mirror of
https://github.com/R0m1k3/xtremflow.git
synced 2026-10-11 17:30:00 +02:00
feat: security hardening, streaming overhaul, design polish, tests
Security: - Replace unsalted SHA-256 password hashing with bcrypt (lazy rehash on login) - Add authenticated /api/xtream-api gateway: Xtream credentials are injected server-side and never sent to the frontend; /api/playlists no longer returns passwords - Redact credentials from all logs (login body, proxy/FFmpeg/scheduler URLs) - Add auth to recordings, EPG, season-passes and streaming routes (HttpOnly session cookie for hls.js; loopback bypass for local FFmpeg) - Lock player postMessage to same-origin in both directions - Vendor and pin hls.js 1.6.7 / mpegts.js 1.7.3 (drop CDN @latest) - Fix rate limiter (client IP was never resolved), add login rate limit, restrict CORS, add CSP Report-Only, block private-IP SSRF targets, fix path traversal in recording log retrieval, chmod 777 -> 770 - Remove dead HiveService (seeded admin/admin into IndexedDB with SHA-256) - Fix authMiddleware not populating 'user' context (getPlaylist ignored the logged-in user; admin purge always returned 403) Streaming: - New FfmpegSessionManager: process registry, idle reaper (4 min live / 15 min VOD), orphan cleanup at startup, clean SIGTERM shutdown, fast-fail with stderr instead of 30 s timeout - Quality selection (source/high/medium/low) for live and VOD; source mode streams with -c:v copy (zero transcoding); selector wired into the player - Concurrent recordings (MAX_CONCURRENT_RECORDINGS, default 2); conflicts retry on the next tick instead of silently failing - Lower live latency (HLS window 20 -> 10 segments, liveSync 10 -> 3) - Fix recording log lookup (.mp4 vs .mkv mismatch) Design: - Replace hardcoded colors with AppColors tokens (12 files) - web/theme.css syncs HTML players with the Flutter palette - DPAD/keyboard navigation (arrow-key focus, player shortcuts) - Tooltips on player icon buttons, Semantics on content cards - Remove 7 dead widgets broken since the Stitch merge Quality: - bin/test/: 21 unit tests (bcrypt, redaction, traversal, SSRF, recording conflicts) plus a quality-selector widget test - GitHub Actions CI (analyze + test + build web) - Archive stale status docs into docs/archive/ Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
1 parent
cb5eca7547
commit
60d3f42901
107 files changed
+4525
-3815
No files matched your search
@@ -23,8 +23,7 @@ class AuthHandler {
|
||||
try {
|
||||
print('[Auth] Login attempt received');
|
||||
final bodyStr = await request.readAsString();
|
||||
print('[Auth] Request body: $bodyStr');
|
||||
|
||||
|
||||
final payload = jsonDecode(bodyStr) as Map<String, dynamic>;
|
||||
final username = payload['username'] as String?;
|
||||
final password = payload['password'] as String?;
|
||||
@@ -51,13 +50,19 @@ class AuthHandler {
|
||||
print('[Auth] User verified, creating session for userId: ${user.id}');
|
||||
// Create session
|
||||
final session = db.createSession(user.id);
|
||||
print('[Auth] Session created with token: ${session.token.substring(0, 8)}...');
|
||||
|
||||
// HttpOnly session cookie so same-origin media requests (hls.js inside
|
||||
// the player iframe cannot send Authorization headers) are authenticated.
|
||||
final maxAge = session.expiresAt.difference(DateTime.now()).inSeconds;
|
||||
return Response.ok(jsonEncode({
|
||||
'success': true,
|
||||
'user': user.toJson(),
|
||||
'token': session.token,
|
||||
}), headers: {'Content-Type': 'application/json'},);
|
||||
}), headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Set-Cookie':
|
||||
'session=${session.token}; HttpOnly; SameSite=Lax; Path=/; Max-Age=$maxAge',
|
||||
},);
|
||||
} catch (e, stackTrace) {
|
||||
print('[Auth] ERROR during login: $e');
|
||||
print('[Auth] Stack trace: $stackTrace');
|
||||
@@ -83,7 +88,10 @@ class AuthHandler {
|
||||
|
||||
return Response.ok(jsonEncode({
|
||||
'success': true,
|
||||
}), headers: {'Content-Type': 'application/json'},);
|
||||
}), headers: {
|
||||
'Content-Type': 'application/json',
|
||||
'Set-Cookie': 'session=; HttpOnly; SameSite=Lax; Path=/; Max-Age=0',
|
||||
},);
|
||||
} catch (e) {
|
||||
return Response.internalServerError(
|
||||
body: jsonEncode({'success': false, 'error': e.toString()}),
|
||||
|
||||
@@ -1,19 +1,17 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../database/database.dart';
|
||||
import '../models/playlist_config.dart';
|
||||
|
||||
/// API EPG — proxy vers Xtream avec cache 30 minutes
|
||||
/// GET /api/epg/<channel_id>?days=1
|
||||
class EpgApi {
|
||||
final AppDatabase _db;
|
||||
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
|
||||
|
||||
// Cache simple en mémoire : channelId → {data, expiresAt}
|
||||
final Map<String, _CacheEntry> _cache = {};
|
||||
|
||||
EpgApi(this._db, this._getPlaylist);
|
||||
EpgApi(this._getPlaylist);
|
||||
|
||||
Future<Response> handleGetEpg(Request request, String channelId) async {
|
||||
// Vérifier le cache
|
||||
|
||||
@@ -120,7 +120,12 @@ class PlaylistsHandler {
|
||||
final name = payload['name'] as String? ?? existing.name;
|
||||
final serverUrl = payload['serverUrl'] as String? ?? existing.serverUrl;
|
||||
final username = payload['username'] as String? ?? existing.username;
|
||||
final password = payload['password'] as String? ?? existing.password;
|
||||
// Empty password means "keep current": clients never receive the real
|
||||
// password, so edit forms send it back blank.
|
||||
final incomingPassword = payload['password'] as String?;
|
||||
final password = (incomingPassword == null || incomingPassword.isEmpty)
|
||||
? existing.password
|
||||
: incomingPassword;
|
||||
final dns = payload['dns'] as String? ?? existing.dns;
|
||||
|
||||
final playlist = db.updatePlaylist(
|
||||
|
||||
+37
-27
@@ -1,14 +1,36 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../models/playlist_config.dart';
|
||||
import '../database/database.dart';
|
||||
import '../utils/log_redactor.dart';
|
||||
|
||||
/// Returns true when [host] must never be proxied (loopback, private LAN,
|
||||
/// link-local/cloud-metadata ranges) — SSRF protection for asset URLs that
|
||||
/// bypass the playlist-domain allowlist.
|
||||
bool isForbiddenProxyHost(String host) {
|
||||
final lower = host.toLowerCase();
|
||||
if (lower == 'localhost' || lower == '::1') return true;
|
||||
|
||||
final ip = InternetAddress.tryParse(lower);
|
||||
if (ip == null) return false; // Hostname: validated by domain allowlist path
|
||||
|
||||
if (ip.isLoopback || ip.isLinkLocal) return true;
|
||||
if (ip.type == InternetAddressType.IPv4) {
|
||||
final parts = ip.address.split('.').map(int.parse).toList();
|
||||
if (parts[0] == 10) return true; // 10.0.0.0/8
|
||||
if (parts[0] == 172 && parts[1] >= 16 && parts[1] <= 31) return true;
|
||||
if (parts[0] == 192 && parts[1] == 168) return true; // 192.168.0.0/16
|
||||
if (parts[0] == 169 && parts[1] == 254) return true; // metadata/link-local
|
||||
if (parts[0] == 0) return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
/// Handler for the Xtream Proxy
|
||||
class ProxyHandler {
|
||||
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
|
||||
final AppDatabase _db;
|
||||
final http.Client _client = http.Client();
|
||||
|
||||
final Map<String, (PlaylistConfig, DateTime)> _playlistCache = {};
|
||||
@@ -48,30 +70,7 @@ class ProxyHandler {
|
||||
return playlist;
|
||||
}
|
||||
|
||||
ProxyHandler(this._getPlaylist, this._db);
|
||||
|
||||
/// Extract token from Authorization header or cookie
|
||||
String? _extractToken(Request request) {
|
||||
// Try Authorization header first
|
||||
final authHeader = request.headers['authorization'];
|
||||
if (authHeader != null && authHeader.startsWith('Bearer ')) {
|
||||
return authHeader.substring(7);
|
||||
}
|
||||
|
||||
// Try cookie
|
||||
final cookie = request.headers['cookie'];
|
||||
if (cookie != null) {
|
||||
final parts = cookie.split(';');
|
||||
for (final part in parts) {
|
||||
final trimmed = part.trim();
|
||||
if (trimmed.startsWith('session=')) {
|
||||
return trimmed.substring(8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return null;
|
||||
}
|
||||
ProxyHandler(this._getPlaylist);
|
||||
|
||||
/// Create Xtream proxy handler with M3U8 URL rewriting support
|
||||
Handler get handler {
|
||||
@@ -118,6 +117,17 @@ class ProxyHandler {
|
||||
|
||||
targetUrl = Uri.parse(fullUrl);
|
||||
|
||||
// Only plain http(s) may be proxied
|
||||
if (targetUrl.scheme != 'http' && targetUrl.scheme != 'https') {
|
||||
return Response.forbidden('Unsupported URL scheme');
|
||||
}
|
||||
|
||||
// Never proxy to loopback/private/link-local targets (SSRF)
|
||||
if (isForbiddenProxyHost(targetUrl.host)) {
|
||||
print('[Proxy] Blocked SSRF attempt to private host: ${targetUrl.host}');
|
||||
return Response.forbidden('Access to this host is forbidden');
|
||||
}
|
||||
|
||||
// SSRF Protection - but allow images/static assets from any host
|
||||
// Xtream providers often use separate CDN servers for picons/images
|
||||
final isStaticAsset = targetUrl.path.endsWith('.png') ||
|
||||
@@ -164,7 +174,7 @@ class ProxyHandler {
|
||||
}
|
||||
|
||||
try {
|
||||
print('[Proxy] Forwarding to: $targetUrl');
|
||||
print('[Proxy] Forwarding to: ${LogRedactor.redactUrl(targetUrl.toString())}');
|
||||
final proxyRequest = http.Request(request.method, targetUrl);
|
||||
|
||||
// Forward safe request headers
|
||||
|
||||
@@ -1,9 +1,11 @@
|
||||
import 'dart:io';
|
||||
import 'dart:convert';
|
||||
import 'package:path/path.dart' as p;
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:shelf_router/shelf_router.dart';
|
||||
import '../database/database.dart';
|
||||
import '../models/user.dart';
|
||||
import '../services/recording_scheduler.dart';
|
||||
import '../utils/safe_path.dart';
|
||||
|
||||
class RecordingsApi {
|
||||
final AppDatabase _db;
|
||||
@@ -30,12 +32,24 @@ class RecordingsApi {
|
||||
);
|
||||
}
|
||||
|
||||
final logFilePath = recording.filePath!.replaceAll('.mp4', '.log');
|
||||
final logFile = File(logFilePath);
|
||||
// Les enregistrements sont écrits en .mkv avec un .log à côté
|
||||
// (l'ancien replaceAll('.mp4', '.log') ne trouvait jamais le fichier).
|
||||
final logFilePath = p.setExtension(recording.filePath!, '.log');
|
||||
|
||||
// Anti path-traversal : le log doit rester dans /app/recordings
|
||||
final safeLogPath = SafePath.resolveWithin('/app/recordings', logFilePath);
|
||||
if (safeLogPath == null) {
|
||||
return Response.forbidden(
|
||||
json.encode({'error': 'Chemin de log invalide'}),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
}
|
||||
|
||||
final logFile = File(safeLogPath);
|
||||
|
||||
if (!await logFile.exists()) {
|
||||
return Response.notFound(
|
||||
json.encode({'error': 'Le fichier de log est introuvable. Chemin: $logFilePath'}),
|
||||
json.encode({'error': 'Le fichier de log est introuvable.'}),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
}
|
||||
@@ -47,9 +61,13 @@ class RecordingsApi {
|
||||
);
|
||||
}
|
||||
|
||||
/// GET /api/recordings — Liste tous les enregistrements
|
||||
/// GET /api/recordings — Liste les enregistrements de l'utilisateur
|
||||
/// (tous les enregistrements pour un admin)
|
||||
Response handleGetAll(Request request) {
|
||||
final recordings = _db.getAllRecordings();
|
||||
final user = request.context['user'] as User?;
|
||||
final recordings = (user != null && !user.isAdmin)
|
||||
? _db.getUserRecordings(user.id)
|
||||
: _db.getAllRecordings();
|
||||
return Response.ok(
|
||||
json.encode(recordings.map((r) => r.toMap()).toList()),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
@@ -62,8 +80,9 @@ class RecordingsApi {
|
||||
final payload = await request.readAsString();
|
||||
final data = json.decode(payload);
|
||||
|
||||
final userId = request.context['userId'] as String? ?? 'dev_user_id';
|
||||
final recording = _db.createRecording(
|
||||
userId: 'dev_user_id',
|
||||
userId: userId,
|
||||
channelId: data['channel_id'],
|
||||
streamUrl: data['stream_url'],
|
||||
title: data['title'] ?? 'Sans Titre',
|
||||
|
||||
+332
-506
@@ -1,20 +1,19 @@
|
||||
import 'dart:async';
|
||||
import 'dart:convert';
|
||||
import 'dart:io';
|
||||
import 'dart:math';
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:shelf_router/shelf_router.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../database/database.dart';
|
||||
import '../models/playlist_config.dart';
|
||||
|
||||
/// Active FFmpeg processes for VOD transcoding
|
||||
final Map<String, Process> _vodProcesses = {};
|
||||
import '../services/ffmpeg_session_manager.dart';
|
||||
import '../utils/log_redactor.dart';
|
||||
|
||||
/// Directory for temporary HLS segments
|
||||
final Directory _hlsTempDir =
|
||||
Directory('${Directory.systemTemp.path}/xtremflow_streams');
|
||||
|
||||
/// Global FFmpeg session registry (initialized in [initStreaming]).
|
||||
final FfmpegSessionManager sessionManager = FfmpegSessionManager(_hlsTempDir);
|
||||
|
||||
/// Helper to resolve FFmpeg path (SYSTEM PATH vs Portable)
|
||||
String _getFFmpegPath() {
|
||||
if (Platform.isWindows) {
|
||||
@@ -35,91 +34,149 @@ bool _isNvidiaGpuEnabled() {
|
||||
return envValue.toLowerCase() == 'true' || envValue == '1';
|
||||
}
|
||||
|
||||
/// Log GPU status on first use
|
||||
bool _gpuStatusLogged = false;
|
||||
void _logGpuStatus() {
|
||||
if (!_gpuStatusLogged) {
|
||||
if (_isNvidiaGpuEnabled()) {
|
||||
print('[FFmpeg] NVIDIA GPU acceleration ENABLED (NVDEC/NVENC)');
|
||||
} else {
|
||||
print(
|
||||
'[FFmpeg] Using CPU processing (set NVIDIA_GPU=true to enable GPU)',
|
||||
);
|
||||
}
|
||||
_gpuStatusLogged = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Initialize streaming subsystem
|
||||
Future<void> initStreaming() async {
|
||||
if (!_hlsTempDir.existsSync()) {
|
||||
await _hlsTempDir.create(recursive: true);
|
||||
await sessionManager.init();
|
||||
}
|
||||
|
||||
/// Supported quality presets. `source` skips video transcoding entirely
|
||||
/// (`-c:v copy`) — a huge CPU win since most Xtream streams are already
|
||||
/// H.264. Audio is always normalized to AAC for HLS compatibility.
|
||||
const supportedQualities = {'source', 'high', 'medium', 'low'};
|
||||
|
||||
String _sanitizeQuality(String? quality) {
|
||||
return supportedQualities.contains(quality) ? quality! : 'high';
|
||||
}
|
||||
|
||||
bool _isValidStreamId(String id) => RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(id);
|
||||
|
||||
/// Video encoding args for the requested quality (live profile).
|
||||
List<String> _liveVideoArgs(String quality, bool gpu) {
|
||||
switch (quality) {
|
||||
case 'source':
|
||||
return ['-c:v', 'copy'];
|
||||
case 'medium':
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
|
||||
'-b:v', '3000k', '-maxrate', '4500k', '-bufsize', '6000k',
|
||||
'-profile:v', 'high', '-level', '4.0', '-pix_fmt', 'yuv420p',
|
||||
'-g', '50',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
|
||||
'-profile:v', 'high', '-level', '4.0',
|
||||
'-b:v', '3000k', '-maxrate', '4500k', '-bufsize', '6000k',
|
||||
'-pix_fmt', 'yuv420p', '-g', '50',
|
||||
];
|
||||
case 'low':
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4',
|
||||
'-b:v', '1500k', '-maxrate', '2000k', '-bufsize', '3000k',
|
||||
'-vf', 'scale=-2:720',
|
||||
'-pix_fmt', 'yuv420p', '-g', '50',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'veryfast', '-tune', 'zerolatency',
|
||||
'-b:v', '1500k', '-maxrate', '2000k', '-bufsize', '3000k',
|
||||
'-vf', 'scale=-2:720',
|
||||
'-pix_fmt', 'yuv420p', '-g', '50',
|
||||
];
|
||||
case 'high':
|
||||
default:
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
|
||||
'-b:v', '8000k', '-maxrate', '12000k', '-bufsize', '16000k',
|
||||
'-profile:v', 'high', '-level', '4.0', '-pix_fmt', 'yuv420p',
|
||||
'-g', '50',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-tune', 'zerolatency',
|
||||
'-profile:v', 'high', '-level', '4.0',
|
||||
'-b:v', '6000k', '-maxrate', '8000k', '-bufsize', '12000k',
|
||||
'-pix_fmt', 'yuv420p', '-g', '50',
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
/// Helper to resolve HTTP redirects and get final URL
|
||||
/// Some IPTV servers return 302 redirects that FFmpeg doesn't follow properly
|
||||
Future<String> _resolveRedirects(String url, {int maxRedirects = 5}) async {
|
||||
String currentUrl = url;
|
||||
final client = http.Client();
|
||||
|
||||
try {
|
||||
for (int i = 0; i < maxRedirects; i++) {
|
||||
final request = http.Request('GET', Uri.parse(currentUrl));
|
||||
request.headers['User-Agent'] = 'VLC/3.0.18 LibVLC/3.0.18';
|
||||
request.followRedirects = false;
|
||||
|
||||
final response = await client.send(request).timeout(
|
||||
const Duration(seconds: 30),
|
||||
onTimeout: () =>
|
||||
throw TimeoutException('Redirect resolution timeout'),
|
||||
);
|
||||
|
||||
// Check if it's a redirect (301, 302, 307, 308)
|
||||
if (response.statusCode >= 300 && response.statusCode < 400) {
|
||||
final location = response.headers['location'];
|
||||
if (location != null && location.isNotEmpty) {
|
||||
// Handle relative URLs
|
||||
if (location.startsWith('/')) {
|
||||
final uri = Uri.parse(currentUrl);
|
||||
currentUrl = '${uri.scheme}://${uri.host}:${uri.port}$location';
|
||||
} else {
|
||||
currentUrl = location;
|
||||
}
|
||||
print('[Redirect] $i: $url -> $currentUrl');
|
||||
await response.stream.drain();
|
||||
continue;
|
||||
}
|
||||
}
|
||||
|
||||
// Not a redirect - we're done
|
||||
await response.stream.drain();
|
||||
break;
|
||||
}
|
||||
} catch (e) {
|
||||
print('[Redirect] Error resolving redirects: $e');
|
||||
// Return original URL if redirect resolution fails
|
||||
} finally {
|
||||
client.close();
|
||||
/// Video encoding args for the requested quality (VOD profile).
|
||||
List<String> _vodVideoArgs(String quality, bool gpu) {
|
||||
switch (quality) {
|
||||
case 'source':
|
||||
return ['-c:v', 'copy'];
|
||||
case 'medium':
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
|
||||
'-rc', 'cbr', '-b:v', '2500k', '-maxrate', '3000k',
|
||||
'-bufsize', '5000k', '-g', '48', '-bf', '2',
|
||||
'-pix_fmt', 'yuv420p',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'fast', '-crf', '23',
|
||||
'-maxrate', '6000k', '-bufsize', '12000k',
|
||||
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
|
||||
];
|
||||
case 'low':
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4',
|
||||
'-rc', 'cbr', '-b:v', '1500k', '-maxrate', '2000k',
|
||||
'-bufsize', '3000k', '-vf', 'scale=-2:720',
|
||||
'-g', '48', '-pix_fmt', 'yuv420p',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'fast', '-crf', '26',
|
||||
'-maxrate', '3000k', '-bufsize', '6000k',
|
||||
'-vf', 'scale=-2:720',
|
||||
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
|
||||
];
|
||||
case 'high':
|
||||
default:
|
||||
return gpu
|
||||
? [
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
|
||||
'-rc', 'cbr', '-b:v', '4000k', '-maxrate', '4500k',
|
||||
'-bufsize', '8000k', '-g', '48', '-bf', '2',
|
||||
'-pix_fmt', 'yuv420p',
|
||||
]
|
||||
: [
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-maxrate', '12000k', '-bufsize', '24000k',
|
||||
'-pix_fmt', 'yuv420p', '-g', '48', '-threads', '0',
|
||||
];
|
||||
}
|
||||
|
||||
return currentUrl;
|
||||
}
|
||||
|
||||
/// Helper to get current playlist configuration (mocked for now, implies single user)
|
||||
/// In a real scenario, this should come from the request session/context
|
||||
PlaylistConfig? _getCurrentPlaylist(Request request) {
|
||||
// TODO: Retrieve from DB/Session based on Auth
|
||||
// For now, we assume the frontend sends enough info or we look up the active one
|
||||
return null; // Implemented later in server.dart injection
|
||||
/// Audio args. Source mode keeps it simple (plain AAC); transcoded modes
|
||||
/// keep the downmix + loudness normalization filter.
|
||||
List<String> _audioArgs({required bool withFilters}) {
|
||||
return [
|
||||
'-c:a', 'aac', '-b:a', '192k', '-ac', '2', '-ar', '48000',
|
||||
if (withFilters)
|
||||
...['-af',
|
||||
'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15']
|
||||
else
|
||||
...['-af', 'aresample=async=1'],
|
||||
];
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 1. LIVE TV HANDLER (Direct MPEG-TS Proxy)
|
||||
// ==========================================
|
||||
Map<String, String> _hlsHeaders() => {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl',
|
||||
'Cache-Control': 'no-cache',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
};
|
||||
|
||||
/// Active FFmpeg processes for Live HLS transcoding
|
||||
final Map<String, Process> _liveProcesses = {};
|
||||
Map<String, String> _segmentHeaders({int maxAge = 60}) => {
|
||||
'Content-Type': 'video/mp2t',
|
||||
'Cache-Control': 'max-age=$maxAge',
|
||||
};
|
||||
|
||||
// ==========================================
|
||||
// 1. LIVE TV HANDLER (FFmpeg HLS + direct TS proxy)
|
||||
// ==========================================
|
||||
|
||||
Handler createLiveStreamHandler(
|
||||
Future<PlaylistConfig?> Function(Request) getPlaylist, {
|
||||
@@ -127,109 +184,89 @@ Handler createLiveStreamHandler(
|
||||
}) {
|
||||
final router = Router();
|
||||
|
||||
// Route: /api/live/{streamId}/playlist.m3u8 (Master playlist)
|
||||
router.get('/<streamId>/playlist.m3u8',
|
||||
(Request request, String streamId) async {
|
||||
Future<Response> servePlaylist(
|
||||
Request request,
|
||||
String streamId,
|
||||
String quality,
|
||||
) async {
|
||||
if (!_isValidStreamId(streamId)) {
|
||||
return Response.badRequest(body: 'Invalid stream ID');
|
||||
}
|
||||
final playlist = await getPlaylist(request);
|
||||
if (playlist == null) return Response.forbidden('No playlist');
|
||||
|
||||
final streamDir = Directory('${_hlsTempDir.path}/live_$streamId');
|
||||
final targetUrl =
|
||||
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
final sessionId = 'live_${streamId}_$quality';
|
||||
|
||||
// Start FFmpeg if not already running for this live stream
|
||||
if (!_liveProcesses.containsKey(streamId)) {
|
||||
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
|
||||
streamDir.createSync(recursive: true);
|
||||
if (!sessionManager.contains(sessionId)) {
|
||||
print(
|
||||
'[Live HLS] Starting $sessionId: ${LogRedactor.redactUrl(targetUrl)}',
|
||||
);
|
||||
}
|
||||
|
||||
final targetUrl =
|
||||
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
|
||||
print('[Live HLS] Starting for $streamId: $targetUrl');
|
||||
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
final ffmpegArgs = <String>[
|
||||
final session = await sessionManager.getOrStart(
|
||||
id: sessionId,
|
||||
isLive: true,
|
||||
ffmpegPath: _getFFmpegPath(),
|
||||
argsBuilder: (dir) => [
|
||||
'-hide_banner', '-loglevel', 'warning',
|
||||
if (useNvidiaGpu) ...['-hwaccel', 'cuda'],
|
||||
if (useNvidiaGpu && quality != 'source') ...['-hwaccel', 'cuda'],
|
||||
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
|
||||
'-reconnect', '1', '-reconnect_streamed', '1',
|
||||
'-reconnect_delay_max', '10',
|
||||
'-i', targetUrl,
|
||||
// Video
|
||||
if (useNvidiaGpu) ...[
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune',
|
||||
'hq',
|
||||
'-b:v', '8000k', '-maxrate', '12000k', '-bufsize', '16000k',
|
||||
'-profile:v', 'high', '-level', '4.0',
|
||||
'-pix_fmt', 'yuv420p',
|
||||
'-g', '50',
|
||||
] else ...[
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-tune', 'zerolatency',
|
||||
'-profile:v', 'high', '-level', '4.0',
|
||||
'-b:v', '6000k', '-maxrate', '8000k', '-bufsize', '12000k',
|
||||
'-pix_fmt', 'yuv420p',
|
||||
'-g', '50',
|
||||
],
|
||||
// Audio: High quality + Sync filter
|
||||
'-c:a', 'aac', '-b:a', '192k', '-ac', '2', '-ar', '48000',
|
||||
'-af', 'aresample=async=1',
|
||||
// HLS Sliding Window — larger window so iOS never requests a deleted segment
|
||||
..._liveVideoArgs(quality, useNvidiaGpu),
|
||||
..._audioArgs(withFilters: false),
|
||||
// HLS sliding window: 10 x 2s segments (lower live latency than the
|
||||
// previous 20-segment window while still safe for iOS)
|
||||
'-f', 'hls',
|
||||
'-hls_time', '2',
|
||||
'-hls_list_size', '20',
|
||||
'-hls_list_size', '10',
|
||||
'-hls_flags', 'delete_segments+independent_segments',
|
||||
'-hls_segment_type', 'mpegts',
|
||||
'-hls_segment_filename', 'seg_%03d.ts',
|
||||
'playlist.m3u8',
|
||||
];
|
||||
|
||||
final process = await Process.start(
|
||||
_getFFmpegPath(),
|
||||
ffmpegArgs,
|
||||
workingDirectory: streamDir.path,
|
||||
);
|
||||
_liveProcesses[streamId] = process;
|
||||
|
||||
process.stderr
|
||||
.transform(utf8.decoder)
|
||||
.listen((d) => print('[Live HLS $streamId] $d'));
|
||||
process.exitCode.then((_) => _liveProcesses.remove(streamId));
|
||||
}
|
||||
|
||||
// Wait for playlist AND at least one segment reference
|
||||
final file = File('${streamDir.path}/playlist.m3u8');
|
||||
int retries = 0;
|
||||
while (retries < 60) {
|
||||
if (file.existsSync()) {
|
||||
final content = file.readAsStringSync();
|
||||
// Live HLS needs at least 2 or 3 segments to be stable on iOS
|
||||
// but we start as soon as we have one for speed
|
||||
if (content.contains('.ts')) break;
|
||||
}
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
retries++;
|
||||
}
|
||||
|
||||
if (!file.existsSync()) {
|
||||
return Response.internalServerError(body: 'Timeout starting live HLS');
|
||||
}
|
||||
|
||||
return Response.ok(
|
||||
file.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-cache',
|
||||
'X-Content-Type-Options': 'nosniff',
|
||||
},
|
||||
],
|
||||
);
|
||||
|
||||
final result = await sessionManager.waitForPlaylist(session);
|
||||
if (!result.ready) {
|
||||
sessionManager.killSession(sessionId);
|
||||
return Response(502, body: 'Live transcoder failed: ${result.error}');
|
||||
}
|
||||
|
||||
session.touch();
|
||||
return Response.ok(
|
||||
File('${session.dir.path}/playlist.m3u8').openRead(),
|
||||
headers: _hlsHeaders(),
|
||||
);
|
||||
}
|
||||
|
||||
// Route: /api/live/{streamId}/{quality}/playlist.m3u8
|
||||
router.get('/<streamId>/<quality>/playlist.m3u8',
|
||||
(Request request, String streamId, String quality) {
|
||||
return servePlaylist(request, streamId, _sanitizeQuality(quality));
|
||||
});
|
||||
|
||||
// Route: /api/live/{streamId}.ts (Direct Proxy for internal recordings or raw playback)
|
||||
// Back-compat route: /api/live/{streamId}/playlist.m3u8 (?quality=...)
|
||||
// Redirects so relative segment URLs resolve inside the quality path.
|
||||
router.get('/<streamId>/playlist.m3u8',
|
||||
(Request request, String streamId) async {
|
||||
final quality =
|
||||
_sanitizeQuality(request.url.queryParameters['quality']);
|
||||
return Response.found('/api/live/$streamId/$quality/playlist.m3u8');
|
||||
});
|
||||
|
||||
// Route: /api/live/{streamId}.ts (Direct Proxy for recordings/raw playback)
|
||||
router.get('/<streamId>.ts', (Request request, String streamId) async {
|
||||
final playlist = await getPlaylist(request);
|
||||
if (playlist == null) return Response.forbidden('No playlist');
|
||||
|
||||
final targetUrl =
|
||||
'${playlist.dns}/live/${playlist.username}/${playlist.password}/$streamId.ts';
|
||||
print('[Live Proxy] Forwarding $streamId: $targetUrl');
|
||||
print('[Live Proxy] Forwarding $streamId: ${LogRedactor.redactUrl(targetUrl)}');
|
||||
|
||||
final client = http.Client();
|
||||
final proxyRequest = http.Request('GET', Uri.parse(targetUrl));
|
||||
@@ -243,313 +280,143 @@ Handler createLiveStreamHandler(
|
||||
body: response.stream,
|
||||
headers: {
|
||||
'Content-Type': 'video/mp2t',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Connection': 'keep-alive',
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
// Route: /api/live/{streamId}/{segment}
|
||||
router.get('/<streamId>/<segment>',
|
||||
(Request request, String streamId, String segment) async {
|
||||
final file = File('${_hlsTempDir.path}/live_$streamId/$segment');
|
||||
// Route: /api/live/{streamId}/{quality}/{segment}
|
||||
router.get('/<streamId>/<quality>/<segment>',
|
||||
(Request request, String streamId, String quality, String segment) {
|
||||
if (!_isValidStreamId(streamId) || segment.contains('..')) {
|
||||
return Response.badRequest(body: 'Invalid request');
|
||||
}
|
||||
final sessionId = 'live_${streamId}_${_sanitizeQuality(quality)}';
|
||||
sessionManager.touch(sessionId);
|
||||
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
|
||||
if (!file.existsSync()) return Response.notFound('Segment not found');
|
||||
|
||||
return Response.ok(
|
||||
file.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'video/mp2t',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'max-age=60',
|
||||
},
|
||||
);
|
||||
return Response.ok(file.openRead(), headers: _segmentHeaders());
|
||||
});
|
||||
|
||||
return router;
|
||||
return router.call;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
// 2. VOD HANDLER (FFmpeg HLS Transcoding)
|
||||
// ==========================================
|
||||
|
||||
// ==========================================
|
||||
// 2. VOD HANDLER (FFmpeg HLS Transcoding)
|
||||
// ==========================================
|
||||
|
||||
final _lastLogTime = <String, int>{};
|
||||
|
||||
Handler createVodStreamHandler(
|
||||
Future<PlaylistConfig?> Function(Request) getPlaylist, {
|
||||
bool Function()? isGpuEnabled,
|
||||
}) {
|
||||
final router = Router();
|
||||
|
||||
// Route: /api/vod/{streamId}/playlist.m3u8
|
||||
router.get('/<streamId>/playlist.m3u8',
|
||||
(Request request, String streamId) async {
|
||||
Future<Response> servePlaylist(
|
||||
Request request,
|
||||
String streamId,
|
||||
String quality,
|
||||
) async {
|
||||
if (!_isValidStreamId(streamId)) {
|
||||
return Response.badRequest(body: 'Invalid stream ID');
|
||||
}
|
||||
final playlist = await getPlaylist(request);
|
||||
if (playlist == null) {
|
||||
return Response.internalServerError(body: 'No playlist');
|
||||
}
|
||||
|
||||
// Validate streamId to prevent Path Traversal
|
||||
if (!RegExp(r'^[a-zA-Z0-9_-]+$').hasMatch(streamId)) {
|
||||
return Response.badRequest(body: 'Invalid stream ID');
|
||||
}
|
||||
|
||||
final streamDir = Directory('${_hlsTempDir.path}/$streamId');
|
||||
|
||||
// Check if existing session is healthy
|
||||
if (_vodProcesses.containsKey(streamId)) {
|
||||
final existingProcess = _vodProcesses[streamId]!;
|
||||
|
||||
// Check if process is still running by checking if playlist exists and has content
|
||||
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
||||
if (playlistFile.existsSync()) {
|
||||
final content = playlistFile.readAsStringSync();
|
||||
// Check if playlist has segments (healthy transcoding)
|
||||
if (content.contains('.ts')) {
|
||||
// Only log once per second to avoid spam
|
||||
final now = DateTime.now().millisecondsSinceEpoch;
|
||||
if (!_lastLogTime.containsKey(streamId) ||
|
||||
(now - _lastLogTime[streamId]! > 2000)) {
|
||||
print('[VOD] Reusing existing session for $streamId');
|
||||
_lastLogTime[streamId] = now;
|
||||
}
|
||||
// Serve existing playlist
|
||||
return Response.ok(
|
||||
playlistFile.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
// Playlist missing or empty - process likely failed, clean up
|
||||
print('[VOD] Cleaning up stale session for $streamId');
|
||||
try {
|
||||
existingProcess.kill();
|
||||
} catch (e) {
|
||||
// Process may already be dead
|
||||
}
|
||||
_vodProcesses.remove(streamId);
|
||||
|
||||
// Clean up directory
|
||||
if (streamDir.existsSync()) {
|
||||
try {
|
||||
streamDir.deleteSync(recursive: true);
|
||||
} catch (e) {
|
||||
print('[VOD] Failed to clean directory: $e');
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Build Upstream URL based on content type
|
||||
// Check for type parameter in request URL (?type=series or ?type=movie)
|
||||
// ?type=series or ?type=movie selects the upstream path
|
||||
final contentType = request.url.queryParameters['type'] ?? 'movie';
|
||||
final basePath = contentType == 'series' ? 'series' : 'movie';
|
||||
|
||||
// Only start FFmpeg if not already running
|
||||
if (!_vodProcesses.containsKey(streamId)) {
|
||||
// Prepare directory (Only for new session)
|
||||
if (streamDir.existsSync()) {
|
||||
streamDir.deleteSync(recursive: true);
|
||||
}
|
||||
streamDir.createSync(recursive: true);
|
||||
final targetUrl =
|
||||
'${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.mkv';
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
final sessionId = 'vod_${streamId}_$quality';
|
||||
|
||||
final targetUrl =
|
||||
'${playlist.dns}/$basePath/${playlist.username}/${playlist.password}/$streamId.mkv';
|
||||
print('[VOD] Starting Transcode ($contentType): $targetUrl');
|
||||
|
||||
// Check if NVIDIA GPU is enabled (from database setting or env var fallback)
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
|
||||
if (useNvidiaGpu) {
|
||||
print('[VOD] Using NVIDIA GPU acceleration (NVENC)');
|
||||
}
|
||||
|
||||
// Build FFmpeg arguments
|
||||
final ffmpegArgs = <String>[
|
||||
'-hide_banner',
|
||||
'-loglevel',
|
||||
'warning',
|
||||
];
|
||||
|
||||
// NVIDIA GPU Hardware Acceleration
|
||||
if (useNvidiaGpu) {
|
||||
ffmpegArgs.addAll([
|
||||
'-hwaccel', 'cuda',
|
||||
// Note: Don't use hwaccel_output_format cuda - it can cause issues
|
||||
]);
|
||||
}
|
||||
|
||||
// Input and robustness flags
|
||||
ffmpegArgs.addAll([
|
||||
'-headers',
|
||||
'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
|
||||
'-reconnect',
|
||||
'1',
|
||||
'-reconnect_at_eof',
|
||||
'1',
|
||||
'-reconnect_streamed',
|
||||
'1',
|
||||
'-reconnect_delay_max',
|
||||
'10',
|
||||
'-rw_timeout',
|
||||
'30000000',
|
||||
'-timeout',
|
||||
'30000000',
|
||||
'-analyzeduration',
|
||||
'5000000',
|
||||
'-probesize',
|
||||
'10000000',
|
||||
'-i',
|
||||
targetUrl,
|
||||
]);
|
||||
|
||||
// Video encoding (GPU or CPU)
|
||||
if (useNvidiaGpu) {
|
||||
// NVIDIA NVENC - Hardware encoding (50x+ faster, much lower CPU)
|
||||
ffmpegArgs.addAll([
|
||||
'-c:v', 'h264_nvenc', // Use NVIDIA NVENC encoder
|
||||
'-preset', 'p4', // Good quality/speed balance
|
||||
'-tune', 'hq', // High quality mode
|
||||
'-rc', 'cbr', // Constant bitrate for HLS
|
||||
'-b:v', '4000k', // Target bitrate
|
||||
'-maxrate', '4500k',
|
||||
'-bufsize', '8000k',
|
||||
'-g', '48', // Keyframe every 2 seconds
|
||||
'-bf', '2', // B-frames for quality
|
||||
'-pix_fmt', 'yuv420p',
|
||||
]);
|
||||
} else {
|
||||
// CPU encoding (libx264)
|
||||
ffmpegArgs.addAll([
|
||||
'-c:v',
|
||||
'libx264',
|
||||
'-preset',
|
||||
'medium', // Quality over raw speed for VOD
|
||||
'-crf',
|
||||
'18', // Near-native visual quality
|
||||
'-maxrate',
|
||||
'12000k',
|
||||
'-bufsize',
|
||||
'24000k',
|
||||
'-pix_fmt',
|
||||
'yuv420p',
|
||||
'-g', '48',
|
||||
'-threads',
|
||||
'0',
|
||||
]);
|
||||
}
|
||||
|
||||
// Audio encoding (same for both)
|
||||
ffmpegArgs.addAll([
|
||||
'-c:a',
|
||||
'aac',
|
||||
'-b:a',
|
||||
'192k',
|
||||
'-ar',
|
||||
'48000',
|
||||
'-af',
|
||||
'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15',
|
||||
]);
|
||||
|
||||
// HLS output settings
|
||||
ffmpegArgs.addAll([
|
||||
'-f',
|
||||
'hls',
|
||||
'-hls_time',
|
||||
'4',
|
||||
'-hls_list_size',
|
||||
'0',
|
||||
'-hls_playlist_type',
|
||||
'event',
|
||||
'-hls_allow_cache',
|
||||
'1',
|
||||
'-hls_flags',
|
||||
'independent_segments',
|
||||
'-hls_segment_type',
|
||||
'mpegts',
|
||||
'-hls_segment_filename',
|
||||
'segment_%03d.ts',
|
||||
'-start_number',
|
||||
'0',
|
||||
'playlist.m3u8',
|
||||
]);
|
||||
|
||||
final ffmpegPath = _getFFmpegPath();
|
||||
Process.start(
|
||||
ffmpegPath,
|
||||
ffmpegArgs,
|
||||
workingDirectory: streamDir.path,
|
||||
).then((process) {
|
||||
_vodProcesses[streamId] = process;
|
||||
|
||||
process.stderr.transform(utf8.decoder).listen((data) {
|
||||
// Log only major errors or startup info to keep logs clean(er)
|
||||
// or keep verbose if debugging
|
||||
print('[FFmpeg $streamId] $data');
|
||||
});
|
||||
|
||||
process.exitCode.then((code) {
|
||||
print('[VOD] FFmpeg exited with code $code');
|
||||
_vodProcesses.remove(streamId);
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
// Wait for playlist AND at least one segment to be referenced
|
||||
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
||||
int retries = 0;
|
||||
while (retries < 60) {
|
||||
if (playlistFile.existsSync()) {
|
||||
final content = playlistFile.readAsStringSync();
|
||||
if (content.contains('.ts')) break; // At least one segment is ready
|
||||
}
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
retries++;
|
||||
}
|
||||
|
||||
if (!playlistFile.existsSync()) {
|
||||
return Response.internalServerError(
|
||||
body: 'Timeout waiting for transcoder',
|
||||
if (!sessionManager.contains(sessionId)) {
|
||||
print(
|
||||
'[VOD] Starting $sessionId ($contentType): ${LogRedactor.redactUrl(targetUrl)}',
|
||||
);
|
||||
}
|
||||
|
||||
return Response.ok(
|
||||
playlistFile.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl', // Correct HLS Mime
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
final session = await sessionManager.getOrStart(
|
||||
id: sessionId,
|
||||
isLive: false,
|
||||
ffmpegPath: _getFFmpegPath(),
|
||||
argsBuilder: (dir) => [
|
||||
'-hide_banner', '-loglevel', 'warning',
|
||||
if (useNvidiaGpu && quality != 'source') ...['-hwaccel', 'cuda'],
|
||||
'-headers', 'User-Agent: VLC/3.0.18 LibVLC/3.0.18\r\n',
|
||||
'-reconnect', '1',
|
||||
'-reconnect_at_eof', '1',
|
||||
'-reconnect_streamed', '1',
|
||||
'-reconnect_delay_max', '10',
|
||||
'-rw_timeout', '30000000',
|
||||
'-timeout', '30000000',
|
||||
'-analyzeduration', '5000000',
|
||||
'-probesize', '10000000',
|
||||
'-i', targetUrl,
|
||||
..._vodVideoArgs(quality, useNvidiaGpu),
|
||||
..._audioArgs(withFilters: quality != 'source'),
|
||||
'-f', 'hls',
|
||||
'-hls_time', '4',
|
||||
'-hls_list_size', '0',
|
||||
'-hls_playlist_type', 'event',
|
||||
'-hls_allow_cache', '1',
|
||||
'-hls_flags', 'independent_segments',
|
||||
'-hls_segment_type', 'mpegts',
|
||||
'-hls_segment_filename', 'segment_%03d.ts',
|
||||
'-start_number', '0',
|
||||
'playlist.m3u8',
|
||||
],
|
||||
);
|
||||
});
|
||||
|
||||
// Route: /api/vod/{streamId}/segment_{n}.ts (Serve segments)
|
||||
router.get('/<streamId>/<segment>',
|
||||
(Request request, String streamId, String segment) async {
|
||||
final file = File('${_hlsTempDir.path}/$streamId/$segment');
|
||||
|
||||
if (!file.existsSync()) {
|
||||
return Response.notFound('Segment not found');
|
||||
final result = await sessionManager.waitForPlaylist(session);
|
||||
if (!result.ready) {
|
||||
sessionManager.killSession(sessionId);
|
||||
return Response(502, body: 'VOD transcoder failed: ${result.error}');
|
||||
}
|
||||
|
||||
session.touch();
|
||||
return Response.ok(
|
||||
file.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'video/mp2t',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'max-age=3600', // Cache segments
|
||||
},
|
||||
File('${session.dir.path}/playlist.m3u8').openRead(),
|
||||
headers: _hlsHeaders(),
|
||||
);
|
||||
}
|
||||
|
||||
// Route: /api/vod/{streamId}/{quality}/playlist.m3u8
|
||||
router.get('/<streamId>/<quality>/playlist.m3u8',
|
||||
(Request request, String streamId, String quality) {
|
||||
return servePlaylist(request, streamId, _sanitizeQuality(quality));
|
||||
});
|
||||
|
||||
return router;
|
||||
// Back-compat route: /api/vod/{streamId}/playlist.m3u8 (?quality=...)
|
||||
router.get('/<streamId>/playlist.m3u8',
|
||||
(Request request, String streamId) async {
|
||||
final quality =
|
||||
_sanitizeQuality(request.url.queryParameters['quality']);
|
||||
final query = request.url.queryParameters['type'] != null
|
||||
? '?type=${request.url.queryParameters['type']}'
|
||||
: '';
|
||||
return Response.found('/api/vod/$streamId/$quality/playlist.m3u8$query');
|
||||
});
|
||||
|
||||
// Route: /api/vod/{streamId}/{quality}/{segment}
|
||||
router.get('/<streamId>/<quality>/<segment>',
|
||||
(Request request, String streamId, String quality, String segment) {
|
||||
if (!_isValidStreamId(streamId) || segment.contains('..')) {
|
||||
return Response.badRequest(body: 'Invalid request');
|
||||
}
|
||||
final sessionId = 'vod_${streamId}_${_sanitizeQuality(quality)}';
|
||||
sessionManager.touch(sessionId);
|
||||
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
|
||||
if (!file.existsSync()) return Response.notFound('Segment not found');
|
||||
|
||||
return Response.ok(file.openRead(), headers: _segmentHeaders(maxAge: 3600));
|
||||
});
|
||||
|
||||
return router.call;
|
||||
}
|
||||
|
||||
// ==========================================
|
||||
@@ -562,7 +429,8 @@ Handler createRecordingStreamHandler(
|
||||
}) {
|
||||
final router = Router();
|
||||
|
||||
router.get('/<streamId>/playlist.m3u8', (Request request, String streamId) async {
|
||||
router.get('/<streamId>/playlist.m3u8',
|
||||
(Request request, String streamId) async {
|
||||
final recording = db.getRecordingById(streamId);
|
||||
if (recording == null) {
|
||||
return Response.notFound('Recording not found');
|
||||
@@ -573,121 +441,79 @@ Handler createRecordingStreamHandler(
|
||||
return Response(202, body: 'Recording not yet started');
|
||||
}
|
||||
if (recording.status == 'failed') {
|
||||
return Response(422, body: 'Recording failed: ${recording.errorReason ?? 'unknown error'}');
|
||||
return Response(422,
|
||||
body: 'Recording failed: ${recording.errorReason ?? 'unknown error'}');
|
||||
}
|
||||
if (recording.status != 'completed' && recording.status != 'recording') {
|
||||
return Response.internalServerError(body: 'Invalid recording status: ${recording.status}');
|
||||
return Response.internalServerError(
|
||||
body: 'Invalid recording status: ${recording.status}');
|
||||
}
|
||||
|
||||
// Check file path and existence
|
||||
if (recording.filePath == null) {
|
||||
return Response.internalServerError(body: 'Recording file path not set');
|
||||
}
|
||||
|
||||
final targetUrl = recording.filePath!;
|
||||
if (!File(targetUrl).existsSync()) {
|
||||
return Response.internalServerError(body: 'Physical recording file not found: $targetUrl');
|
||||
return Response.internalServerError(
|
||||
body: 'Physical recording file not found');
|
||||
}
|
||||
|
||||
final streamDir = Directory('${_hlsTempDir.path}/rec_$streamId');
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
final sessionId = 'rec_$streamId';
|
||||
|
||||
if (_vodProcesses.containsKey('rec_$streamId')) {
|
||||
final existingProcess = _vodProcesses['rec_$streamId']!;
|
||||
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
||||
|
||||
if (playlistFile.existsSync() && playlistFile.readAsStringSync().contains('.ts')) {
|
||||
return Response.ok(
|
||||
playlistFile.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
try { existingProcess.kill(); } catch (_) {}
|
||||
_vodProcesses.remove('rec_$streamId');
|
||||
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
|
||||
}
|
||||
|
||||
if (!_vodProcesses.containsKey('rec_$streamId')) {
|
||||
if (streamDir.existsSync()) streamDir.deleteSync(recursive: true);
|
||||
streamDir.createSync(recursive: true);
|
||||
|
||||
final useNvidiaGpu = isGpuEnabled?.call() ?? _isNvidiaGpuEnabled();
|
||||
|
||||
final ffmpegArgs = <String>[
|
||||
final session = await sessionManager.getOrStart(
|
||||
id: sessionId,
|
||||
isLive: false,
|
||||
ffmpegPath: _getFFmpegPath(),
|
||||
argsBuilder: (dir) => [
|
||||
'-hide_banner', '-loglevel', 'warning',
|
||||
if (useNvidiaGpu) ...['-hwaccel', 'cuda'],
|
||||
'-i', targetUrl,
|
||||
];
|
||||
|
||||
if (useNvidiaGpu) {
|
||||
ffmpegArgs.addAll([
|
||||
if (useNvidiaGpu) ...[
|
||||
'-c:v', 'h264_nvenc', '-preset', 'p4', '-tune', 'hq',
|
||||
'-rc', 'cbr', '-b:v', '3000k', '-maxrate', '3500k', '-bufsize', '6000k',
|
||||
'-rc', 'cbr', '-b:v', '3000k', '-maxrate', '3500k',
|
||||
'-bufsize', '6000k',
|
||||
'-g', '48', '-bf', '2', '-pix_fmt', 'yuv420p',
|
||||
]);
|
||||
} else {
|
||||
ffmpegArgs.addAll([
|
||||
] else ...[
|
||||
'-c:v', 'libx264', '-preset', 'medium', '-crf', '18',
|
||||
'-maxrate', '12000k', '-bufsize', '24000k', '-pix_fmt', 'yuv420p',
|
||||
'-g', '48', '-threads', '0',
|
||||
]);
|
||||
}
|
||||
|
||||
ffmpegArgs.addAll([
|
||||
'-c:a', 'aac', '-b:a', '192k', '-ar', '48000',
|
||||
'-af', 'pan=stereo|FL=1.0*FL+0.707*FC+0.5*BL+0.5*SL+0.5*LFE|FR=1.0*FR+0.707*FC+0.5*BR+0.5*SR+0.5*LFE,dynaudnorm=f=150:g=15',
|
||||
],
|
||||
..._audioArgs(withFilters: true),
|
||||
'-f', 'hls', '-hls_time', '4', '-hls_list_size', '0',
|
||||
'-hls_playlist_type', 'vod', '-hls_allow_cache', '1',
|
||||
'-hls_flags', 'independent_segments', '-hls_segment_type', 'mpegts',
|
||||
'-hls_segment_filename', 'segment_%03d.ts', '-start_number', '0',
|
||||
'playlist.m3u8',
|
||||
]);
|
||||
],
|
||||
);
|
||||
|
||||
Process.start(_getFFmpegPath(), ffmpegArgs, workingDirectory: streamDir.path).then((process) {
|
||||
_vodProcesses['rec_$streamId'] = process;
|
||||
process.stderr.transform(utf8.decoder).listen((data) => print('[FFmpeg Rec $streamId] $data'));
|
||||
process.exitCode.then((code) {
|
||||
_vodProcesses.remove('rec_$streamId');
|
||||
});
|
||||
});
|
||||
final result = await sessionManager.waitForPlaylist(session);
|
||||
if (!result.ready) {
|
||||
sessionManager.killSession(sessionId);
|
||||
return Response(502,
|
||||
body: 'Recording transcoder failed: ${result.error}');
|
||||
}
|
||||
|
||||
final playlistFile = File('${streamDir.path}/playlist.m3u8');
|
||||
int retries = 0;
|
||||
while (retries < 60) {
|
||||
if (playlistFile.existsSync() && playlistFile.readAsStringSync().contains('.ts')) break;
|
||||
await Future.delayed(const Duration(milliseconds: 500));
|
||||
retries++;
|
||||
}
|
||||
|
||||
if (!playlistFile.existsSync()) return Response.internalServerError(body: 'Timeout waiting for transcoder');
|
||||
|
||||
session.touch();
|
||||
return Response.ok(
|
||||
playlistFile.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'application/vnd.apple.mpegurl',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'no-cache',
|
||||
},
|
||||
File('${session.dir.path}/playlist.m3u8').openRead(),
|
||||
headers: _hlsHeaders(),
|
||||
);
|
||||
});
|
||||
|
||||
router.get('/<streamId>/<segment>', (Request request, String streamId, String segment) async {
|
||||
final file = File('${_hlsTempDir.path}/rec_$streamId/$segment');
|
||||
router.get('/<streamId>/<segment>',
|
||||
(Request request, String streamId, String segment) async {
|
||||
if (segment.contains('..')) {
|
||||
return Response.badRequest(body: 'Invalid request');
|
||||
}
|
||||
final sessionId = 'rec_$streamId';
|
||||
sessionManager.touch(sessionId);
|
||||
final file = File('${_hlsTempDir.path}/$sessionId/$segment');
|
||||
if (!file.existsSync()) return Response.notFound('Segment not found');
|
||||
return Response.ok(
|
||||
file.openRead(),
|
||||
headers: {
|
||||
'Content-Type': 'video/mp2t',
|
||||
'Access-Control-Allow-Origin': '*',
|
||||
'Cache-Control': 'max-age=3600',
|
||||
},
|
||||
);
|
||||
return Response.ok(file.openRead(), headers: _segmentHeaders(maxAge: 3600));
|
||||
});
|
||||
|
||||
return router;
|
||||
return router.call;
|
||||
}
|
||||
@@ -0,0 +1,78 @@
|
||||
import 'dart:convert';
|
||||
import 'package:shelf/shelf.dart';
|
||||
import 'package:http/http.dart' as http;
|
||||
import '../models/playlist_config.dart';
|
||||
import '../utils/log_redactor.dart';
|
||||
|
||||
/// Authenticated gateway to the Xtream `player_api.php` endpoint.
|
||||
///
|
||||
/// The frontend never sees the Xtream credentials: it calls
|
||||
/// `GET /api/xtream-api?action=...` with its session token and the server
|
||||
/// injects the username/password of the user's playlist before forwarding.
|
||||
class XtreamApiHandler {
|
||||
final Future<PlaylistConfig?> Function(Request) _getPlaylist;
|
||||
final http.Client _client = http.Client();
|
||||
|
||||
XtreamApiHandler(this._getPlaylist);
|
||||
|
||||
/// Query parameters the client is allowed to pass through to Xtream.
|
||||
static const _allowedParams = {
|
||||
'action',
|
||||
'category_id',
|
||||
'stream_id',
|
||||
'series_id',
|
||||
'vod_id',
|
||||
'limit',
|
||||
'type',
|
||||
};
|
||||
|
||||
Future<Response> handle(Request request) async {
|
||||
final playlist = await _getPlaylist(request);
|
||||
if (playlist == null) {
|
||||
return Response.forbidden(
|
||||
jsonEncode({'error': 'No playlist configured'}),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
}
|
||||
|
||||
final params = <String, String>{
|
||||
'username': playlist.username,
|
||||
'password': playlist.password,
|
||||
};
|
||||
request.url.queryParameters.forEach((key, value) {
|
||||
if (_allowedParams.contains(key)) params[key] = value;
|
||||
});
|
||||
|
||||
final base = Uri.parse('${playlist.dns}/player_api.php');
|
||||
final targetUrl = base.replace(queryParameters: params);
|
||||
|
||||
try {
|
||||
final proxyRequest = http.Request('GET', targetUrl)
|
||||
..headers['User-Agent'] = 'VLC/3.0.18 LibVLC/3.0.18'
|
||||
..headers['Accept'] = '*/*'
|
||||
..followRedirects = true;
|
||||
|
||||
final response = await _client
|
||||
.send(proxyRequest)
|
||||
.timeout(const Duration(seconds: 90));
|
||||
|
||||
return Response(
|
||||
response.statusCode,
|
||||
body: response.stream,
|
||||
headers: {
|
||||
'Content-Type':
|
||||
response.headers['content-type'] ?? 'application/json',
|
||||
'Cache-Control': 'no-store',
|
||||
},
|
||||
);
|
||||
} catch (e) {
|
||||
print(
|
||||
'[XtreamApi] Error forwarding to ${LogRedactor.redactUrl(targetUrl.toString())}: $e',
|
||||
);
|
||||
return Response.internalServerError(
|
||||
body: jsonEncode({'error': 'Upstream Xtream API error'}),
|
||||
headers: {'Content-Type': 'application/json'},
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user