BlueGit

timfa filemanager

Files

filemanager / server / video-stream.js

video-stream.js

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