BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

b7042cf2 History
video-stream.test.js 15.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
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', width: 1920, height: 1080, 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 videoWidth: 1920,
116 videoHeight: 1080,
117 subtitleTracks: [],
118 imageSubtitleTracks: [],
119 subtitleSummary: {
120 total: 0,
121 converted: 0,
122 imageBased: 0,
123 skipped: 0,
124 },
125 });
126 });
127
128 test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>
129 {
130 mockSpawn.mockImplementation((command, args) =>
131 {
132 const child = makeChildProcess();
133 const exeName = path.basename(String(command || '')).toLowerCase();
134
135 if (exeName.includes('ffprobe'))
136 {
137 process.nextTick(() =>
138 {
139 child.stdout.emit('data', Buffer.from(JSON.stringify({
140 streams: [
141 { codec_type: 'video', codec_name: 'h264', width: 1280, height: 720, tags: {}, disposition: {} },
142 { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },
143 ],
144 })));
145 child.emit('close', 0);
146 });
147 return child;
148 }
149
150 const segmentArgIndex = args.indexOf('-hls_segment_filename');
151 expect(segmentArgIndex).toBeGreaterThan(-1);
152 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
153 expect(args).not.toContain('-hls_playlist_type');
154
155 const playlistPath = String(args[args.length - 1] || '');
156 const outputDir = path.dirname(playlistPath);
157 process.nextTick(() =>
158 {
159 fs.mkdirSync(outputDir, { recursive: true });
160 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
161 });
162
163 return child;
164 });
165
166 const { createVideoStreamSession } = require('../server/video-stream');
167 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
168 sessionId: expect.any(String),
169 durationSeconds: null,
170 videoWidth: 1280,
171 videoHeight: 720,
172 subtitleTracks: [],
173 imageSubtitleTracks: [],
174 subtitleSummary: {
175 total: 0,
176 converted: 0,
177 imageBased: 0,
178 skipped: 0,
179 },
180 });
181 });
182
183 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
184 {
185 mockSpawn.mockImplementation((command, args) =>
186 {
187 const child = makeChildProcess();
188 const exeName = path.basename(String(command || '')).toLowerCase();
189
190 if (exeName.includes('ffprobe'))
191 {
192 process.nextTick(() =>
193 {
194 child.stdout.emit('data', Buffer.from(JSON.stringify({
195 streams: [
196 { codec_type: 'video', codec_name: 'h264', width: 640, height: 360, tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
197 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
198 ],
199 })));
200 child.emit('close', 0);
201 });
202 return child;
203 }
204
205 const playlistPath = String(args[args.length - 1] || '');
206 const outputDir = path.dirname(playlistPath);
207 process.nextTick(() =>
208 {
209 fs.mkdirSync(outputDir, { recursive: true });
210 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
211 });
212
213 return child;
214 });
215
216 const { createVideoStreamSession } = require('../server/video-stream');
217 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
218 durationSeconds: 1337.5,
219 });
220 });
221
222 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
223 {
224 mockSpawn.mockImplementation((command, args) =>
225 {
226 const child = makeChildProcess();
227 const exeName = path.basename(String(command || '')).toLowerCase();
228
229 if (exeName.includes('ffprobe'))
230 {
231 process.nextTick(() =>
232 {
233 child.stdout.emit('data', Buffer.from(JSON.stringify({
234 streams: [
235 { codec_type: 'video', codec_name: 'h264', width: 1024, height: 576, tags: {}, disposition: {} },
236 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
237 { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} },
238 ],
239 })));
240 child.emit('close', 0);
241 });
242 return child;
243 }
244
245 const mapIndex = args.indexOf('-map');
246 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
247
248 if (mappedValue.startsWith('0:s:'))
249 {
250 const subtitleTarget = String(args[args.length - 1] || '');
251 process.nextTick(() =>
252 {
253 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
254 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
255 child.emit('close', 0);
256 });
257 return child;
258 }
259
260 const playlistPath = String(args[args.length - 1] || '');
261 const outputDir = path.dirname(playlistPath);
262 process.nextTick(() =>
263 {
264 fs.mkdirSync(outputDir, { recursive: true });
265 setTimeout(() =>
266 {
267 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
268 }, 80);
269 });
270
271 return child;
272 });
273
274 const { createVideoStreamSession } = require('../server/video-stream');
275 const startedAt = Date.now();
276 const session = await createVideoStreamSession(sourceFile);
277 const elapsedMs = Date.now() - startedAt;
278
279 expect(elapsedMs).toBeGreaterThanOrEqual(60);
280 expect(session).toEqual({
281 sessionId: expect.any(String),
282 durationSeconds: null,
283 videoWidth: 1024,
284 videoHeight: 576,
285 subtitleTracks: [
286 expect.objectContaining({
287 fileName: 'subtitle-0.vtt',
288 language: 'eng',
289 }),
290 ],
291 imageSubtitleTracks: [],
292 subtitleSummary: {
293 total: 1,
294 converted: 1,
295 imageBased: 0,
296 skipped: 0,
297 },
298 });
299 });
300
301 test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>
302 {
303 mockSpawn.mockImplementation((command, args) =>
304 {
305 const child = makeChildProcess();
306 const exeName = path.basename(String(command || '')).toLowerCase();
307
308 if (exeName.includes('ffprobe'))
309 {
310 process.nextTick(() =>
311 {
312 child.stdout.emit('data', Buffer.from(JSON.stringify({
313 streams: [
314 { codec_type: 'video', codec_name: 'h264', width: 1920, height: 1080, tags: {}, disposition: {} },
315 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
316 { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },
317 ],
318 })));
319 child.emit('close', 0);
320 });
321 return child;
322 }
323
324 const mapIndex = args.indexOf('-map');
325 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
326
327 // Fail subtitle extraction but keep HLS transcoding path successful.
328 if (mappedValue.startsWith('0:s:'))
329 {
330 process.nextTick(() =>
331 {
332 child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));
333 child.emit('close', 1);
334 });
335 return child;
336 }
337
338 const playlistPath = String(args[args.length - 1] || '');
339 const outputDir = path.dirname(playlistPath);
340 process.nextTick(() =>
341 {
342 fs.mkdirSync(outputDir, { recursive: true });
343 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
344 });
345
346 return child;
347 });
348
349 const { createVideoStreamSession } = require('../server/video-stream');
350 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
351 sessionId: expect.any(String),
352 durationSeconds: null,
353 videoWidth: 1920,
354 videoHeight: 1080,
355 subtitleTracks: [],
356 imageSubtitleTracks: [
357 expect.objectContaining({
358 label: 'Subtitle 1 (eng)',
359 language: 'eng',
360 streamIndex: 0,
361 }),
362 ],
363 subtitleSummary: {
364 total: 1,
365 converted: 0,
366 imageBased: 1,
367 skipped: 0,
368 },
369 });
370 });
371
372 test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () =>
373 {
374 mockSpawn.mockImplementation((command, args) =>
375 {
376 const child = makeChildProcess();
377 const exeName = path.basename(String(command || '')).toLowerCase();
378
379 if (exeName.includes('ffprobe'))
380 {
381 process.nextTick(() =>
382 {
383 child.stdout.emit('data', Buffer.from(JSON.stringify({
384 streams: [
385 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
386 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
387 ],
388 })));
389 child.emit('close', 0);
390 });
391 return child;
392 }
393
394 const playlistPath = String(args[args.length - 1] || '');
395 const outputDir = path.dirname(playlistPath);
396 process.nextTick(() =>
397 {
398 fs.mkdirSync(outputDir, { recursive: true });
399 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
400 });
401 return child;
402 });
403
404 const streamModule = require('../server/video-stream');
405 const beforeDirs = new Set(
406 fs.existsSync(streamModule.STREAM_ROOT_DIR)
407 ? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
408 : []
409 );
410 const session = await streamModule.createVideoStreamSession(sourceFile);
411 const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
412 const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName));
413 expect(newDirName).toEqual(expect.any(String));
414 const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));
415 expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);
416 const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
417
418 for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)
419 {
420 const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;
421 fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);
422 }
423
424 const { req, res } = makeReqRes();
425 await streamModule.sendVideoStreamAsset(
426 session.sessionId,
427 `stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
428 req,
429 res
430 );
431
432 await new Promise((resolve) => setTimeout(resolve, 80));
433
434 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);
435 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);
436
437 streamModule.releaseVideoStreamSession(session.sessionId);
438 });
439
440 test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>
441 {
442 mockSpawn.mockImplementation((command, args) =>
443 {
444 const child = makeChildProcess();
445 const exeName = path.basename(String(command || '')).toLowerCase();
446
447 if (exeName.includes('ffprobe'))
448 {
449 process.nextTick(() =>
450 {
451 child.stdout.emit('data', Buffer.from(JSON.stringify({
452 streams: [
453 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
454 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
455 ],
456 })));
457 child.emit('close', 0);
458 });
459 return child;
460 }
461
462 const playlistPath = String(args[args.length - 1] || '');
463 const outputDir = path.dirname(playlistPath);
464 process.nextTick(() =>
465 {
466 fs.mkdirSync(outputDir, { recursive: true });
467 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
468 });
469 return child;
470 });
471
472 const streamModule = require('../server/video-stream');
473 const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
474 const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
475
476 expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId);
477
478 const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) =>
479 path.basename(String(command || '')).toLowerCase().includes('ffmpeg')
480 );
481 expect(ffmpegSpawns).toHaveLength(1);
482
483 const firstReqRes = makeReqRes();
484 await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res);
485
486 const secondReqRes = makeReqRes();
487 await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res);
488
489 streamModule.releaseVideoStreamSession(firstViewer.sessionId);
490
491 const stillActiveReqRes = makeReqRes();
492 await expect(
493 streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res)
494 ).resolves.toBeUndefined();
495
496 const releasedReqRes = makeReqRes();
497 await expect(
498 streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res)
499 ).rejects.toMatchObject({ status: 404 });
500
501 streamModule.releaseVideoStreamSession(secondViewer.sessionId);
502 });
503});