BlueGit

timfa filemanager

Files

filemanager / tests / video-stream.test.js

video-stream.test.js

b49a534c History
video-stream.test.js 12.0 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 subtitleSummary: {
117 total: 0,
118 converted: 0,
119 skipped: 0,
120 },
121 });
122 });
123
124 test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () =>
125 {
126 mockSpawn.mockImplementation((command, args) =>
127 {
128 const child = makeChildProcess();
129 const exeName = path.basename(String(command || '')).toLowerCase();
130
131 if (exeName.includes('ffprobe'))
132 {
133 process.nextTick(() =>
134 {
135 child.stdout.emit('data', Buffer.from(JSON.stringify({
136 streams: [
137 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
138 { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } },
139 ],
140 })));
141 child.emit('close', 0);
142 });
143 return child;
144 }
145
146 const segmentArgIndex = args.indexOf('-hls_segment_filename');
147 expect(segmentArgIndex).toBeGreaterThan(-1);
148 expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts');
149 expect(args).not.toContain('-hls_playlist_type');
150
151 const playlistPath = String(args[args.length - 1] || '');
152 const outputDir = path.dirname(playlistPath);
153 process.nextTick(() =>
154 {
155 fs.mkdirSync(outputDir, { recursive: true });
156 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
157 });
158
159 return child;
160 });
161
162 const { createVideoStreamSession } = require('../server/video-stream');
163 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
164 sessionId: expect.any(String),
165 durationSeconds: null,
166 subtitleTracks: [],
167 subtitleSummary: {
168 total: 0,
169 converted: 0,
170 skipped: 0,
171 },
172 });
173 });
174
175 test('createVideoStreamSession reads duration from ffprobe duration tags', async () =>
176 {
177 mockSpawn.mockImplementation((command, args) =>
178 {
179 const child = makeChildProcess();
180 const exeName = path.basename(String(command || '')).toLowerCase();
181
182 if (exeName.includes('ffprobe'))
183 {
184 process.nextTick(() =>
185 {
186 child.stdout.emit('data', Buffer.from(JSON.stringify({
187 streams: [
188 { codec_type: 'video', codec_name: 'h264', tags: { DURATION: '00:22:17.500000000' }, disposition: {} },
189 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
190 ],
191 })));
192 child.emit('close', 0);
193 });
194 return child;
195 }
196
197 const playlistPath = String(args[args.length - 1] || '');
198 const outputDir = path.dirname(playlistPath);
199 process.nextTick(() =>
200 {
201 fs.mkdirSync(outputDir, { recursive: true });
202 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
203 });
204
205 return child;
206 });
207
208 const { createVideoStreamSession } = require('../server/video-stream');
209 await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({
210 durationSeconds: 1337.5,
211 });
212 });
213
214 test('createVideoStreamSession does not become ready from subtitle files alone', async () =>
215 {
216 mockSpawn.mockImplementation((command, args) =>
217 {
218 const child = makeChildProcess();
219 const exeName = path.basename(String(command || '')).toLowerCase();
220
221 if (exeName.includes('ffprobe'))
222 {
223 process.nextTick(() =>
224 {
225 child.stdout.emit('data', Buffer.from(JSON.stringify({
226 streams: [
227 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
228 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
229 { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} },
230 ],
231 })));
232 child.emit('close', 0);
233 });
234 return child;
235 }
236
237 const mapIndex = args.indexOf('-map');
238 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
239
240 if (mappedValue.startsWith('0:s:'))
241 {
242 const subtitleTarget = String(args[args.length - 1] || '');
243 process.nextTick(() =>
244 {
245 fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true });
246 fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n');
247 child.emit('close', 0);
248 });
249 return child;
250 }
251
252 const playlistPath = String(args[args.length - 1] || '');
253 const outputDir = path.dirname(playlistPath);
254 process.nextTick(() =>
255 {
256 fs.mkdirSync(outputDir, { recursive: true });
257 setTimeout(() =>
258 {
259 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
260 }, 80);
261 });
262
263 return child;
264 });
265
266 const { createVideoStreamSession } = require('../server/video-stream');
267 const startedAt = Date.now();
268 const session = await createVideoStreamSession(sourceFile);
269 const elapsedMs = Date.now() - startedAt;
270
271 expect(elapsedMs).toBeGreaterThanOrEqual(60);
272 expect(session).toEqual({
273 sessionId: expect.any(String),
274 durationSeconds: null,
275 subtitleTracks: [
276 expect.objectContaining({
277 fileName: 'subtitle-0.vtt',
278 language: 'eng',
279 }),
280 ],
281 subtitleSummary: {
282 total: 1,
283 converted: 1,
284 skipped: 0,
285 },
286 });
287 });
288
289 test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () =>
290 {
291 mockSpawn.mockImplementation((command, args) =>
292 {
293 const child = makeChildProcess();
294 const exeName = path.basename(String(command || '')).toLowerCase();
295
296 if (exeName.includes('ffprobe'))
297 {
298 process.nextTick(() =>
299 {
300 child.stdout.emit('data', Buffer.from(JSON.stringify({
301 streams: [
302 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
303 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
304 { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} },
305 ],
306 })));
307 child.emit('close', 0);
308 });
309 return child;
310 }
311
312 const mapIndex = args.indexOf('-map');
313 const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : '';
314
315 // Fail subtitle extraction but keep HLS transcoding path successful.
316 if (mappedValue.startsWith('0:s:'))
317 {
318 process.nextTick(() =>
319 {
320 child.stderr.emit('data', Buffer.from('Subtitle codec not supported'));
321 child.emit('close', 1);
322 });
323 return child;
324 }
325
326 const playlistPath = String(args[args.length - 1] || '');
327 const outputDir = path.dirname(playlistPath);
328 process.nextTick(() =>
329 {
330 fs.mkdirSync(outputDir, { recursive: true });
331 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
332 });
333
334 return child;
335 });
336
337 const { createVideoStreamSession } = require('../server/video-stream');
338 await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({
339 sessionId: expect.any(String),
340 durationSeconds: null,
341 subtitleTracks: [],
342 subtitleSummary: {
343 total: 1,
344 converted: 0,
345 skipped: 1,
346 },
347 });
348 });
349
350 test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () =>
351 {
352 mockSpawn.mockImplementation((command, args) =>
353 {
354 const child = makeChildProcess();
355 const exeName = path.basename(String(command || '')).toLowerCase();
356
357 if (exeName.includes('ffprobe'))
358 {
359 process.nextTick(() =>
360 {
361 child.stdout.emit('data', Buffer.from(JSON.stringify({
362 streams: [
363 { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
364 { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
365 ],
366 })));
367 child.emit('close', 0);
368 });
369 return child;
370 }
371
372 const playlistPath = String(args[args.length - 1] || '');
373 const outputDir = path.dirname(playlistPath);
374 process.nextTick(() =>
375 {
376 fs.mkdirSync(outputDir, { recursive: true });
377 fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
378 });
379 return child;
380 });
381
382 const streamModule = require('../server/video-stream');
383 const session = await streamModule.createVideoStreamSession(sourceFile);
384 const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, session.sessionId);
385
386 for (let segmentIndex = 0; segmentIndex <= 220; segmentIndex += 1)
387 {
388 const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;
389 fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);
390 }
391
392 const { req, res } = makeReqRes();
393 await streamModule.sendVideoStreamAsset(session.sessionId, 'stream_0_segment_000220.ts', req, res);
394
395 await new Promise((resolve) => setTimeout(resolve, 80));
396
397 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);
398 expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);
399
400 streamModule.releaseVideoStreamSession(session.sessionId);
401 });
402});