BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

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