BlueGit

timfa filemanager

Files

filemanager / server / video-stream.js

video-stream.js

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