BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

e5da312e History
video-stream.test.js 29.6 KiB Download Raw
1'use strict';
2
3const { EventEmitter } = require('events');
4const fs = require('fs');
5const os = require('os');
6const path = require('path');
7
8jest.mock('child_process', () => ({
9 spawn: jest.fn(),
10}));
11
12jest.mock('../server/image-subtitles', () => ({
13 clearCachesForFile: jest.fn(),
14 pruneOldImageSubtitleCaches: jest.fn(),
15 purgeSubtitleCacheDir: jest.fn(),
16}));
17
18function makeChildProcess ()
19{
20 const child = new EventEmitter();
21 child.stdout = new EventEmitter();
22 child.stderr = new EventEmitter();
23 child.kill = jest.fn();
24 return child;
25}
26
27function makeReqRes ()
28{
29 const req = new EventEmitter();
30 const res = new EventEmitter();
31 const headers = {};
32
33 res.set = (name, value) =>
34 {
35 headers[name] = value;
36 return res;
37 };
38 res.type = () => res;
39 res.sendFile = (targetPath, cb) =>
40 {
41 process.nextTick(() =>
42 {
43 if (!fs.existsSync(targetPath))
44 {
45 const err = new Error('File not found');
46 err.code = 'ENOENT';
47 cb(err);
48 return;
49 }
50
51 res.emit('finish');
52 cb();
53 });
54 };
55
56 return { req, res, headers };
57}
58
59describe('video stream bootstrap', () =>
60{
61 let mockSpawn;
62 let sourceFile;
63
64 beforeEach(() =>
65 {
66 jest.resetModules();
67 mockSpawn = require('child_process').spawn;
68 mockSpawn.mockReset();
69
70 const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-'));
71 sourceFile = path.join(tmpDir, 'clip.mkv');
72 fs.writeFileSync(sourceFile, 'video');
73 });
74
75 test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () =>
76 {
77 mockSpawn.mockImplementation((command, args) =>
78 {
79 const child = makeChildProcess();
80 const exeName = path.basename(String(command || '')).toLowerCase();
81
82 if (exeName.includes('ffprobe'))
83 {
84 process.nextTick(() =>
85 {
86 child.stdout.emit('data', Buffer.from(JSON.stringify({
87 format: { duration: '12.5' },
88 streams: [
89 { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} },
90 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
91 ],
92 })));
93 child.emit('close', 0);
94 });
95 return child;
96 }
97
98 expect(exeName.includes('ffmpeg')).toBe(true);
99
100 const outputPattern = String(args[args.length - 1] || '');
101 const outputDir = path.dirname(outputPattern);
102
103 process.nextTick(() =>
104 {
105 fs.mkdirSync(outputDir, { recursive: true });
106 setTimeout(() =>
107 {
108 fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n');
109 }, 40);
110 });
111
112 return child;
113 });
114
115 const { createVideoStreamSession } = require('../server/video-stream');
116 const session = await createVideoStreamSession(sourceFile);
117
118 expect(session).toEqual({
119 sessionId: expect.any(String),
120 durationSeconds: 12.5,
121 videoWidth: 1920,
122 videoHeight: 1080,
123 subtitleTracks: [],
124 imageSubtitleTracks: [],
125 subtitleSummary: {
126 total: 0,
127 converted: 0,
128 imageBased: 0,
129 skipped: 0,
130 },
131 });
132 });
133
134 test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>
135 {
136 mockSpawn.mockImplementation((command, args) =>
137 {
138 const child = makeChildProcess();
139 const exeName = path.basename(String(command || '')).toLowerCase();
140
141 if (exeName.includes('ffprobe'))
142 {
143 process.nextTick(() =>
144 {
145 child.stdout.emit('data', Buffer.from(JSON.stringify({
146 streams: [
147 { codec_type: 'video', codec_name: 'h264', width: 1280, height: 720, tags: {}, disposition: {} },
148 { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },
149 ],
150 })));
151 child.emit('close', 0);
152 });
153 return child;
154 }
155
156 const segmentArgIndex = args.indexOf('-hls_segment_filename');
157 expect(segmentArgIndex).toBeGreaterThan(-1);
158 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
159 expect(args).not.toContain('-hls_playlist_type');
160
161 const playlistPath = String(args[args.length - 1] || '');
162 const outputDir = path.dirname(playlistPath);
163 process.nextTick(() =>
164 {
165 fs.mkdirSync(outputDir, { recursive: true });
166 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
167 });
168
169 return child;
170 });
171
172 const { createVideoStreamSession } = require('../server/video-stream');
173 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
174 sessionId: expect.any(String),
175 durationSeconds: null,
176 videoWidth: 1280,
177 videoHeight: 720,
178 subtitleTracks: [],
179 imageSubtitleTracks: [],
180 subtitleSummary: {
181 total: 0,
182 converted: 0,
183 imageBased: 0,
184 skipped: 0,
185 },
186 });
187 });
188
189 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
190 {
191 mockSpawn.mockImplementation((command, args) =>
192 {
193 const child = makeChildProcess();
194 const exeName = path.basename(String(command || '')).toLowerCase();
195
196 if (exeName.includes('ffprobe'))
197 {
198 process.nextTick(() =>
199 {
200 child.stdout.emit('data', Buffer.from(JSON.stringify({
201 streams: [
202 { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
203 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
204 ],
205 })));
206 child.emit('close', 0);
207 });
208 return child;
209 }
210
211 const playlistPath = String(args[args.length - 1] || '');
212 const outputDir = path.dirname(playlistPath);
213 process.nextTick(() =>
214 {
215 fs.mkdirSync(outputDir, { recursive: true });
216 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
217 });
218
219 return child;
220 });
221
222 const { createVideoStreamSession } = require('../server/video-stream');
223 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
224 durationSeconds: 1337.5,
225 });
226 });
227
228 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
229 {
230 mockSpawn.mockImplementation((command, args) =>
231 {
232 const child = makeChildProcess();
233 const exeName = path.basename(String(command || '')).toLowerCase();
234
235 if (exeName.includes('ffprobe'))
236 {
237 process.nextTick(() =>
238 {
239 child.stdout.emit('data', Buffer.from(JSON.stringify({
240 streams: [
241 { codec_type: 'video', codec_name: 'h264', width: 1024, height: 576, tags: {}, disposition: {} },
242 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
243 { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} },
244 ],
245 })));
246 child.emit('close', 0);
247 });
248 return child;
249 }
250
251 const mapIndex = args.indexOf('-map');
252 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
253
254 if (mappedValue.startsWith('0:s:'))
255 {
256 const subtitleTarget = String(args[args.length - 1] || '');
257 process.nextTick(() =>
258 {
259 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
260 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
261 child.emit('close', 0);
262 });
263 return child;
264 }
265
266 const playlistPath = String(args[args.length - 1] || '');
267 const outputDir = path.dirname(playlistPath);
268 process.nextTick(() =>
269 {
270 fs.mkdirSync(outputDir, { recursive: true });
271 setTimeout(() =>
272 {
273 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
274 }, 80);
275 });
276
277 return child;
278 });
279
280 const { createVideoStreamSession } = require('../server/video-stream');
281 const startedAt = Date.now();
282 const session = await createVideoStreamSession(sourceFile);
283 const elapsedMs = Date.now() - startedAt;
284
285 expect(elapsedMs).toBeGreaterThanOrEqual(60);
286 expect(session).toEqual({
287 sessionId: expect.any(String),
288 durationSeconds: null,
289 videoWidth: 1024,
290 videoHeight: 576,
291 subtitleTracks: [
292 expect.objectContaining({
293 fileName: 'subtitle-0.vtt',
294 language: 'eng',
295 }),
296 ],
297 imageSubtitleTracks: [],
298 subtitleSummary: {
299 total: 1,
300 converted: 1,
301 imageBased: 0,
302 skipped: 0,
303 },
304 });
305 });
306
307 test('createVideoStreamSession includes matching sidecar srt subtitles', async () =>
308 {
309 fs.writeFileSync(path.join(path.dirname(sourceFile), 'clip.srt'), '1\n00:00:00,000 --> 00:00:01,000\nHello\n');
310
311 mockSpawn.mockImplementation((command, args) =>
312 {
313 const child = makeChildProcess();
314 const exeName = path.basename(String(command || '')).toLowerCase();
315
316 if (exeName.includes('ffprobe'))
317 {
318 process.nextTick(() =>
319 {
320 child.stdout.emit('data', Buffer.from(JSON.stringify({
321 streams: [
322 { codec_type: 'video', codec_name: 'h264', width: 854, height: 480, tags: {}, disposition: {} },
323 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
324 ],
325 })));
326 child.emit('close', 0);
327 });
328 return child;
329 }
330
331 const subtitleTarget = String(args[args.length - 1] || '');
332 if (args.includes('-c:s') && args.includes('webvtt') && subtitleTarget.endsWith('.vtt'))
333 {
334 process.nextTick(() =>
335 {
336 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
337 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
338 child.emit('close', 0);
339 });
340 return child;
341 }
342
343 const playlistPath = String(args[args.length - 1] || '');
344 const outputDir = path.dirname(playlistPath);
345 process.nextTick(() =>
346 {
347 fs.mkdirSync(outputDir, { recursive: true });
348 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
349 });
350
351 return child;
352 });
353
354 const { createVideoStreamSession } = require('../server/video-stream');
355 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
356 sessionId: expect.any(String),
357 durationSeconds: null,
358 videoWidth: 854,
359 videoHeight: 480,
360 subtitleTracks: [
361 expect.objectContaining({
362 fileName: 'subtitle-0.vtt',
363 language: 'und',
364 isDefault: true,
365 }),
366 ],
367 imageSubtitleTracks: [],
368 subtitleSummary: {
369 total: 1,
370 converted: 1,
371 imageBased: 0,
372 skipped: 0,
373 },
374 });
375 });
376
377 test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>
378 {
379 mockSpawn.mockImplementation((command, args) =>
380 {
381 const child = makeChildProcess();
382 const exeName = path.basename(String(command || '')).toLowerCase();
383
384 if (exeName.includes('ffprobe'))
385 {
386 process.nextTick(() =>
387 {
388 child.stdout.emit('data', Buffer.from(JSON.stringify({
389 streams: [
390 { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} },
391 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
392 { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },
393 ],
394 })));
395 child.emit('close', 0);
396 });
397 return child;
398 }
399
400 const mapIndex = args.indexOf('-map');
401 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
402
403 // Fail subtitle extraction but keep HLS transcoding path successful.
404 if (mappedValue.startsWith('0:s:'))
405 {
406 process.nextTick(() =>
407 {
408 child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));
409 child.emit('close', 1);
410 });
411 return child;
412 }
413
414 const playlistPath = String(args[args.length - 1] || '');
415 const outputDir = path.dirname(playlistPath);
416 process.nextTick(() =>
417 {
418 fs.mkdirSync(outputDir, { recursive: true });
419 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
420 });
421
422 return child;
423 });
424
425 const { createVideoStreamSession } = require('../server/video-stream');
426 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
427 sessionId: expect.any(String),
428 durationSeconds: null,
429 videoWidth: 1920,
430 videoHeight: 1080,
431 subtitleTracks: [],
432 imageSubtitleTracks: [
433 expect.objectContaining({
434 label: 'Subtitle 1 (eng)',
435 language: 'eng',
436 streamIndex: 0,
437 }),
438 ],
439 subtitleSummary: {
440 total: 1,
441 converted: 0,
442 imageBased: 1,
443 skipped: 0,
444 },
445 });
446 });
447
448 test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () =>
449 {
450 mockSpawn.mockImplementation((command, args) =>
451 {
452 const child = makeChildProcess();
453 const exeName = path.basename(String(command || '')).toLowerCase();
454
455 if (exeName.includes('ffprobe'))
456 {
457 process.nextTick(() =>
458 {
459 child.stdout.emit('data', Buffer.from(JSON.stringify({
460 streams: [
461 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
462 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
463 ],
464 })));
465 child.emit('close', 0);
466 });
467 return child;
468 }
469
470 const playlistPath = String(args[args.length - 1] || '');
471 const outputDir = path.dirname(playlistPath);
472 process.nextTick(() =>
473 {
474 fs.mkdirSync(outputDir, { recursive: true });
475 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
476 });
477 return child;
478 });
479
480 const streamModule = require('../server/video-stream');
481 const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles');
482 const beforeDirs = new Set(
483 fs.existsSync(streamModule.STREAM_ROOT_DIR)
484 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
485 : []
486 );
487 const session = await streamModule.createVideoStreamSession(sourceFile);
488 const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
489 const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName));
490 expect(newDirName).toEqual(expect.any(String));
491 const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));
492 expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);
493 const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
494
495 // ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries.
496 // With one video + one audio stream the names are 'video' and 'Audio-1'.
497 for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)
498 {
499 const pad = String(segmentIndex).padStart(6, '0');
500 fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
501 fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
502 }
503
504 const { req, res } = makeReqRes();
505 await streamModule.sendVideoStreamAsset(
506 session.sessionId,
507 `stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
508 req,
509 res
510 );
511
512 await new Promise((resolve) => setTimeout(resolve, 80));
513
514 expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false);
515 expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true);
516 expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false);
517 expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true);
518 expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();
519
520 streamModule.releaseVideoStreamSession(session.sessionId);
521 });
522
523 test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () =>
524 {
525 mockSpawn.mockImplementation((command, args) =>
526 {
527 const child = makeChildProcess();
528 const exeName = path.basename(String(command || '')).toLowerCase();
529 if (exeName.includes('ffprobe'))
530 {
531 process.nextTick(() =>
532 {
533 child.stdout.emit('data', Buffer.from(JSON.stringify({
534 streams: [
535 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
536 ],
537 })));
538 child.emit('close', 0);
539 });
540 return child;
541 }
542 const outputDir = path.dirname(String(args[args.length - 1] || ''));
543 process.nextTick(() =>
544 {
545 fs.mkdirSync(outputDir, { recursive: true });
546 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
547 });
548 return child;
549 });
550
551 const streamModule = require('../server/video-stream');
552 const beforeDirs = new Set(
553 fs.existsSync(streamModule.STREAM_ROOT_DIR)
554 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
555 : []
556 );
557 const session = await streamModule.createVideoStreamSession(sourceFile);
558 const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d));
559 const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));
560
561 // Write a small number of named-variant segments (below the retention window).
562 const segmentCount = 10;
563 for (let i = 0; i < segmentCount; i += 1)
564 {
565 fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`);
566 }
567
568 const { req, res } = makeReqRes();
569 await streamModule.sendVideoStreamAsset(
570 session.sessionId,
571 `stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`,
572 req,
573 res
574 );
575
576 // Segment count is below retention threshold — nothing should be deleted.
577 expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount);
578
579 streamModule.releaseVideoStreamSession(session.sessionId);
580 });
581
582 test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>
583 {
584 mockSpawn.mockImplementation((command, args) =>
585 {
586 const child = makeChildProcess();
587 const exeName = path.basename(String(command || '')).toLowerCase();
588
589 if (exeName.includes('ffprobe'))
590 {
591 process.nextTick(() =>
592 {
593 child.stdout.emit('data', Buffer.from(JSON.stringify({
594 streams: [
595 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
596 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
597 ],
598 })));
599 child.emit('close', 0);
600 });
601 return child;
602 }
603
604 const playlistPath = String(args[args.length - 1] || '');
605 const outputDir = path.dirname(playlistPath);
606 process.nextTick(() =>
607 {
608 fs.mkdirSync(outputDir, { recursive: true });
609 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
610 });
611 return child;
612 });
613
614 const streamModule = require('../server/video-stream');
615 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
616 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
617
618 expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId);
619
620 const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) =>
621 path.basename(String(command || '')).toLowerCase().includes('ffmpeg')
622 );
623 expect(ffmpegSpawns).toHaveLength(1);
624
625 const firstReqRes = makeReqRes();
626 await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res);
627
628 const secondReqRes = makeReqRes();
629 await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res);
630
631 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
632
633 const stillActiveReqRes = makeReqRes();
634 await expect(
635 streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res)
636 ).resolves.toBeUndefined();
637
638 const releasedReqRes = makeReqRes();
639 await expect(
640 streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res)
641 ).rejects.toMatchObject({ status: 404 });
642
643 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
644 });
645
646 test('prunes subtitle caches using the slowest viewer across same-file sessions', async () =>
647 {
648 mockSpawn.mockImplementation((command, args) =>
649 {
650 const child = makeChildProcess();
651 const exeName = path.basename(String(command || '')).toLowerCase();
652
653 if (exeName.includes('ffprobe'))
654 {
655 process.nextTick(() =>
656 {
657 child.stdout.emit('data', Buffer.from(JSON.stringify({
658 streams: [
659 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
660 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
661 ],
662 })));
663 child.emit('close', 0);
664 });
665 return child;
666 }
667
668 const playlistPath = String(args[args.length - 1] || '');
669 const outputDir = path.dirname(playlistPath);
670 process.nextTick(() =>
671 {
672 fs.mkdirSync(outputDir, { recursive: true });
673 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
674 });
675 return child;
676 });
677
678 const streamModule = require('../server/video-stream');
679 const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles');
680 const beforeDirs = new Set(
681 fs.existsSync(streamModule.STREAM_ROOT_DIR)
682 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
683 : []
684 );
685
686 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
687 const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
688 const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));
689 const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));
690 const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
691
692 for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1)
693 {
694 const pad = String(segmentIndex).padStart(6, '0');
695 fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
696 fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
697 }
698
699 let reqRes = makeReqRes();
700 await streamModule.sendVideoStreamAsset(
701 firstViewer.sessionId,
702 `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,
703 reqRes.req,
704 reqRes.res
705 );
706
707 await new Promise((resolve) => setTimeout(resolve, 80));
708
709 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
710 const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
711 const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName));
712 const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || ''));
713
714 fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1');
715
716 reqRes = makeReqRes();
717 await streamModule.sendVideoStreamAsset(
718 secondViewer.sessionId,
719 'stream_video_segment_000001.ts',
720 reqRes.req,
721 reqRes.res
722 );
723
724 pruneOldImageSubtitleCaches.mockClear();
725
726 reqRes = makeReqRes();
727 await streamModule.sendVideoStreamAsset(
728 firstViewer.sessionId,
729 `stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`,
730 reqRes.req,
731 reqRes.res
732 );
733
734 await new Promise((resolve) => setTimeout(resolve, 80));
735
736 expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6);
737
738 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
739 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
740 });
741
742 test('purges subtitle disk cache when the module is first loaded', () =>
743 {
744 const { purgeSubtitleCacheDir } = require('../server/image-subtitles');
745 require('../server/video-stream');
746 expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1);
747 });
748
749 test('purges stream output directory when the module is first loaded', () =>
750 {
751 const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams');
752 const orphanDir = path.join(streamRoot, 'orphan-after-restart');
753 fs.mkdirSync(orphanDir, { recursive: true });
754 fs.writeFileSync(path.join(orphanDir, 'stream_0_segment_000001.ts'), 'segment');
755
756 require('../server/video-stream');
757 expect(fs.existsSync(orphanDir)).toBe(false);
758 });
759
760 test('cleanupIdleStreamArtifacts removes stream output directory when no streams are active', () =>
761 {
762 const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams');
763 const orphanDir = path.join(streamRoot, 'orphan-idle-cleanup');
764 fs.mkdirSync(orphanDir, { recursive: true });
765 fs.writeFileSync(path.join(orphanDir, 'stream_0.m3u8'), '#EXTM3U\n');
766
767 const streamModule = require('../server/video-stream');
768 streamModule.cleanupIdleStreamArtifacts();
769
770 expect(fs.existsSync(orphanDir)).toBe(false);
771 });
772
773 test('clears subtitle caches for a video when its last stream is released', async () =>
774 {
775 mockSpawn.mockImplementation((command, args) =>
776 {
777 const child = makeChildProcess();
778 const exeName = path.basename(String(command || '')).toLowerCase();
779
780 if (exeName.includes('ffprobe'))
781 {
782 process.nextTick(() =>
783 {
784 child.stdout.emit('data', Buffer.from(JSON.stringify({
785 streams: [
786 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
787 ],
788 })));
789 child.emit('close', 0);
790 });
791 return child;
792 }
793
794 const playlistPath = String(args[args.length - 1] || '');
795 const outputDir = path.dirname(playlistPath);
796 process.nextTick(() =>
797 {
798 fs.mkdirSync(outputDir, { recursive: true });
799 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
800 });
801 return child;
802 });
803
804 const streamModule = require('../server/video-stream');
805 const { clearCachesForFile } = require('../server/image-subtitles');
806
807 const session = await streamModule.createVideoStreamSession(sourceFile);
808 clearCachesForFile.mockClear();
809
810 streamModule.releaseVideoStreamSession(session.sessionId);
811 expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);
812 });
813
814 test('keeps subtitle caches while another same-file session is still active', async () =>
815 {
816 mockSpawn.mockImplementation((command, args) =>
817 {
818 const child = makeChildProcess();
819 const exeName = path.basename(String(command || '')).toLowerCase();
820
821 if (exeName.includes('ffprobe'))
822 {
823 process.nextTick(() =>
824 {
825 child.stdout.emit('data', Buffer.from(JSON.stringify({
826 streams: [
827 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
828 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
829 ],
830 })));
831 child.emit('close', 0);
832 });
833 return child;
834 }
835
836 const playlistPath = String(args[args.length - 1] || '');
837 const outputDir = path.dirname(playlistPath);
838 process.nextTick(() =>
839 {
840 fs.mkdirSync(outputDir, { recursive: true });
841 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
842 });
843 return child;
844 });
845
846 const streamModule = require('../server/video-stream');
847 const { clearCachesForFile } = require('../server/image-subtitles');
848 const beforeDirs = new Set(
849 fs.existsSync(streamModule.STREAM_ROOT_DIR)
850 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
851 : []
852 );
853
854 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
855 const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
856 const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));
857 const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));
858 const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
859
860 for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1)
861 {
862 const pad = String(segmentIndex).padStart(6, '0');
863 fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
864 fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
865 }
866
867 let reqRes = makeReqRes();
868 await streamModule.sendVideoStreamAsset(
869 firstViewer.sessionId,
870 `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,
871 reqRes.req,
872 reqRes.res
873 );
874
875 await new Promise((resolve) => setTimeout(resolve, 80));
876
877 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
878 clearCachesForFile.mockClear();
879
880 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
881 expect(clearCachesForFile).not.toHaveBeenCalled();
882
883 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
884 expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);
885 });
886});