BlueGit

timfa filemanager

Files

filemanager / server / video-stream.js

video-stream.js

video-stream.js 30.6 KiB Download Raw
1'use strict';
2
3const { spawn } = require('child_process');
4const crypto = require('crypto');
5const fs = require('fs');
6const os = require('os');
7const path = require('path');
8const { clearCachesForFile, pruneOldImageSubtitleCaches, purgeSubtitleCacheDir } = require('./image-subtitles');
9
10const STREAM_ROOT_DIR = path.join(os.tmpdir(), 'filemanager-video-streams');
11const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;
12const STREAM_READY_TIMEOUT_MS = 20 * 1000;
13const STREAM_IDLE_STOP_MS = 5 * 60 * 1000;
14const ESTIMATED_SEGMENT_BYTES = 1024 * 1024;
15const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT);
16const IMAGE_BASED_SUBTITLE_CODECS = new Set([
17 'hdmv_pgs_subtitle',
18 'pgssub',
19 'dvd_subtitle',
20 'dvdsub',
21 'dvb_subtitle',
22 'xsub',
23]);
24const sessions = new Map();
25const leases = new Map();
26const reusableSessionIdBySource = new Map();
27
28// Remove any .sup subtitle files left over from a previous server run.
29purgeSubtitleCacheDir();
30
31function purgeStreamRootDir ()
32{
33 try
34 {
35 fs.rmSync(STREAM_ROOT_DIR, { recursive: true, force: true });
36 } catch
37 {
38 // Best-effort cleanup.
39 }
40}
41
42function cleanupIdleStreamArtifacts ()
43{
44 if (sessions.size > 0) return;
45 if (leases.size > 0) return;
46 purgeStreamRootDir();
47}
48
49// Remove stale stream output folders left by previous runs.
50purgeStreamRootDir();
51
52// Periodically sweep stream artifacts when no streams are active.
53const streamRootCleanupTimer = setInterval(cleanupIdleStreamArtifacts, STREAM_IDLE_STOP_MS);
54if (streamRootCleanupTimer && typeof streamRootCleanupTimer.unref === 'function')
55{
56 streamRootCleanupTimer.unref();
57}
58
59function parseSegmentRetentionCount (value)
60{
61 const parsed = Number.parseInt(String(value || ''), 10);
62 if (Number.isInteger(parsed) && parsed >= 30) return parsed;
63 return defaultSegmentRetentionCount();
64}
65
66function readRaspberryPiModel ()
67{
68 try
69 {
70 return fs.readFileSync('/proc/device-tree/model', 'utf8').replace(/\u0000/g, '').trim();
71 } catch
72 {
73 return '';
74 }
75}
76
77function clampNumber (value, min, max)
78{
79 return Math.min(max, Math.max(min, value));
80}
81
82function currentCpuPressureFactor (cpuCount)
83{
84 if (typeof os.loadavg !== 'function') return 1;
85 if (!Number.isFinite(cpuCount) || cpuCount <= 0) return 1;
86
87 const [load1] = os.loadavg();
88 if (!Number.isFinite(load1) || load1 < 0) return 1;
89
90 const saturation = load1 / cpuCount;
91 if (saturation >= 1.5) return 0.72;
92 if (saturation >= 1.2) return 0.8;
93 if (saturation >= 1.0) return 0.88;
94 if (saturation >= 0.8) return 0.94;
95 return 1;
96}
97
98function defaultSegmentRetentionCount ()
99{
100 const totalMemBytes = Number(os.totalmem()) || 0;
101 const freeMemBytes = Number(os.freemem()) || 0;
102 const cpuCount = Math.max(1, ((os.cpus() || []).length || 1));
103 const arch = String(os.arch() || '').toLowerCase();
104 const piModel = readRaspberryPiModel().toLowerCase();
105 const isPi5 = piModel.includes('raspberry pi 5');
106 const isArm = arch === 'arm' || arch === 'arm64' || arch.startsWith('armv');
107 const cpuPressure = currentCpuPressureFactor(cpuCount);
108
109 const freeMemRatio = totalMemBytes > 0 ? (freeMemBytes / totalMemBytes) : 1;
110 const memoryPressure = freeMemRatio < 0.12 ? 0.72 : freeMemRatio < 0.2 ? 0.84 : freeMemRatio < 0.3 ? 0.92 : 1;
111
112 if (isPi5)
113 {
114 const memoryBudgetBytes = Math.floor(totalMemBytes * 0.03);
115 const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES);
116 const byCpu = 120 + ((cpuCount - 2) * 20);
117 const combined = Math.min(byMemory, byCpu);
118 return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 100, 220);
119 }
120
121 if (isArm)
122 {
123 const memoryBudgetBytes = Math.floor(totalMemBytes * 0.025);
124 const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES);
125 const byCpu = 90 + ((cpuCount - 2) * 14);
126 const combined = Math.min(byMemory, byCpu);
127 return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 80, 180);
128 }
129
130 const memoryBudgetBytes = Math.floor(totalMemBytes * 0.05);
131 const byMemory = Math.floor(memoryBudgetBytes / ESTIMATED_SEGMENT_BYTES);
132 const byCpu = 140 + ((cpuCount - 4) * 16);
133 const combined = Math.min(byMemory, byCpu);
134 return clampNumber(Math.floor(combined * cpuPressure * memoryPressure), 120, 320);
135}
136
137function hasInitialHlsAssets (outputDir)
138{
139 try
140 {
141 const entries = fs.readdirSync(outputDir, { withFileTypes: true });
142 return entries.some((entry) =>
143 {
144 if (!entry.isFile()) return false;
145 if (entry.name === 'master.m3u8') return true;
146 if (/^stream_\d+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true;
147 if (/^stream_\d+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true;
148 return false;
149 });
150 } catch
151 {
152 return false;
153 }
154}
155
156function makeHttpError (status, message)
157{
158 const err = new Error(message);
159 err.status = status;
160 return err;
161}
162
163function ensureStreamRootDir ()
164{
165 fs.mkdirSync(STREAM_ROOT_DIR, { recursive: true });
166}
167
168function ffmpegPath ()
169{
170 return String(process.env.FFMPEG_PATH || '').trim() || 'ffmpeg';
171}
172
173function ffprobePath ()
174{
175 return String(process.env.FFPROBE_PATH || '').trim() || 'ffprobe';
176}
177
178function pruneExpiredSessions ()
179{
180 const now = Date.now();
181
182 for (const [leaseId, lease] of leases)
183 {
184 if (lease.expiresAt > now) continue;
185 releaseVideoStreamSession(leaseId);
186 }
187
188 for (const [sessionId, session] of sessions)
189 {
190 if (session.expiresAt > now) continue;
191 destroySession(sessionId);
192 }
193}
194
195function refreshSession (session)
196{
197 session.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;
198}
199
200function refreshLease (lease)
201{
202 lease.expiresAt = Date.now() + STREAM_SESSION_TTL_MS;
203}
204
205function destroySession (sessionId)
206{
207 const session = sessions.get(sessionId);
208 if (!session) return false;
209
210 sessions.delete(sessionId);
211
212 if (reusableSessionIdBySource.get(session.sourcePath) === session.id)
213 {
214 reusableSessionIdBySource.delete(session.sourcePath);
215 }
216
217 if (session.leaseIds)
218 {
219 for (const leaseId of session.leaseIds)
220 {
221 leases.delete(leaseId);
222 }
223 session.leaseIds.clear();
224 }
225
226 if (session.idleTimer)
227 {
228 clearTimeout(session.idleTimer);
229 session.idleTimer = null;
230 }
231
232 try
233 {
234 if (session.process) session.process.kill('SIGTERM');
235 } catch
236 {
237 // Ignore process cleanup failures.
238 }
239
240 fs.rmSync(session.outputDir, { recursive: true, force: true });
241
242 // Clear image subtitle caches associated with this file.
243 clearCachesForFile(session.sourcePath);
244
245 return true;
246}
247
248function pruneImageSubtitleCachesForSession (session)
249{
250 if (!session || !session.sourcePath) return;
251
252 const slowestIndex = slowestLeaseSegmentIndex(session);
253 if (!Number.isInteger(slowestIndex)) return;
254
255 const estimatedSegmentDurationSeconds = 6;
256 const slowestViewerTimeSeconds = slowestIndex * estimatedSegmentDurationSeconds;
257 pruneOldImageSubtitleCaches(session.sourcePath, slowestViewerTimeSeconds);
258}
259
260function getSessionForLease (leaseId)
261{
262 const lease = leases.get(leaseId);
263 if (!lease) return null;
264
265 const session = sessions.get(lease.sessionId);
266 if (!session)
267 {
268 leases.delete(leaseId);
269 return null;
270 }
271
272 return { lease, session };
273}
274
275function createLeaseForSession (session)
276{
277 const leaseId = crypto.randomBytes(18).toString('hex');
278 const lease = {
279 id: leaseId,
280 sessionId: session.id,
281 expiresAt: Date.now() + STREAM_SESSION_TTL_MS,
282 lastActivityAt: Date.now(),
283 lastSegmentIndex: null,
284 };
285 leases.set(leaseId, lease);
286 session.leaseIds.add(leaseId);
287 return lease;
288}
289
290function touchSessionActivity (session, lease)
291{
292 refreshSession(session);
293 session.lastActivityAt = Date.now();
294
295 if (lease)
296 {
297 refreshLease(lease);
298 lease.lastActivityAt = Date.now();
299 }
300}
301
302function clearIdleStopTimer (session)
303{
304 if (!session.idleTimer) return;
305 clearTimeout(session.idleTimer);
306 session.idleTimer = null;
307}
308
309function scheduleIdleStop (session)
310{
311 clearIdleStopTimer(session);
312 if (session.activeRequests > 0 || (session.leaseIds && session.leaseIds.size > 0)) return;
313
314 session.idleTimer = setTimeout(() =>
315 {
316 const activeSession = sessions.get(session.id);
317 if (!activeSession) return;
318 if (activeSession.activeRequests > 0 || (activeSession.leaseIds && activeSession.leaseIds.size > 0)) return;
319 if (Date.now() - activeSession.lastActivityAt < STREAM_IDLE_STOP_MS)
320 {
321 scheduleIdleStop(activeSession);
322 return;
323 }
324 destroySession(activeSession.id);
325 }, STREAM_IDLE_STOP_MS);
326}
327
328function startAssetRequest (session, lease)
329{
330 session.activeRequests += 1;
331 touchSessionActivity(session, lease);
332 clearIdleStopTimer(session);
333}
334
335function finishAssetRequest (session, lease)
336{
337 if (session.activeRequests > 0) session.activeRequests -= 1;
338 touchSessionActivity(session, lease);
339 if (session.activeRequests === 0 && session.leaseIds.size === 0) scheduleIdleStop(session);
340}
341
342function parseSegmentIndexFromAssetPath (assetPath)
343{
344 const baseName = path.basename(String(assetPath || ''));
345 const match = baseName.match(/^stream_\d+_segment_(\d+)\.ts$/i);
346 if (!match) return null;
347
348 const segmentIndex = Number.parseInt(match[1], 10);
349 return Number.isInteger(segmentIndex) ? segmentIndex : null;
350}
351
352function runSegmentPrune (session)
353{
354 if (session.segmentPruneRunning) return;
355 if (session.segmentPrunePendingCutoff <= session.segmentPrunedUntil) return;
356
357 const cutoff = session.segmentPrunePendingCutoff;
358 session.segmentPruneRunning = true;
359
360 fs.promises.readdir(session.outputDir)
361 .then((entries) =>
362 {
363 const removals = [];
364 for (const entryName of entries)
365 {
366 const match = String(entryName).match(/^stream_\d+_segment_(\d+)\.ts$/i);
367 if (!match) continue;
368 const segmentIndex = Number.parseInt(match[1], 10);
369 if (!Number.isInteger(segmentIndex)) continue;
370 if (segmentIndex > cutoff) continue;
371
372 removals.push(
373 fs.promises.unlink(path.join(session.outputDir, entryName)).catch(() =>
374 {
375 // Ignore races while ffmpeg rotates temp files and request handlers read segments.
376 })
377 );
378 }
379 return Promise.all(removals);
380 })
381 .then(() =>
382 {
383 session.segmentPrunedUntil = Math.max(session.segmentPrunedUntil, cutoff);
384 pruneImageSubtitleCachesForSession(session);
385 if (session.segmentPrunedUntil >= 0 && reusableSessionIdBySource.get(session.sourcePath) === session.id)
386 {
387 reusableSessionIdBySource.delete(session.sourcePath);
388 }
389 })
390 .catch(() =>
391 {
392 // Best effort cleanup; keep streaming even if pruning fails.
393 })
394 .finally(() =>
395 {
396 session.segmentPruneRunning = false;
397 if (session.segmentPrunePendingCutoff > session.segmentPrunedUntil)
398 {
399 runSegmentPrune(session);
400 }
401 });
402}
403
404function slowestLeaseSegmentIndex (session)
405{
406 if (!session.leaseIds.size) return null;
407
408 let minIndex = null;
409 for (const leaseId of session.leaseIds)
410 {
411 const lease = leases.get(leaseId);
412 if (!lease) continue;
413 if (!Number.isInteger(lease.lastSegmentIndex)) return null;
414 if (minIndex === null || lease.lastSegmentIndex < minIndex) minIndex = lease.lastSegmentIndex;
415 }
416
417 return minIndex;
418}
419
420function scheduleSegmentPrune (session, lease, segmentIndex)
421{
422 if (!Number.isInteger(segmentIndex) || segmentIndex < 0) return;
423
424 lease.lastSegmentIndex = segmentIndex;
425 const slowestIndex = slowestLeaseSegmentIndex(session);
426 if (!Number.isInteger(slowestIndex)) return;
427
428 const pruneCutoff = slowestIndex - STREAM_SEGMENT_RETENTION_COUNT;
429 if (pruneCutoff <= session.segmentPrunedUntil) return;
430
431 session.segmentPrunePendingCutoff = Math.max(session.segmentPrunePendingCutoff, pruneCutoff);
432 runSegmentPrune(session);
433}
434
435function runCommand (command, args)
436{
437 return new Promise((resolve, reject) =>
438 {
439 const child = spawn(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
440 let stdout = '';
441 let stderr = '';
442
443 child.stdout.on('data', (chunk) =>
444 {
445 stdout += chunk.toString();
446 });
447
448 child.stderr.on('data', (chunk) =>
449 {
450 stderr += chunk.toString();
451 });
452
453 child.on('error', (err) =>
454 {
455 if (err && err.code === 'ENOENT')
456 {
457 reject(makeHttpError(503, `${command} is not installed or not available in PATH.`));
458 return;
459 }
460 reject(err);
461 });
462
463 child.on('close', (code) =>
464 {
465 if (code === 0)
466 {
467 resolve({ stdout, stderr });
468 return;
469 }
470 reject(makeHttpError(500, stderr.trim() || `${command} exited with code ${code}.`));
471 });
472 });
473}
474
475async function probeInput (sourcePath)
476{
477 const { stdout } = await runCommand(ffprobePath(), [
478 '-v', 'error',
479 '-print_format', 'json',
480 '-show_streams',
481 '-show_format',
482 sourcePath,
483 ]);
484
485 let payload;
486 try
487 {
488 payload = JSON.parse(stdout || '{}');
489 } catch
490 {
491 throw makeHttpError(500, 'ffprobe returned invalid stream metadata.');
492 }
493
494 const typedIndexes = { video: 0, audio: 0, subtitle: 0 };
495 const streams = Array.isArray(payload.streams) ? payload.streams.map((stream) =>
496 {
497 const codecType = String(stream.codec_type || '').toLowerCase();
498 const relativeIndex = Object.prototype.hasOwnProperty.call(typedIndexes, codecType)
499 ? typedIndexes[codecType]++
500 : null;
501 return {
502 ...stream,
503 codecType,
504 relativeIndex,
505 tags: stream.tags || {},
506 disposition: stream.disposition || {},
507 };
508 }) : [];
509
510 return {
511 raw: payload,
512 durationSeconds: inputDurationSeconds(payload, streams),
513 video: streams.filter((stream) => stream.codecType === 'video'),
514 audio: streams.filter((stream) => stream.codecType === 'audio'),
515 subtitles: streams.filter((stream) => stream.codecType === 'subtitle'),
516 };
517}
518
519function parsePositiveNumber (value)
520{
521 const number = Number(value);
522 return Number.isFinite(number) && number > 0 ? number : null;
523}
524
525function parseDurationTagSeconds (value)
526{
527 const raw = String(value || '').trim();
528 if (!raw) return null;
529
530 const numeric = parsePositiveNumber(raw);
531 if (numeric) return numeric;
532
533 const match = raw.match(/^(\d+):([0-5]?\d):([0-5]?\d(?:\.\d+)?)$/);
534 if (!match) return null;
535
536 const hours = Number(match[1]);
537 const minutes = Number(match[2]);
538 const seconds = Number(match[3]);
539 if (!Number.isFinite(hours) || !Number.isFinite(minutes) || !Number.isFinite(seconds)) return null;
540 return hours * 3600 + minutes * 60 + seconds;
541}
542
543function inputDurationSeconds (payload, streams)
544{
545 const formatDuration = parsePositiveNumber(payload && payload.format && payload.format.duration);
546 if (formatDuration) return formatDuration;
547
548 for (const stream of streams)
549 {
550 const duration = parsePositiveNumber(stream.duration);
551 if (duration) return duration;
552 }
553
554 const formatTags = payload && payload.format && payload.format.tags;
555 const formatTagDuration = formatTags && parseDurationTagSeconds(formatTags.duration || formatTags.DURATION);
556 if (formatTagDuration) return formatTagDuration;
557
558 for (const stream of streams)
559 {
560 const tagDuration = parseDurationTagSeconds(stream.tags.duration || stream.tags.DURATION);
561 if (tagDuration) return tagDuration;
562 }
563
564 return null;
565}
566
567function sanitiseTrackValue (value, fallback)
568{
569 const cleaned = String(value || '').trim().replace(/[^A-Za-z0-9._-]+/g, '-').replace(/^-+|-+$/g, '');
570 return cleaned || fallback;
571}
572
573function trackLanguage (stream)
574{
575 return sanitiseTrackValue(stream.tags.language || stream.tags.LANGUAGE || 'und', 'und').slice(0, 8);
576}
577
578function trackLabel (stream, fallback)
579{
580 const title = String(stream.tags.title || stream.tags.handler_name || '').trim();
581 if (title) return title;
582 const language = trackLanguage(stream);
583 if (language && language !== 'und') return `${fallback} (${language})`;
584 return fallback;
585}
586
587function findMatchingSidecarSrtPath (sourcePath)
588{
589 const absoluteSourcePath = path.resolve(String(sourcePath || ''));
590 const dirPath = path.dirname(absoluteSourcePath);
591 const baseName = path.parse(absoluteSourcePath).name;
592 const exactPath = path.join(dirPath, `${baseName}.srt`);
593
594 try
595 {
596 const exactStat = fs.statSync(exactPath);
597 if (exactStat.isFile()) return exactPath;
598 } catch
599 {
600 // Fall back to case-insensitive directory scan.
601 }
602
603 const wantedName = `${baseName}.srt`.toLowerCase();
604
605 try
606 {
607 const entries = fs.readdirSync(dirPath, { withFileTypes: true });
608 for (const entry of entries)
609 {
610 if (!entry.isFile()) continue;
611 if (entry.name.toLowerCase() !== wantedName) continue;
612 return path.join(dirPath, entry.name);
613 }
614 } catch
615 {
616 return null;
617 }
618
619 return null;
620}
621
622async function extractSubtitleTracks (sourcePath, outputDir, subtitleStreams)
623{
624 const extractedTracks = [];
625 const imageBasedTracks = [];
626 let skippedCount = 0;
627 let trackNumber = 0;
628
629 for (const stream of subtitleStreams)
630 {
631 const codecName = String(stream.codec_name || '').toLowerCase();
632
633 // Image-based subtitle formats will be shown as DOM overlays via frame extraction.
634 if (IMAGE_BASED_SUBTITLE_CODECS.has(codecName))
635 {
636 imageBasedTracks.push({
637 label: trackLabel(stream, `Subtitle ${stream.relativeIndex + 1}`),
638 language: trackLanguage(stream),
639 isDefault: !!stream.disposition.default,
640 streamIndex: stream.relativeIndex,
641 });
642 continue;
643 }
644
645 const fileName = `subtitle-${trackNumber}.vtt`;
646 const targetPath = path.join(outputDir, fileName);
647
648 try
649 {
650 await runCommand(ffmpegPath(), [
651 '-hide_banner',
652 '-loglevel', 'error',
653 '-nostdin',
654 '-y',
655 '-i', sourcePath,
656 '-map', `0:s:${stream.relativeIndex}`,
657 '-c:s', 'webvtt',
658 targetPath,
659 ]);
660 } catch
661 {
662 skippedCount += 1;
663 continue;
664 }
665
666 extractedTracks.push({
667 fileName,
668 label: trackLabel(stream, `Subtitle ${trackNumber + 1}`),
669 language: trackLanguage(stream),
670 isDefault: !!stream.disposition.default,
671 });
672 trackNumber += 1;
673 }
674
675 const sidecarSrtPath = findMatchingSidecarSrtPath(sourcePath);
676 const hasSidecarSrt = !!sidecarSrtPath;
677 if (sidecarSrtPath)
678 {
679 const fileName = `subtitle-${trackNumber}.vtt`;
680 const targetPath = path.join(outputDir, fileName);
681 try
682 {
683 await runCommand(ffmpegPath(), [
684 '-hide_banner',
685 '-loglevel', 'error',
686 '-nostdin',
687 '-y',
688 '-i', sidecarSrtPath,
689 '-c:s', 'webvtt',
690 targetPath,
691 ]);
692
693 extractedTracks.push({
694 fileName,
695 label: `Subtitle ${trackNumber + 1} (external)`,
696 language: 'und',
697 isDefault: extractedTracks.length === 0 && imageBasedTracks.length === 0,
698 });
699 trackNumber += 1;
700 } catch
701 {
702 skippedCount += 1;
703 }
704 }
705
706 return {
707 tracks: extractedTracks,
708 imageBasedTracks,
709 hasSidecarSrt,
710 skippedCount,
711 };
712}
713
714function buildHlsArgs (sourcePath, outputDir, streamInfo)
715{
716 const args = [
717 '-hide_banner',
718 '-loglevel', 'error',
719 '-nostdin',
720 '-y',
721 '-i', sourcePath,
722 '-map', '0:v:0',
723 ];
724
725 for (const audioStream of streamInfo.audio)
726 {
727 args.push('-map', `0:a:${audioStream.relativeIndex}`);
728 }
729
730 args.push(
731 '-c:v', 'libx264',
732 '-preset', 'veryfast',
733 '-crf', '23',
734 '-pix_fmt', 'yuv420p',
735 '-g', '48',
736 '-sc_threshold', '0',
737 );
738
739 if (streamInfo.audio.length)
740 {
741 args.push('-c:a', 'aac', '-b:a', '160k', '-ac', '2');
742 } else
743 {
744 args.push('-an');
745 }
746
747 const variantMap = [];
748 if (streamInfo.audio.length)
749 {
750 variantMap.push('v:0,agroup:audio,name:video');
751 streamInfo.audio.forEach((audioStream, index) =>
752 {
753 let entry = `a:${index},agroup:audio,name:${sanitiseTrackValue(trackLabel(audioStream, `Audio ${index + 1}`), `audio-${index + 1}`)},language:${trackLanguage(audioStream)}`;
754 if (audioStream.disposition.default) entry += ',default:yes';
755 variantMap.push(entry);
756 });
757 } else
758 {
759 variantMap.push('v:0,name:video');
760 }
761
762 args.push(
763 '-f', 'hls',
764 '-hls_time', '4',
765 '-hls_list_size', '0',
766 '-hls_flags', 'independent_segments+temp_file',
767 '-master_pl_name', 'master.m3u8',
768 '-hls_segment_filename', path.join(outputDir, 'stream_%v_segment_%06d.ts'),
769 '-var_stream_map', variantMap.join(' '),
770 path.join(outputDir, 'stream_%v.m3u8'),
771 );
772
773 return args;
774}
775
776function startHlsTranscode (session, streamInfo)
777{
778 const args = buildHlsArgs(session.sourcePath, session.outputDir, streamInfo);
779 const child = spawn(ffmpegPath(), args, { stdio: ['ignore', 'ignore', 'pipe'] });
780 let stderr = '';
781
782 child.stderr.on('data', (chunk) =>
783 {
784 stderr += chunk.toString();
785 if (stderr.length > 16000) stderr = stderr.slice(-16000);
786 });
787
788 child.on('error', (err) =>
789 {
790 if (err && err.code === 'ENOENT')
791 {
792 session.error = makeHttpError(503, 'ffmpeg is not installed or not available in PATH.');
793 return;
794 }
795 session.error = err;
796 });
797
798 child.on('close', (code) =>
799 {
800 session.process = null;
801 if (code === 0 || session.error) return;
802 session.error = makeHttpError(500, stderr.trim() || `ffmpeg exited with code ${code}.`);
803 });
804
805 session.process = child;
806}
807
808function waitForFile (targetPath, session, timeoutMs = STREAM_READY_TIMEOUT_MS)
809{
810 const startedAt = Date.now();
811
812 return new Promise((resolve, reject) =>
813 {
814 const check = () =>
815 {
816 if (fs.existsSync(targetPath))
817 {
818 resolve();
819 return;
820 }
821
822 if (session.error)
823 {
824 reject(session.error);
825 return;
826 }
827
828 if (Date.now() - startedAt >= timeoutMs)
829 {
830 reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
831 return;
832 }
833
834 setTimeout(check, 120);
835 };
836
837 check();
838 });
839}
840
841function waitForStreamStart (session, timeoutMs = STREAM_READY_TIMEOUT_MS)
842{
843 const startedAt = Date.now();
844
845 return new Promise((resolve, reject) =>
846 {
847 const check = () =>
848 {
849 if (fs.existsSync(path.join(session.outputDir, 'master.m3u8')) || hasInitialHlsAssets(session.outputDir))
850 {
851 resolve();
852 return;
853 }
854
855 if (session.error)
856 {
857 reject(session.error);
858 return;
859 }
860
861 if (!session.process)
862 {
863 reject(makeHttpError(500, 'Video stream preparation stopped unexpectedly.'));
864 return;
865 }
866
867 if (Date.now() - startedAt >= timeoutMs)
868 {
869 reject(makeHttpError(504, 'Timed out while preparing the video stream.'));
870 return;
871 }
872
873 setTimeout(check, 120);
874 };
875
876 check();
877 });
878}
879
880async function initialiseSession (session)
881{
882 const streamInfo = await probeInput(session.sourcePath);
883 if (!streamInfo.video.length)
884 {
885 throw makeHttpError(400, 'File does not contain a video stream.');
886 }
887
888 const primaryVideoStream = streamInfo.video[0] || {};
889 session.videoWidth = parsePositiveNumber(primaryVideoStream.width);
890 session.videoHeight = parsePositiveNumber(primaryVideoStream.height);
891
892 const subtitleResult = await extractSubtitleTracks(session.sourcePath, session.outputDir, streamInfo.subtitles);
893 session.subtitleTracks = subtitleResult.tracks;
894 session.imageSubtitleTracks = subtitleResult.imageBasedTracks;
895 session.subtitleSummary = {
896 total: streamInfo.subtitles.length + (subtitleResult.hasSidecarSrt ? 1 : 0),
897 converted: subtitleResult.tracks.length,
898 imageBased: subtitleResult.imageBasedTracks.length,
899 skipped: subtitleResult.skippedCount,
900 };
901 startHlsTranscode(session, streamInfo);
902 session.durationSeconds = streamInfo.durationSeconds;
903 await waitForStreamStart(session);
904}
905
906async function createVideoStreamSession (sourcePath)
907{
908 pruneExpiredSessions();
909 ensureStreamRootDir();
910
911 const sourceKey = String(sourcePath || '');
912 let session = null;
913
914 const reusableSessionId = reusableSessionIdBySource.get(sourceKey);
915 if (reusableSessionId)
916 {
917 const reusable = sessions.get(reusableSessionId);
918 if (reusable && !reusable.error && reusable.segmentPrunedUntil < 0)
919 {
920 session = reusable;
921 } else
922 {
923 reusableSessionIdBySource.delete(sourceKey);
924 }
925 }
926
927 if (!session)
928 {
929 const sessionId = crypto.randomBytes(18).toString('hex');
930 const outputDir = path.join(STREAM_ROOT_DIR, sessionId);
931 fs.mkdirSync(outputDir, { recursive: true });
932
933 session = {
934 id: sessionId,
935 sourcePath: String(sourcePath || ''),
936 sourceKey: sourceKey,
937 outputDir,
938 expiresAt: Date.now() + STREAM_SESSION_TTL_MS,
939 process: null,
940 error: null,
941 subtitleTracks: [],
942 imageSubtitleTracks: [],
943 subtitleSummary: { total: 0, converted: 0, imageBased: 0, skipped: 0 },
944 readyPromise: null,
945 activeRequests: 0,
946 lastActivityAt: Date.now(),
947 idleTimer: null,
948 segmentPruneRunning: false,
949 segmentPrunePendingCutoff: -1,
950 segmentPrunedUntil: -1,
951 leaseIds: new Set(),
952 };
953
954 session.readyPromise = initialiseSession(session).catch((err) =>
955 {
956 session.error = err;
957 throw err;
958 });
959
960 sessions.set(session.id, session);
961 reusableSessionIdBySource.set(sourceKey, session.id);
962 }
963
964 if (!session.leaseIds) session.leaseIds = new Set();
965 const lease = createLeaseForSession(session);
966 touchSessionActivity(session, lease);
967
968 try
969 {
970 await session.readyPromise;
971 } catch (err)
972 {
973 releaseVideoStreamSession(lease.id);
974 throw err;
975 }
976
977 return {
978 sessionId: lease.id,
979 durationSeconds: session.durationSeconds,
980 videoWidth: session.videoWidth || null,
981 videoHeight: session.videoHeight || null,
982 subtitleTracks: session.subtitleTracks.map((track) => ({ ...track })),
983 imageSubtitleTracks: (session.imageSubtitleTracks || []).map((track) => ({ ...track })),
984 subtitleSummary: {
985 total: Number(session.subtitleSummary.total || 0),
986 converted: Number(session.subtitleSummary.converted || 0),
987 imageBased: Number(session.subtitleSummary.imageBased || 0),
988 skipped: Number(session.subtitleSummary.skipped || 0),
989 },
990 };
991}
992
993function contentTypeForAsset (assetPath)
994{
995 const ext = path.extname(assetPath).toLowerCase();
996 if (ext === '.m3u8') return 'application/vnd.apple.mpegurl';
997 if (ext === '.ts') return 'video/mp2t';
998 if (ext === '.vtt') return 'text/vtt; charset=utf-8';
999 if (ext === '.aac') return 'audio/aac';
1000 if (ext === '.mp4' || ext === '.m4s') return 'video/mp4';
1001 return 'application/octet-stream';
1002}
1003
1004async function sendVideoStreamAsset (sessionId, assetPath, req, res)
1005{
1006 pruneExpiredSessions();
1007 const active = getSessionForLease(sessionId);
1008 if (!active) throw makeHttpError(404, 'Video stream session not found.');
1009
1010 const { session, lease } = active;
1011
1012 touchSessionActivity(session, lease);
1013 await session.readyPromise;
1014
1015 const relativeAssetPath = String(assetPath || 'master.m3u8').replace(/^[/\\]+/, '');
1016 const resolvedPath = path.resolve(session.outputDir, relativeAssetPath);
1017 const resolvedRoot = path.resolve(session.outputDir);
1018 if (resolvedPath !== resolvedRoot && !resolvedPath.startsWith(resolvedRoot + path.sep))
1019 {
1020 throw makeHttpError(404, 'Stream asset not found.');
1021 }
1022
1023 const segmentIndex = parseSegmentIndexFromAssetPath(relativeAssetPath);
1024 if (segmentIndex !== null) scheduleSegmentPrune(session, lease, segmentIndex);
1025
1026 await waitForFile(resolvedPath, session);
1027 res.set('Cache-Control', 'private, no-store');
1028 res.type(contentTypeForAsset(resolvedPath));
1029
1030 startAssetRequest(session, lease);
1031
1032 let settled = false;
1033 const finish = () =>
1034 {
1035 if (settled) return;
1036 settled = true;
1037 finishAssetRequest(session, lease);
1038 };
1039
1040 req.on('aborted', finish);
1041 res.on('close', finish);
1042 res.on('finish', finish);
1043 res.on('error', finish);
1044
1045 await new Promise((resolve, reject) =>
1046 {
1047 res.sendFile(resolvedPath, (err) =>
1048 {
1049 finish();
1050 if (!err)
1051 {
1052 resolve();
1053 return;
1054 }
1055
1056 if (err.code === 'ECONNABORTED' || err.message === 'Request aborted')
1057 {
1058 resolve();
1059 return;
1060 }
1061
1062 reject(err);
1063 });
1064 });
1065}
1066
1067function releaseVideoStreamSession (sessionId)
1068{
1069 const leaseId = String(sessionId || '');
1070 const active = getSessionForLease(leaseId);
1071 if (!active)
1072 {
1073 leases.delete(leaseId);
1074 return false;
1075 }
1076
1077 const { session } = active;
1078 leases.delete(leaseId);
1079 session.leaseIds.delete(leaseId);
1080
1081 if (session.leaseIds.size === 0 && session.activeRequests === 0)
1082 {
1083 return destroySession(session.id);
1084 }
1085
1086 return true;
1087}
1088
1089function collectOutputDirStats (outputDir)
1090{
1091 const stats = {
1092 exists: false,
1093 totalBytes: 0,
1094 totalFiles: 0,
1095 segmentFiles: 0,
1096 segmentBytes: 0,
1097 playlistFiles: 0,
1098 subtitleFiles: 0,
1099 };
1100
1101 if (!outputDir || !fs.existsSync(outputDir)) return stats;
1102 stats.exists = true;
1103
1104 let entries = [];
1105 try
1106 {
1107 entries = fs.readdirSync(outputDir, { withFileTypes: true });
1108 } catch
1109 {
1110 return stats;
1111 }
1112
1113 for (const entry of entries)
1114 {
1115 if (!entry.isFile()) continue;
1116 const name = entry.name;
1117 const fullPath = path.join(outputDir, name);
1118 let size = 0;
1119 try
1120 {
1121 const fileStat = fs.statSync(fullPath);
1122 size = Number(fileStat.size) || 0;
1123 } catch
1124 {
1125 size = 0;
1126 }
1127
1128 stats.totalFiles += 1;
1129 stats.totalBytes += size;
1130
1131 if (/\.ts$/i.test(name))
1132 {
1133 stats.segmentFiles += 1;
1134 stats.segmentBytes += size;
1135 continue;
1136 }
1137
1138 if (/\.m3u8$/i.test(name))
1139 {
1140 stats.playlistFiles += 1;
1141 continue;
1142 }
1143
1144 if (/\.(sup|vtt)$/i.test(name))
1145 {
1146 stats.subtitleFiles += 1;
1147 }
1148 }
1149
1150 return stats;
1151}
1152
1153function getVideoStreamDebugSnapshot ()
1154{
1155 const activeStreams = [];
1156
1157 for (const [sessionId, session] of sessions.entries())
1158 {
1159 activeStreams.push({
1160 sessionId,
1161 sourcePath: session.sourcePath,
1162 outputDir: session.outputDir,
1163 viewers: session.leaseIds ? session.leaseIds.size : 0,
1164 activeRequests: Number(session.activeRequests || 0),
1165 expiresAt: Number(session.expiresAt || 0),
1166 output: collectOutputDirStats(session.outputDir),
1167 });
1168 }
1169
1170 const knownSessionDirs = new Set(activeStreams.map((stream) => path.resolve(stream.outputDir || '')));
1171 const orphanedOutputDirs = [];
1172 try
1173 {
1174 const entries = fs.readdirSync(STREAM_ROOT_DIR, { withFileTypes: true });
1175 for (const entry of entries)
1176 {
1177 if (!entry.isDirectory()) continue;
1178 const dirPath = path.resolve(path.join(STREAM_ROOT_DIR, entry.name));
1179 if (knownSessionDirs.has(dirPath)) continue;
1180 orphanedOutputDirs.push({
1181 outputDir: dirPath,
1182 output: collectOutputDirStats(dirPath),
1183 });
1184 }
1185 } catch
1186 {
1187 // Stream root may not exist yet.
1188 }
1189
1190 return {
1191 streamRootDir: STREAM_ROOT_DIR,
1192 activeSessionCount: sessions.size,
1193 activeLeaseCount: leases.size,
1194 activeStreams,
1195 orphanedOutputDirs,
1196 };
1197}
1198
1199module.exports = {
1200 STREAM_ROOT_DIR,
1201 STREAM_SESSION_TTL_MS,
1202 STREAM_IDLE_STOP_MS,
1203 STREAM_SEGMENT_RETENTION_COUNT,
1204 createVideoStreamSession,
1205 sendVideoStreamAsset,
1206 releaseVideoStreamSession,
1207 getVideoStreamDebugSnapshot,
1208 cleanupIdleStreamArtifacts,
1209};