'use strict'; const { spawn } = require('child_process'); const crypto = require('crypto'); const fs = require('fs'); const os = require('os'); const path = require('path'); const { clearCachesForFile, pruneOldImageSubtitleCaches, purgeSubtitleCacheDir } = require('./image-subtitles'); 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 = 5 * 60 * 1000; const STREAM_EXPIRY_SWEEP_MS = parseSweepInterval(process.env.VIDEO_STREAM_EXPIRY_SWEEP_MS, 60 * 1000); const ESTIMATED_SEGMENT_BYTES = 1024 * 1024; const ESTIMATED_SEGMENT_DURATION_SECONDS = 6; const STREAM_PRUNE_DELETE_BATCH_SIZE = parsePruneDeleteBatchSize(process.env.VIDEO_STREAM_PRUNE_DELETE_BATCH_SIZE); const MAX_STREAM_SEGMENT_RETENTION_COUNT = 360; const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT); const IMAGE_BASED_SUBTITLE_CODECS = new Set([ 'hdmv_pgs_subtitle', 'pgssub', 'dvd_subtitle', 'dvdsub', 'dvb_subtitle', 'xsub', ]); const sessions = new Map(); const leases = new Map(); const reusableSessionIdBySource = new Map(); // Remove any .sup subtitle files left over from a previous server run. purgeSubtitleCacheDir(); function purgeStreamRootDir () { try { fs.rmSync(STREAM_ROOT_DIR, { recursive: true, force: true }); } catch { // Best-effort cleanup. } } function cleanupIdleStreamArtifacts () { if (sessions.size > 0) return; if (leases.size > 0) return; purgeStreamRootDir(); } // Remove stale stream output folders left by previous runs. purgeStreamRootDir(); // Periodically sweep stream artifacts when no streams are active. const streamRootCleanupTimer = setInterval(cleanupIdleStreamArtifacts, STREAM_IDLE_STOP_MS); if (streamRootCleanupTimer && typeof streamRootCleanupTimer.unref === 'function') { streamRootCleanupTimer.unref(); } // Ensure expired leases/sessions are reclaimed even without further stream requests. const streamExpirySweepTimer = setInterval(pruneExpiredSessions, STREAM_EXPIRY_SWEEP_MS); if (streamExpirySweepTimer && typeof streamExpirySweepTimer.unref === 'function') { streamExpirySweepTimer.unref(); } function parseSweepInterval (value, fallbackMs) { const parsed = Number.parseInt(String(value || ''), 10); if (Number.isInteger(parsed) && parsed >= 1000) { return clampNumber(parsed, 1000, 10 * 60 * 1000); } return fallbackMs; } function parseSegmentRetentionCount (value) { const parsed = Number.parseInt(String(value || ''), 10); if (Number.isInteger(parsed) && parsed >= 30) { return clampNumber(parsed, 30, MAX_STREAM_SEGMENT_RETENTION_COUNT); } return defaultSegmentRetentionCount(); } function parsePruneDeleteBatchSize (value) { const parsed = Number.parseInt(String(value || ''), 10); if (Number.isInteger(parsed) && parsed >= 1) { return clampNumber(parsed, 1, 128); } return 16; } function readRaspberryPiModel () { try { return fs.readFileSync('/proc/device-tree/model', 'utf8').replace(/\u0000/g, '').trim(); } catch { return ''; } } function clampNumber (value, min, max) { return Math.min(max, Math.max(min, value)); } function currentCpuPressureFactor (cpuCount) { if (typeof os.loadavg !== 'function') return 1; if (!Number.isFinite(cpuCount) || cpuCount <= 0) return 1; const [load1] = os.loadavg(); if (!Number.isFinite(load1) || load1 < 0) return 1; const saturation = load1 / cpuCount; if (saturation >= 1.5) return 0.72; if (saturation >= 1.2) return 0.8; if (saturation >= 1.0) return 0.88; if (saturation >= 0.8) return 0.94; return 1; } function defaultSegmentRetentionCount () { const totalMemBytes = Number(os.totalmem()) || 0; const freeMemBytes = Number(os.freemem()) || 0; const cpuCount = Math.max(1, ((os.cpus() || []).length || 1)); const arch = String(os.arch() || '').toLowerCase(); const piModel = readRaspberryPiModel().toLowerCase(); const isPi5 = piModel.includes('raspberry pi 5'); const isArm = arch === 'arm' || arch === 'arm64' || arch.startsWith('armv'); const cpuPressure = currentCpuPressureFactor(cpuCount); const freeMemRatio = totalMemBytes > 0 ? (freeMemBytes / totalMemBytes) : 1; const memoryPressure = freeMemRatio < 0.12 ? 0.72 : freeMemRatio < 0.2 ? 0.84 : freeMemRatio < 0.3 ? 0.92 : 1; if (isPi5) { const memoryBudgetBytes = Math.floor(totalMemBytes * 0.03); const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); const byCpu = 120 + ((cpuCount - 2) * 20); const combined = Math.min(byMemory, byCpu); return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 100, 220); } if (isArm) { const memoryBudgetBytes = Math.floor(totalMemBytes * 0.025); const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); const byCpu = 90 + ((cpuCount - 2) * 14); const combined = Math.min(byMemory, byCpu); return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 80, 180); } const memoryBudgetBytes = Math.floor(totalMemBytes * 0.05); const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES); const byCpu = 140 + ((cpuCount - 4) * 16); const combined = Math.min(byMemory, byCpu); return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 120, 320); } 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_.+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true; if (/^stream_.+_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 [leaseId, lease] of leases) { if (lease.expiresAt > now) continue; releaseVideoStreamSession(leaseId); } 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 refreshLease (lease) { lease.expiresAt = Date.now() + STREAM_SESSION_TTL_MS; } function destroySession (sessionId) { const session = sessions.get(sessionId); if (!session) return false; sessions.delete(sessionId); if (reusableSessionIdBySource.get(session.sourcePath) === session.id) { reusableSessionIdBySource.delete(session.sourcePath); } if (session.leaseIds) { for (const leaseId of session.leaseIds) { leases.delete(leaseId); } session.leaseIds.clear(); } 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 }); // Only clear file-wide subtitle caches when no other active stream session // for the same source file remains. if (!hasActiveSessionForSourcePath(session.sourcePath)) { clearCachesForFile(session.sourcePath); } return true; } function pruneImageSubtitleCachesForSession (session) { if (!session || !session.sourcePath) return; const slowestViewerTimeSeconds = slowestViewerTimeSecondsForSourcePath(session.sourcePath); if (!Number.isFinite(slowestViewerTimeSeconds)) return; pruneOldImageSubtitleCaches(session.sourcePath, slowestViewerTimeSeconds); } function hasActiveSessionForSourcePath (sourcePath) { const wantedPath = String(sourcePath || ''); if (!wantedPath) return false; for (const session of sessions.values()) { if (session && session.sourcePath === wantedPath) return true; } return false; } function slowestViewerTimeSecondsForSourcePath (sourcePath) { const wantedPath = String(sourcePath || ''); if (!wantedPath) return null; let slowestIndex = null; let hasActiveViewers = false; for (const session of sessions.values()) { if (!session || session.sourcePath !== wantedPath) continue; if (!session.leaseIds || session.leaseIds.size === 0) continue; hasActiveViewers = true; const sessionSlowestIndex = slowestLeaseSegmentIndex(session); if (!Number.isInteger(sessionSlowestIndex)) return null; if (slowestIndex === null || sessionSlowestIndex < slowestIndex) { slowestIndex = sessionSlowestIndex; } } if (!hasActiveViewers || slowestIndex === null) return null; return slowestIndex * ESTIMATED_SEGMENT_DURATION_SECONDS; } function getSessionForLease (leaseId) { const lease = leases.get(leaseId); if (!lease) return null; const session = sessions.get(lease.sessionId); if (!session) { leases.delete(leaseId); return null; } return { lease, session }; } function createLeaseForSession (session) { const leaseId = crypto.randomBytes(18).toString('hex'); const lease = { id: leaseId, sessionId: session.id, expiresAt: Date.now() + STREAM_SESSION_TTL_MS, lastActivityAt: Date.now(), lastSegmentIndex: null, }; leases.set(leaseId, lease); session.leaseIds.add(leaseId); return lease; } function touchSessionActivity (session, lease) { refreshSession(session); session.lastActivityAt = Date.now(); if (lease) { refreshLease(lease); lease.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 || (session.leaseIds && session.leaseIds.size > 0)) return; session.idleTimer = setTimeout(() => { const activeSession = sessions.get(session.id); if (!activeSession) return; if (activeSession.activeRequests > 0 || (activeSession.leaseIds && activeSession.leaseIds.size > 0)) return; if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS) { scheduleIdleStop(activeSession); return; } destroySession(activeSession.id); }, STREAM_IDLE_STOP_MS); } function startAssetRequest (session, lease) { session.activeRequests += 1; touchSessionActivity(session, lease); clearIdleStopTimer(session); } function finishAssetRequest (session, lease) { if (session.activeRequests > 0) session.activeRequests -= 1; const activeSession = sessions.get(session.id); if (!activeSession) return; touchSessionActivity(activeSession, lease); if (activeSession.activeRequests === 0 && activeSession.leaseIds.size === 0) { destroySession(activeSession.id); } } function parseSegmentIndexFromAssetPath (assetPath) { const baseName = path.basename(String(assetPath || '')); const match = baseName.match(/^stream_.+_segment_(\d+)\.ts$/i); if (!match) return null; const segmentIndex = Number.parseInt(match[1], 10); return Number.isInteger(segmentIndex) ? segmentIndex : null; } function runSegmentPrune (session) { if (session.segmentPruneRunning) return; if (session.segmentPrunePendingCutoff <= session.segmentPrunedUntil) return; const cutoff = session.segmentPrunePendingCutoff; const pruneStartedAt = Date.now(); session.segmentPruneRunning = true; fs.promises.readdir(session.outputDir) .then((entries) => { const removals = []; for (const entryName of entries) { const match = String(entryName).match(/^stream_.+_segment_(\d+)\.ts$/i); if (!match) continue; const segmentIndex = Number.parseInt(match[1], 10); if (!Number.isInteger(segmentIndex)) continue; if (segmentIndex > cutoff) continue; removals.push(path.join(session.outputDir, entryName)); } return deleteFilesInBatches(removals, STREAM_PRUNE_DELETE_BATCH_SIZE); }) .then((deletedCount) => { const completedAt = Date.now(); session.segmentPrunedUntil = Math.max(session.segmentPrunedUntil, cutoff); session.lastSegmentPrune = { cutoff, deletedSegments: deletedCount, durationMs: Math.max(0, completedAt - pruneStartedAt), completedAt, }; pruneImageSubtitleCachesForSession(session); if (session.segmentPrunedUntil >= 0 && reusableSessionIdBySource.get(session.sourcePath) === session.id) { reusableSessionIdBySource.delete(session.sourcePath); } }) .catch(() => { // Best effort cleanup; keep streaming even if pruning fails. }) .finally(() => { session.segmentPruneRunning = false; if (session.segmentPrunePendingCutoff > session.segmentPrunedUntil) { runSegmentPrune(session); } }); } async function deleteFilesInBatches (pathsToDelete, batchSize) { const paths = Array.isArray(pathsToDelete) ? pathsToDelete : []; if (!paths.length) return 0; let deletedCount = 0; for (let index = 0; index < paths.length; index += batchSize) { const batch = paths.slice(index, index + batchSize); await Promise.all(batch.map((targetPath) => fs.promises.unlink(targetPath) .then(() => { deletedCount += 1; }) .catch(() => { // Ignore races while ffmpeg rotates temp files and request handlers read segments. }) )); } return deletedCount; } function slowestLeaseSegmentIndex (session) { if (!session.leaseIds.size) return null; let minIndex = null; for (const leaseId of session.leaseIds) { const lease = leases.get(leaseId); if (!lease) continue; if (!Number.isInteger(lease.lastSegmentIndex)) return null; if (minIndex === null || lease.lastSegmentIndex < minIndex) minIndex = lease.lastSegmentIndex; } return minIndex; } function scheduleSegmentPrune (session, lease, segmentIndex) { if (!Number.isInteger(segmentIndex) || segmentIndex < 0) return; lease.lastSegmentIndex = segmentIndex; const slowestIndex = slowestLeaseSegmentIndex(session); if (!Number.isInteger(slowestIndex)) return; const pruneCutoff = slowestIndex - STREAM_SEGMENT_RETENTION_COUNT; if (pruneCutoff <= session.segmentPrunedUntil) return; session.segmentPrunePendingCutoff = Math.max(session.segmentPrunePendingCutoff, pruneCutoff); runSegmentPrune(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; } function findMatchingSidecarSrtPath (sourcePath) { const absoluteSourcePath = path.resolve(String(sourcePath || '')); const dirPath = path.dirname(absoluteSourcePath); const baseName = path.parse(absoluteSourcePath).name; const exactPath = path.join(dirPath, `${baseName}.srt`); try { const exactStat = fs.statSync(exactPath); if (exactStat.isFile()) return exactPath; } catch { // Fall back to case-insensitive directory scan. } const wantedName = `${baseName}.srt`.toLowerCase(); try { const entries = fs.readdirSync(dirPath, { withFileTypes: true }); for (const entry of entries) { if (!entry.isFile()) continue; if (entry.name.toLowerCase() !== wantedName) continue; return path.join(dirPath, entry.name); } } catch { return null; } return null; } function stripSubtitleEditorNotes (text) { return String(text || '') .replace(/\{[^{}]*\}/g, '') .replace(/[ \t]{2,}/g, ' ') .trim(); } function isWebVttStructuralLine (line) { const trimmed = String(line || '').trim(); if (!trimmed) return true; if (/^WEBVTT\b/i.test(trimmed)) return true; if (trimmed.includes('-->')) return true; if (/^(NOTE|STYLE|REGION)\b/i.test(trimmed)) return true; if (/^\d+$/.test(trimmed)) return true; return false; } function sanitizeWebVttContent (vttContent) { return String(vttContent || '').split(/\r?\n/).map((line) => { if (isWebVttStructuralLine(line)) return line; return stripSubtitleEditorNotes(line); }).join('\n'); } async function sanitizeWebVttFile (filePath) { const raw = await fs.promises.readFile(filePath, 'utf8'); const sanitized = sanitizeWebVttContent(raw); if (sanitized !== raw) { await fs.promises.writeFile(filePath, sanitized, 'utf8'); } } async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams) { const extractedTracks = []; const imageBasedTracks = []; let skippedCount = 0; let trackNumber = 0; for (const stream of subtitleStreams) { const codecName = String(stream.codec_name || '').toLowerCase(); // Image-based subtitle formats will be shown as DOM overlays via frame extraction. if (IMAGE_BASED_SUBTITLE_CODECS.has(codecName)) { imageBasedTracks.push({ label: trackLabel(stream, `Subtitle ${stream.relativeIndex + 1}`), language: trackLanguage(stream), isDefault: !!stream.disposition.default, streamIndex: stream.relativeIndex, }); continue; } 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; } try { await sanitizeWebVttFile(targetPath); } catch { skippedCount += 1; continue; } extractedTracks.push({ fileName, label: trackLabel(stream, `Subtitle ${trackNumber + 1}`), language: trackLanguage(stream), isDefault: !!stream.disposition.default, }); trackNumber += 1; } const sidecarSrtPath = findMatchingSidecarSrtPath(sourcePath); const hasSidecarSrt = !!sidecarSrtPath; if (sidecarSrtPath) { const fileName = `subtitle-${trackNumber}.vtt`; const targetPath = path.join(outputDir, fileName); try { await runCommand(ffmpegPath(), [ '-hide_banner', '-loglevel', 'error', '-nostdin', '-y', '-i', sidecarSrtPath, '-c:s', 'webvtt', targetPath, ]); await sanitizeWebVttFile(targetPath); extractedTracks.push({ fileName, label: `Subtitle ${trackNumber + 1} (external)`, language: 'und', isDefault: extractedTracks.length === 0 && imageBasedTracks.length === 0, }); trackNumber += 1; } catch { skippedCount += 1; } } return { tracks: extractedTracks, imageBasedTracks, hasSidecarSrt, 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 primaryVideoStream = streamInfo.video[0] || {}; session.videoWidth = parsePositiveNumber(primaryVideoStream.width); session.videoHeight = parsePositiveNumber(primaryVideoStream.height); const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles); session.subtitleTracks = subtitleResult.tracks; session.imageSubtitleTracks = subtitleResult.imageBasedTracks; session.subtitleSummary = { total: streamInfo.subtitles.length + (subtitleResult.hasSidecarSrt ? 1 : 0), converted: subtitleResult.tracks.length, imageBased: subtitleResult.imageBasedTracks.length, skipped: subtitleResult.skippedCount, }; startHlsTranscode(session, streamInfo); session.durationSeconds = streamInfo.durationSeconds; await waitForStreamStart(session); } async function createVideoStreamSession (sourcePath) { pruneExpiredSessions(); ensureStreamRootDir(); const sourceKey = String(sourcePath || ''); let session = null; const reusableSessionId = reusableSessionIdBySource.get(sourceKey); if (reusableSessionId) { const reusable = sessions.get(reusableSessionId); if (reusable && !reusable.error && reusable.segmentPrunedUntil < 0) { session = reusable; } else { reusableSessionIdBySource.delete(sourceKey); } } if (!session) { const sessionId = crypto.randomBytes(18).toString('hex'); const outputDir = path.join(STREAM_ROOT_DIR, sessionId); fs.mkdirSync(outputDir, { recursive: true }); session = { id: sessionId, sourcePath: String(sourcePath || ''), sourceKey: sourceKey, outputDir, expiresAt: Date.now() + STREAM_SESSION_TTL_MS, process: null, error: null, subtitleTracks: [], imageSubtitleTracks: [], subtitleSummary: { total: 0, converted: 0, imageBased: 0, skipped: 0 }, readyPromise: null, activeRequests: 0, lastActivityAt: Date.now(), idleTimer: null, segmentPruneRunning: false, segmentPrunePendingCutoff: -1, segmentPrunedUntil: -1, lastSegmentPrune: null, leaseIds: new Set(), }; session.readyPromise = initialiseSession(session).catch((err) => { session.error = err; throw err; }); sessions.set(session.id, session); reusableSessionIdBySource.set(sourceKey, session.id); } if (!session.leaseIds) session.leaseIds = new Set(); const lease = createLeaseForSession(session); touchSessionActivity(session, lease); try { await session.readyPromise; } catch (err) { releaseVideoStreamSession(lease.id); throw err; } return { sessionId: lease.id, durationSeconds: session.durationSeconds, videoWidth: session.videoWidth || null, videoHeight: session.videoHeight || null, subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })), imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({ ...track })), subtitleSummary: { total: Number(session.subtitleSummary.total || 0), converted: Number(session.subtitleSummary.converted || 0), imageBased: Number(session.subtitleSummary.imageBased || 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 active = getSessionForLease(sessionId); if (!active) throw makeHttpError(404, 'Video stream session not found.'); const { session, lease } = active; touchSessionActivity(session, lease); 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.'); } const segmentIndex = parseSegmentIndexFromAssetPath(relativeAssetPath); if (segmentIndex !== null) scheduleSegmentPrune(session, lease, segmentIndex); await waitForFile(resolvedPath, session); res.set('Cache-Control', 'private, no-store'); res.type(contentTypeForAsset(resolvedPath)); startAssetRequest(session, lease); let settled = false; const finish = () => { if (settled) return; settled = true; finishAssetRequest(session, lease); }; 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) { const leaseId = String(sessionId || ''); const active = getSessionForLease(leaseId); if (!active) { leases.delete(leaseId); return false; } const { session } = active; leases.delete(leaseId); session.leaseIds.delete(leaseId); if (session.leaseIds.size === 0) { return destroySession(session.id); } return true; } function collectOutputDirStats (outputDir) { const stats = { exists: false, totalBytes: 0, totalFiles: 0, segmentFiles: 0, segmentBytes: 0, playlistFiles: 0, subtitleFiles: 0, }; if (!outputDir || !fs.existsSync(outputDir)) return stats; stats.exists = true; let entries = []; try { entries = fs.readdirSync(outputDir, { withFileTypes: true }); } catch { return stats; } for (const entry of entries) { if (!entry.isFile()) continue; const name = entry.name; const fullPath = path.join(outputDir, name); let size = 0; try { const fileStat = fs.statSync(fullPath); size = Number(fileStat.size) || 0; } catch { size = 0; } stats.totalFiles += 1; stats.totalBytes += size; if (/\.ts$/i.test(name)) { stats.segmentFiles += 1; stats.segmentBytes += size; continue; } if (/\.m3u8$/i.test(name)) { stats.playlistFiles += 1; continue; } if (/\.(sup|vtt)$/i.test(name)) { stats.subtitleFiles += 1; } } return stats; } function getVideoStreamDebugSnapshot () { const activeStreams = []; for (const [sessionId, session] of sessions.entries()) { activeStreams.push({ sessionId, sourcePath: session.sourcePath, outputDir: session.outputDir, viewers: session.leaseIds ? session.leaseIds.size : 0, activeRequests: Number(session.activeRequests || 0), expiresAt: Number(session.expiresAt || 0), segmentRetentionCount: STREAM_SEGMENT_RETENTION_COUNT, segmentPruneDeleteBatchSize: STREAM_PRUNE_DELETE_BATCH_SIZE, segmentPrunePendingCutoff: Number(session.segmentPrunePendingCutoff || 0), segmentPrunedUntil: Number(session.segmentPrunedUntil || 0), slowestViewerSegmentIndex: slowestLeaseSegmentIndex(session) ?? -1, lastSegmentPrune: session.lastSegmentPrune || null, output: collectOutputDirStats(session.outputDir), }); } const knownSessionDirs = new Set(activeStreams.map((stream) => path.resolve(stream.outputDir || ''))); const orphanedOutputDirs = []; try { const entries = fs.readdirSync(STREAM_ROOT_DIR, { withFileTypes: true }); for (const entry of entries) { if (!entry.isDirectory()) continue; const dirPath = path.resolve(path.join(STREAM_ROOT_DIR, entry.name)); if (knownSessionDirs.has(dirPath)) continue; orphanedOutputDirs.push({ outputDir: dirPath, output: collectOutputDirStats(dirPath), }); } } catch { // Stream root may not exist yet. } return { streamRootDir: STREAM_ROOT_DIR, streamSegmentRetentionCount: STREAM_SEGMENT_RETENTION_COUNT, streamSegmentRetentionMax: MAX_STREAM_SEGMENT_RETENTION_COUNT, streamPruneDeleteBatchSize: STREAM_PRUNE_DELETE_BATCH_SIZE, activeSessionCount: sessions.size, activeLeaseCount: leases.size, activeStreams, orphanedOutputDirs, }; } function getActiveStreamCount () { return sessions.size; } module.exports = { STREAM_ROOT_DIR, STREAM_SESSION_TTL_MS, STREAM_IDLE_STOP_MS, STREAM_SEGMENT_RETENTION_COUNT, createVideoStreamSession, sendVideoStreamAsset, releaseVideoStreamSession, getActiveStreamCount, getVideoStreamDebugSnapshot, cleanupIdleStreamArtifacts, stripSubtitleEditorNotes, sanitizeWebVttContent, };