'use strict'; const { spawn } = require('child_process'); const crypto = require('crypto'); const fs = require('fs'); const os = require('os'); const path = require('path'); const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams'); const STREAM_SESSION_TTL_MS = 30 * 60 * 1000; const STREAM_READY_TIMEOUT_MS = 20 * 1000; const STREAM_IDLE_STOP_MS = 20 * 1000; const sessions = new Map(); function hasInitialHlsAssets (outputDir) { try { const entries = fs.readdirSync(outputDir, { withFileTypes: true }); return entries.some((entry) => { if (!entry.isFile()) return false; if (entry.name === 'master.m3u8') return true; if (/^stream_\d+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true; if (/^stream_\d+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true; return false; }); } catch { return false; } } function makeHttpError (status, message) { const err = new Error(message); err.status = status; return err; } function ensureStreamRootDir () { fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true }); } function ffmpegPath () { return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg'; } function ffprobePath () { return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe'; } function pruneExpiredSessions () { const now = Date.now(); for (const [sessionId, session] of sessions) { if (session.expiresAt > now) continue; destroySession(sessionId); } } function refreshSession (session) { session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS; } function destroySession (sessionId) { const session = sessions.get(sessionId); if (!session) return false; sessions.delete(sessionId); if (session.idleTimer) { clearTimeout(session.idleTimer); session.idleTimer = null; } try { if (session.process) session.process.kill('SIGTERM'); } catch { // Ignore process cleanup failures. } fs.rmSync(session.outputDir, { recursive: true, force: true }); return true; } function touchSessionActivity (session) { refreshSession(session); session.lastActivityAt = Date.now(); } function clearIdleStopTimer (session) { if (!session.idleTimer) return; clearTimeout(session.idleTimer); session.idleTimer = null; } function scheduleIdleStop (session) { clearIdleStopTimer(session); if (session.activeRequests > 0) return; session.idleTimer = setTimeout(() => { const activeSession = sessions.get(session.id); if (!activeSession) return; if (activeSession.activeRequests > 0) return; if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS) { scheduleIdleStop(activeSession); return; } destroySession(activeSession.id); }, STREAM_IDLE_STOP_MS); } function startAssetRequest (session) { session.activeRequests += 1; touchSessionActivity(session); clearIdleStopTimer(session); } function finishAssetRequest (session) { if (session.activeRequests > 0) session.activeRequests -= 1; touchSessionActivity(session); if (session.activeRequests === 0) scheduleIdleStop(session); } function runCommand (command, args) { return new Promise((resolve, reject) => { const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] }); let stdout = ''; let stderr = ''; child.stdout.on('data', (chunk) => { stdout += chunk.toString(); }); child.stderr.on('data', (chunk) => { stderr += chunk.toString(); }); child.on('error', (err) => { if (err && err.code === 'ENOENT') { reject(makeHttpError(503, `${command} is not installed or not available in PATH.`)); return; } reject(err); }); child.on('close', (code) => { if (code === 0) { resolve({ stdout, stderr }); return; } reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`)); }); }); } async function probeInput (sourcePath) { const { stdout } = await runCommand(ffprobePath(), [ '-v', 'error', '-print_format', 'json', '-show_streams', '-show_format', sourcePath, ]); let payload; try { payload = JSON.parse(stdout || '{}'); } catch { throw makeHttpError(500, 'ffprobe returned invalid stream metadata.'); } const typedIndexes = { video: 0, audio: 0, subtitle: 0 }; const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) => { const codecType = String(stream.codec_type || '').toLowerCase(); const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType) ? typedIndexes[codecType]++ : null; return { ...stream, codecType, relativeIndex, tags: stream.tags || {}, disposition: stream.disposition || {}, }; }) : []; return { raw: payload, durationSeconds: inputDurationSeconds(payload, streams), video: streams.filter((stream) => stream.codecType === 'video'), audio: streams.filter((stream) => stream.codecType === 'audio'), subtitles: streams.filter((stream) => stream.codecType === 'subtitle'), }; } function parsePositiveNumber (value) { const number = Number(value); return Number.isFinite(number) && number > 0 ? number : null; } function parseDurationTagSeconds (value) { const raw = String(value || '').trim(); if (!raw) return null; const numeric = parsePositiveNumber(raw); if (numeric) return numeric; const match = raw.match(/^(\d+):([0-5]?\d):([0-5]?\d(?:\.\d+)?)$/); if (!match) return null; const hours = Number(match[1]); const minutes = Number(match[2]); const seconds = Number(match[3]); if (!Number.isFinite(hours) || !Number.isFinite(minutes) || !Number.isFinite(seconds)) return null; return hours * 3600 + minutes * 60 + seconds; } function inputDurationSeconds (payload, streams) { const formatDuration = parsePositiveNumber(payload && payload.format && payload.format.duration); if (formatDuration) return formatDuration; for (const stream of streams) { const duration = parsePositiveNumber(stream.duration); if (duration) return duration; } const formatTags = payload && payload.format && payload.format.tags; const formatTagDuration = formatTags && parseDurationTagSeconds(formatTags.duration || formatTags.DURATION); if (formatTagDuration) return formatTagDuration; for (const stream of streams) { const tagDuration = parseDurationTagSeconds(stream.tags.duration || stream.tags.DURATION); if (tagDuration) return tagDuration; } return null; } function sanitiseTrackValue (value, fallback) { const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, ''); return cleaned || fallback; } function trackLanguage (stream) { return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8); } function trackLabel (stream, fallback) { const title = String(stream.tags.title || stream.tags.handler_name || '').trim(); if (title) return title; const language = trackLanguage(stream); if (language && language !== 'und') return `${fallback} (${language})`; return fallback; } async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams) { const extractedTracks = []; let skippedCount = 0; let trackNumber = 0; for (const stream of subtitleStreams) { const fileName = `subtitle-${trackNumber}.vtt`; const targetPath = path.join(outputDir, fileName); try { await runCommand(ffmpegPath(), [ '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', sourcePath, '-map', `0:s:${stream.relativeIndex}`, '-c:s', 'webvtt', targetPath, ]); } catch { skippedCount += 1; continue; } extractedTracks.push({ fileName, label: trackLabel(stream, `Subtitle ${trackNumber + 1}`), language: trackLanguage(stream), isDefault: !!stream.disposition.default, }); trackNumber += 1; } return { tracks: extractedTracks, skippedCount, }; } function buildHlsArgs (sourcePath, outputDir, streamInfo) { const args = [ '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', sourcePath, '-map', '0:v:0', ]; for (const audioStream of streamInfo.audio) { args.push('-map', `0:a:${audioStream.relativeIndex}`); } args.push( '-c:v', 'libx264', '-preset', 'veryfast', '-crf', '23', '-pix_fmt', 'yuv420p', '-g', '48', '-sc_threshold', '0', ); if (streamInfo.audio.length) { args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2'); } else { args.push('-an'); } const variantMap = []; if (streamInfo.audio.length) { variantMap.push('v:0,agroup:audio,name:video'); streamInfo.audio.forEach((audioStream, index) => { let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`; if (audioStream.disposition.default) entry += ',default:yes'; variantMap.push(entry); }); } else { variantMap.push('v:0,name:video'); } args.push( '-f', 'hls', '-hls_time', '4', '-hls_list_size', '0', '-hls_flags', 'independent_segments+temp_file', '-master_pl_name', 'master.m3u8', '-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'), '-var_stream_map', variantMap.join(' '), path.join(outputDir, 'stream_%v.m3u8'), ); return args; } function startHlsTranscode (session, streamInfo) { const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo); const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] }); let stderr = ''; child.stderr.on('data', (chunk) => { stderr += chunk.toString(); if (stderr.length > 16000) stderr = stderr.slice(-16000); }); child.on('error', (err) => { if (err && err.code === 'ENOENT') { session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.'); return; } session.error = err; }); child.on('close', (code) => { session.process = null; if (code === 0 || session.error) return; session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`); }); session.process = child; } function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS) { const startedAt = Date.now(); return new Promise((resolve, reject) => { const check = () => { if (fs.existsSync(targetPath)) { resolve(); return; } if (session.error) { reject(session.error); return; } if (Date.now() - startedAt >= timeoutMs) { reject(makeHttpError(504, 'Timed out while preparing the video stream.')); return; } setTimeout(check, 120); }; check(); }); } function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS) { const startedAt = Date.now(); return new Promise((resolve, reject) => { const check = () => { if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasInitialHlsAssets(session.outputDir)) { resolve(); return; } if (session.error) { reject(session.error); return; } if (!session.process) { reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.')); return; } if (Date.now() - startedAt >= timeoutMs) { reject(makeHttpError(504, 'Timed out while preparing the video stream.')); return; } setTimeout(check, 120); }; check(); }); } async function initialiseSession (session) { const streamInfo = await probeInput(session.sourcePath); if (!streamInfo.video.length) { throw makeHttpError(400, 'File does not contain a video stream.'); } const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles); session.subtitleTracks = subtitleResult.tracks; session.subtitleSummary = { total: streamInfo.subtitles.length, converted: subtitleResult.tracks.length, skipped: subtitleResult.skippedCount, }; startHlsTranscode(session, streamInfo); session.durationSeconds = streamInfo.durationSeconds; await waitForStreamStart(session); } async function createVideoStreamSession (sourcePath) { pruneExpiredSessions(); ensureStreamRootDir(); const sessionId = crypto.randomBytes(18).toString('hex'); const outputDir = path.join(STREAM_ROOT_DIR, sessionId); fs.mkdirSync(outputDir, { recursive: true }); const session = { id: sessionId, sourcePath, outputDir, expiresAt: Date.now() + STREAM_SESSION_TTL_MS, process: null, error: null, subtitleTracks: [], subtitleSummary: { total: 0, converted: 0, skipped: 0 }, readyPromise: null, activeRequests: 0, lastActivityAt: Date.now(), idleTimer: null, }; session.readyPromise = initialiseSession(session).catch((err) => { session.error = err; throw err; }); sessions.set(sessionId, session); await session.readyPromise; return { sessionId, durationSeconds: session.durationSeconds, subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })), subtitleSummary: { total: Number(session.subtitleSummary.total || 0), converted: Number(session.subtitleSummary.converted || 0), skipped: Number(session.subtitleSummary.skipped || 0), }, }; } function contentTypeForAsset (assetPath) { const ext = path.extname(assetPath).toLowerCase(); if (ext === '.m3u8') return 'application/vnd.apple.mpegurl'; if (ext === '.ts') return 'video/mp2t'; if (ext === '.vtt') return 'text/vtt; charset=utf-8'; if (ext === '.aac') return 'audio/aac'; if (ext === '.mp4' || ext === '.m4s') return 'video/mp4'; return 'application/octet-stream'; } async function sendVideoStreamAsset (sessionId, assetPath, req, res) { pruneExpiredSessions(); const session = sessions.get(sessionId); if (!session) throw makeHttpError(404, 'Video stream session not found.'); touchSessionActivity(session); await session.readyPromise; const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, ''); const resolvedPath = path.resolve(session.outputDir, relativeAssetPath); const resolvedRoot = path.resolve(session.outputDir); if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep)) { throw makeHttpError(404, 'Stream asset not found.'); } await waitForFile(resolvedPath, session); res.set('Cache-Control', 'private, no-store'); res.type(contentTypeForAsset(resolvedPath)); startAssetRequest(session); let settled = false; const finish = () => { if (settled) return; settled = true; finishAssetRequest(session); }; req.on('aborted', finish); res.on('close', finish); res.on('finish', finish); res.on('error', finish); await new Promise((resolve, reject) => { res.sendFile(resolvedPath, (err) => { finish(); if (!err) { resolve(); return; } if (err.code === 'ECONNABORTED' || err.message === 'Request aborted') { resolve(); return; } reject(err); }); }); } function releaseVideoStreamSession (sessionId) { pruneExpiredSessions(); return destroySession(String(sessionId || '')); } module.exports = { STREAM_ROOT_DIR, STREAM_SESSION_TTL_MS, STREAM_IDLE_STOP_MS, createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession, };