BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

50e24563 History
video-stream.test.js 19.7 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 for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)
496 {
497 const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;
498 fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);
499 }
500
501 const { req, res } = makeReqRes();
502 await streamModule.sendVideoStreamAsset(
503 session.sessionId,
504 `stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
505 req,
506 res
507 );
508
509 await new Promise((resolve) => setTimeout(resolve, 80));
510
511 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);
512 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);
513 expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();
514
515 streamModule.releaseVideoStreamSession(session.sessionId);
516 });
517
518 test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>
519 {
520 mockSpawn.mockImplementation((command, args) =>
521 {
522 const child = makeChildProcess();
523 const exeName = path.basename(String(command || '')).toLowerCase();
524
525 if (exeName.includes('ffprobe'))
526 {
527 process.nextTick(() =>
528 {
529 child.stdout.emit('data', Buffer.from(JSON.stringify({
530 streams: [
531 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
532 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
533 ],
534 })));
535 child.emit('close', 0);
536 });
537 return child;
538 }
539
540 const playlistPath = String(args[args.length - 1] || '');
541 const outputDir = path.dirname(playlistPath);
542 process.nextTick(() =>
543 {
544 fs.mkdirSync(outputDir, { recursive: true });
545 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
546 });
547 return child;
548 });
549
550 const streamModule = require('../server/video-stream');
551 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
552 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
553
554 expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId);
555
556 const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) =>
557 path.basename(String(command || '')).toLowerCase().includes('ffmpeg')
558 );
559 expect(ffmpegSpawns).toHaveLength(1);
560
561 const firstReqRes = makeReqRes();
562 await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res);
563
564 const secondReqRes = makeReqRes();
565 await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res);
566
567 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
568
569 const stillActiveReqRes = makeReqRes();
570 await expect(
571 streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res)
572 ).resolves.toBeUndefined();
573
574 const releasedReqRes = makeReqRes();
575 await expect(
576 streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res)
577 ).rejects.toMatchObject({ status: 404 });
578
579 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
580 });
581
582 test('purges subtitle disk cache when the module is first loaded', () =>
583 {
584 const { purgeSubtitleCacheDir } = require('../server/image-subtitles');
585 require('../server/video-stream');
586 expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1);
587 });
588
589 test('clears subtitle caches for a video when its last stream is released', async () =>
590 {
591 mockSpawn.mockImplementation((command, args) =>
592 {
593 const child = makeChildProcess();
594 const exeName = path.basename(String(command || '')).toLowerCase();
595
596 if (exeName.includes('ffprobe'))
597 {
598 process.nextTick(() =>
599 {
600 child.stdout.emit('data', Buffer.from(JSON.stringify({
601 streams: [
602 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
603 ],
604 })));
605 child.emit('close', 0);
606 });
607 return child;
608 }
609
610 const playlistPath = String(args[args.length - 1] || '');
611 const outputDir = path.dirname(playlistPath);
612 process.nextTick(() =>
613 {
614 fs.mkdirSync(outputDir, { recursive: true });
615 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
616 });
617 return child;
618 });
619
620 const streamModule = require('../server/video-stream');
621 const { clearCachesForFile } = require('../server/image-subtitles');
622
623 const session = await streamModule.createVideoStreamSession(sourceFile);
624 clearCachesForFile.mockClear();
625
626 streamModule.releaseVideoStreamSession(session.sessionId);
627 expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);
628 });
629});