BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

video-stream.test.js 18.1 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}));
16
17function makeChildProcess ()
18{
19 const child = new EventEmitter();
20 child.stdout = new EventEmitter();
21 child.stderr = new EventEmitter();
22 child.kill = jest.fn();
23 return child;
24}
25
26function makeReqRes ()
27{
28 const req = new EventEmitter();
29 const res = new EventEmitter();
30 const headers = {};
31
32 res.set = (name, value) =>
33 {
34 headers[name] = value;
35 return res;
36 };
37 res.type = () => res;
38 res.sendFile = (targetPath, cb) =>
39 {
40 process.nextTick(() =>
41 {
42 if (!fs.existsSync(targetPath))
43 {
44 const err = new Error('File not found');
45 err.code = 'ENOENT';
46 cb(err);
47 return;
48 }
49
50 res.emit('finish');
51 cb();
52 });
53 };
54
55 return { req, res, headers };
56}
57
58describe('video stream bootstrap', () =>
59{
60 let mockSpawn;
61 let sourceFile;
62
63 beforeEach(() =>
64 {
65 jest.resetModules();
66 mockSpawn = require('child_process').spawn;
67 mockSpawn.mockReset();
68
69 const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-'));
70 sourceFile = path.join(tmpDir, 'clip.mkv');
71 fs.writeFileSync(sourceFile, 'video');
72 });
73
74 test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () =>
75 {
76 mockSpawn.mockImplementation((command, args) =>
77 {
78 const child = makeChildProcess();
79 const exeName = path.basename(String(command || '')).toLowerCase();
80
81 if (exeName.includes('ffprobe'))
82 {
83 process.nextTick(() =>
84 {
85 child.stdout.emit('data', Buffer.from(JSON.stringify({
86 format: { duration: '12.5' },
87 streams: [
88 { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} },
89 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
90 ],
91 })));
92 child.emit('close', 0);
93 });
94 return child;
95 }
96
97 expect(exeName.includes('ffmpeg')).toBe(true);
98
99 const outputPattern = String(args[args.length - 1] || '');
100 const outputDir = path.dirname(outputPattern);
101
102 process.nextTick(() =>
103 {
104 fs.mkdirSync(outputDir, { recursive: true });
105 setTimeout(() =>
106 {
107 fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n');
108 }, 40);
109 });
110
111 return child;
112 });
113
114 const { createVideoStreamSession } = require('../server/video-stream');
115 const session = await createVideoStreamSession(sourceFile);
116
117 expect(session).toEqual({
118 sessionId: expect.any(String),
119 durationSeconds: 12.5,
120 videoWidth: 1920,
121 videoHeight: 1080,
122 subtitleTracks: [],
123 imageSubtitleTracks: [],
124 subtitleSummary: {
125 total: 0,
126 converted: 0,
127 imageBased: 0,
128 skipped: 0,
129 },
130 });
131 });
132
133 test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>
134 {
135 mockSpawn.mockImplementation((command, args) =>
136 {
137 const child = makeChildProcess();
138 const exeName = path.basename(String(command || '')).toLowerCase();
139
140 if (exeName.includes('ffprobe'))
141 {
142 process.nextTick(() =>
143 {
144 child.stdout.emit('data', Buffer.from(JSON.stringify({
145 streams: [
146 { codec_type: 'video', codec_name: 'h264', width: 1280, height: 720, tags: {}, disposition: {} },
147 { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },
148 ],
149 })));
150 child.emit('close', 0);
151 });
152 return child;
153 }
154
155 const segmentArgIndex = args.indexOf('-hls_segment_filename');
156 expect(segmentArgIndex).toBeGreaterThan(-1);
157 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
158 expect(args).not.toContain('-hls_playlist_type');
159
160 const playlistPath = String(args[args.length - 1] || '');
161 const outputDir = path.dirname(playlistPath);
162 process.nextTick(() =>
163 {
164 fs.mkdirSync(outputDir, { recursive: true });
165 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
166 });
167
168 return child;
169 });
170
171 const { createVideoStreamSession } = require('../server/video-stream');
172 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
173 sessionId: expect.any(String),
174 durationSeconds: null,
175 videoWidth: 1280,
176 videoHeight: 720,
177 subtitleTracks: [],
178 imageSubtitleTracks: [],
179 subtitleSummary: {
180 total: 0,
181 converted: 0,
182 imageBased: 0,
183 skipped: 0,
184 },
185 });
186 });
187
188 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
189 {
190 mockSpawn.mockImplementation((command, args) =>
191 {
192 const child = makeChildProcess();
193 const exeName = path.basename(String(command || '')).toLowerCase();
194
195 if (exeName.includes('ffprobe'))
196 {
197 process.nextTick(() =>
198 {
199 child.stdout.emit('data', Buffer.from(JSON.stringify({
200 streams: [
201 { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
202 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
203 ],
204 })));
205 child.emit('close', 0);
206 });
207 return child;
208 }
209
210 const playlistPath = String(args[args.length - 1] || '');
211 const outputDir = path.dirname(playlistPath);
212 process.nextTick(() =>
213 {
214 fs.mkdirSync(outputDir, { recursive: true });
215 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
216 });
217
218 return child;
219 });
220
221 const { createVideoStreamSession } = require('../server/video-stream');
222 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
223 durationSeconds: 1337.5,
224 });
225 });
226
227 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
228 {
229 mockSpawn.mockImplementation((command, args) =>
230 {
231 const child = makeChildProcess();
232 const exeName = path.basename(String(command || '')).toLowerCase();
233
234 if (exeName.includes('ffprobe'))
235 {
236 process.nextTick(() =>
237 {
238 child.stdout.emit('data', Buffer.from(JSON.stringify({
239 streams: [
240 { codec_type: 'video', codec_name: 'h264', width: 1024, height: 576, tags: {}, disposition: {} },
241 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
242 { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} },
243 ],
244 })));
245 child.emit('close', 0);
246 });
247 return child;
248 }
249
250 const mapIndex = args.indexOf('-map');
251 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
252
253 if (mappedValue.startsWith('0:s:'))
254 {
255 const subtitleTarget = String(args[args.length - 1] || '');
256 process.nextTick(() =>
257 {
258 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
259 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
260 child.emit('close', 0);
261 });
262 return child;
263 }
264
265 const playlistPath = String(args[args.length - 1] || '');
266 const outputDir = path.dirname(playlistPath);
267 process.nextTick(() =>
268 {
269 fs.mkdirSync(outputDir, { recursive: true });
270 setTimeout(() =>
271 {
272 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
273 }, 80);
274 });
275
276 return child;
277 });
278
279 const { createVideoStreamSession } = require('../server/video-stream');
280 const startedAt = Date.now();
281 const session = await createVideoStreamSession(sourceFile);
282 const elapsedMs = Date.now() - startedAt;
283
284 expect(elapsedMs).toBeGreaterThanOrEqual(60);
285 expect(session).toEqual({
286 sessionId: expect.any(String),
287 durationSeconds: null,
288 videoWidth: 1024,
289 videoHeight: 576,
290 subtitleTracks: [
291 expect.objectContaining({
292 fileName: 'subtitle-0.vtt',
293 language: 'eng',
294 }),
295 ],
296 imageSubtitleTracks: [],
297 subtitleSummary: {
298 total: 1,
299 converted: 1,
300 imageBased: 0,
301 skipped: 0,
302 },
303 });
304 });
305
306 test('createVideoStreamSession includes matching sidecar srt subtitles', async () =>
307 {
308 fs.writeFileSync(path.join(path.dirname(sourceFile), 'clip.srt'), '1\n00:00:00,000 --> 00:00:01,000\nHello\n');
309
310 mockSpawn.mockImplementation((command, args) =>
311 {
312 const child = makeChildProcess();
313 const exeName = path.basename(String(command || '')).toLowerCase();
314
315 if (exeName.includes('ffprobe'))
316 {
317 process.nextTick(() =>
318 {
319 child.stdout.emit('data', Buffer.from(JSON.stringify({
320 streams: [
321 { codec_type: 'video', codec_name: 'h264', width: 854, height: 480, tags: {}, disposition: {} },
322 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
323 ],
324 })));
325 child.emit('close', 0);
326 });
327 return child;
328 }
329
330 const subtitleTarget = String(args[args.length - 1] || '');
331 if (args.includes('-c:s') && args.includes('webvtt') && subtitleTarget.endsWith('.vtt'))
332 {
333 process.nextTick(() =>
334 {
335 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
336 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
337 child.emit('close', 0);
338 });
339 return child;
340 }
341
342 const playlistPath = String(args[args.length - 1] || '');
343 const outputDir = path.dirname(playlistPath);
344 process.nextTick(() =>
345 {
346 fs.mkdirSync(outputDir, { recursive: true });
347 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
348 });
349
350 return child;
351 });
352
353 const { createVideoStreamSession } = require('../server/video-stream');
354 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
355 sessionId: expect.any(String),
356 durationSeconds: null,
357 videoWidth: 854,
358 videoHeight: 480,
359 subtitleTracks: [
360 expect.objectContaining({
361 fileName: 'subtitle-0.vtt',
362 language: 'und',
363 isDefault: true,
364 }),
365 ],
366 imageSubtitleTracks: [],
367 subtitleSummary: {
368 total: 1,
369 converted: 1,
370 imageBased: 0,
371 skipped: 0,
372 },
373 });
374 });
375
376 test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>
377 {
378 mockSpawn.mockImplementation((command, args) =>
379 {
380 const child = makeChildProcess();
381 const exeName = path.basename(String(command || '')).toLowerCase();
382
383 if (exeName.includes('ffprobe'))
384 {
385 process.nextTick(() =>
386 {
387 child.stdout.emit('data', Buffer.from(JSON.stringify({
388 streams: [
389 { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} },
390 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
391 { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },
392 ],
393 })));
394 child.emit('close', 0);
395 });
396 return child;
397 }
398
399 const mapIndex = args.indexOf('-map');
400 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
401
402 // Fail subtitle extraction but keep HLS transcoding path successful.
403 if (mappedValue.startsWith('0:s:'))
404 {
405 process.nextTick(() =>
406 {
407 child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));
408 child.emit('close', 1);
409 });
410 return child;
411 }
412
413 const playlistPath = String(args[args.length - 1] || '');
414 const outputDir = path.dirname(playlistPath);
415 process.nextTick(() =>
416 {
417 fs.mkdirSync(outputDir, { recursive: true });
418 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
419 });
420
421 return child;
422 });
423
424 const { createVideoStreamSession } = require('../server/video-stream');
425 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
426 sessionId: expect.any(String),
427 durationSeconds: null,
428 videoWidth: 1920,
429 videoHeight: 1080,
430 subtitleTracks: [],
431 imageSubtitleTracks: [
432 expect.objectContaining({
433 label: 'Subtitle 1 (eng)',
434 language: 'eng',
435 streamIndex: 0,
436 }),
437 ],
438 subtitleSummary: {
439 total: 1,
440 converted: 0,
441 imageBased: 1,
442 skipped: 0,
443 },
444 });
445 });
446
447 test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () =>
448 {
449 mockSpawn.mockImplementation((command, args) =>
450 {
451 const child = makeChildProcess();
452 const exeName = path.basename(String(command || '')).toLowerCase();
453
454 if (exeName.includes('ffprobe'))
455 {
456 process.nextTick(() =>
457 {
458 child.stdout.emit('data', Buffer.from(JSON.stringify({
459 streams: [
460 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
461 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
462 ],
463 })));
464 child.emit('close', 0);
465 });
466 return child;
467 }
468
469 const playlistPath = String(args[args.length - 1] || '');
470 const outputDir = path.dirname(playlistPath);
471 process.nextTick(() =>
472 {
473 fs.mkdirSync(outputDir, { recursive: true });
474 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
475 });
476 return child;
477 });
478
479 const streamModule = require('../server/video-stream');
480 const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles');
481 const beforeDirs = new Set(
482 fs.existsSync(streamModule.STREAM_ROOT_DIR)
483 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
484 : []
485 );
486 const session = await streamModule.createVideoStreamSession(sourceFile);
487 const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
488 const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName));
489 expect(newDirName).toEqual(expect.any(String));
490 const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));
491 expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);
492 const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
493
494 for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)
495 {
496 const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;
497 fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);
498 }
499
500 const { req, res } = makeReqRes();
501 await streamModule.sendVideoStreamAsset(
502 session.sessionId,
503 `stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
504 req,
505 res
506 );
507
508 await new Promise((resolve) => setTimeout(resolve, 80));
509
510 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);
511 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);
512 expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();
513
514 streamModule.releaseVideoStreamSession(session.sessionId);
515 });
516
517 test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>
518 {
519 mockSpawn.mockImplementation((command, args) =>
520 {
521 const child = makeChildProcess();
522 const exeName = path.basename(String(command || '')).toLowerCase();
523
524 if (exeName.includes('ffprobe'))
525 {
526 process.nextTick(() =>
527 {
528 child.stdout.emit('data', Buffer.from(JSON.stringify({
529 streams: [
530 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
531 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
532 ],
533 })));
534 child.emit('close', 0);
535 });
536 return child;
537 }
538
539 const playlistPath = String(args[args.length - 1] || '');
540 const outputDir = path.dirname(playlistPath);
541 process.nextTick(() =>
542 {
543 fs.mkdirSync(outputDir, { recursive: true });
544 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
545 });
546 return child;
547 });
548
549 const streamModule = require('../server/video-stream');
550 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
551 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
552
553 expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId);
554
555 const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) =>
556 path.basename(String(command || '')).toLowerCase().includes('ffmpeg')
557 );
558 expect(ffmpegSpawns).toHaveLength(1);
559
560 const firstReqRes = makeReqRes();
561 await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res);
562
563 const secondReqRes = makeReqRes();
564 await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res);
565
566 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
567
568 const stillActiveReqRes = makeReqRes();
569 await expect(
570 streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res)
571 ).resolves.toBeUndefined();
572
573 const releasedReqRes = makeReqRes();
574 await expect(
575 streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res)
576 ).rejects.toMatchObject({ status: 404 });
577
578 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
579 });
580});