'use strict'; const { EventEmitter } = require('events'); const fs = require('fs'); const os = require('os'); const path = require('path'); jest.mock('child_process', () => ({ spawn: jest.fn(), })); function makeChildProcess () { const child = new EventEmitter(); child.stdout = new EventEmitter(); child.stderr = new EventEmitter(); child.kill = jest.fn(); return child; } function makeReqRes () { const req = new EventEmitter(); const res = new EventEmitter(); const headers = {}; res.set = (name, value) => { headers[name] = value; return res; }; res.type = () => res; res.sendFile = (targetPath, cb) => { process.nextTick(() => { if (!fs.existsSync(targetPath)) { const err = new Error('File not found'); err.code = 'ENOENT'; cb(err); return; } res.emit('finish'); cb(); }); }; return { req, res, headers }; } describe('video stream bootstrap', () => { let mockSpawn; let sourceFile; beforeEach(() => { jest.resetModules(); mockSpawn = require('child_process').spawn; mockSpawn.mockReset(); const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'filemanager-video-stream-test-')); sourceFile = path.join(tmpDir, 'clip.mkv'); fs.writeFileSync(sourceFile, 'video'); }); test('createVideoStreamSession resolves once ffmpeg starts writing stream assets', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ format: { duration: '12.5' }, streams: [ { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, ], }))); child.emit('close', 0); }); return child; } expect(exeName.includes('ffmpeg')).toBe(true); const outputPattern = String(args[args.length - 1] || ''); const outputDir = path.dirname(outputPattern); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); setTimeout(() => { fs.writeFileSync(path.join(outputDir, 'stream_0.m3u8'), '#EXTM3U\n'); }, 40); }); return child; }); const { createVideoStreamSession } = require('../server/video-stream'); const session = await createVideoStreamSession(sourceFile); expect(session).toEqual({ sessionId: expect.any(String), durationSeconds: 12.5, subtitleTracks: [], subtitleSummary: { total: 0, converted: 0, skipped: 0, }, }); }); test('createVideoStreamSession configures flat segment filenames that match playlist URLs', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ streams: [ { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: { handler_name: 'SoundHandler' }, disposition: { default: 1 } }, ], }))); child.emit('close', 0); }); return child; } const segmentArgIndex = args.indexOf('-hls_segment_filename'); expect(segmentArgIndex).toBeGreaterThan(-1); expect(String(args[segmentArgIndex + 1])).toContain('stream_%v_segment_%06d.ts'); expect(args).not.toContain('-hls_playlist_type'); const playlistPath = String(args[args.length - 1] || ''); const outputDir = path.dirname(playlistPath); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }); return child; }); const { createVideoStreamSession } = require('../server/video-stream'); await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ sessionId: expect.any(String), durationSeconds: null, subtitleTracks: [], subtitleSummary: { total: 0, converted: 0, skipped: 0, }, }); }); test('createVideoStreamSession reads duration from ffprobe duration tags', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ streams: [ { codec_type: 'video', codec_name: 'h264', tags: { DURATION: '00:22:17.500000000' }, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, ], }))); child.emit('close', 0); }); return child; } const playlistPath = String(args[args.length - 1] || ''); const outputDir = path.dirname(playlistPath); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }); return child; }); const { createVideoStreamSession } = require('../server/video-stream'); await expect(createVideoStreamSession(sourceFile)).resolves.toMatchObject({ durationSeconds: 1337.5, }); }); test('createVideoStreamSession does not become ready from subtitle files alone', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ streams: [ { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, { codec_type: 'subtitle', codec_name: 'subrip', tags: { language: 'eng' }, disposition: {} }, ], }))); child.emit('close', 0); }); return child; } const mapIndex = args.indexOf('-map'); const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; if (mappedValue.startsWith('0:s:')) { const subtitleTarget = String(args[args.length - 1] || ''); process.nextTick(() => { fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true }); fs.writeFileSync(subtitleTarget, 'WEBVTT\n\n'); child.emit('close', 0); }); return child; } const playlistPath = String(args[args.length - 1] || ''); const outputDir = path.dirname(playlistPath); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); setTimeout(() => { fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }, 80); }); return child; }); const { createVideoStreamSession } = require('../server/video-stream'); const startedAt = Date.now(); const session = await createVideoStreamSession(sourceFile); const elapsedMs = Date.now() - startedAt; expect(elapsedMs).toBeGreaterThanOrEqual(60); expect(session).toEqual({ sessionId: expect.any(String), durationSeconds: null, subtitleTracks: [ expect.objectContaining({ fileName: 'subtitle-0.vtt', language: 'eng', }), ], subtitleSummary: { total: 1, converted: 1, skipped: 0, }, }); }); test('createVideoStreamSession keeps playback available when subtitle conversion fails', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ streams: [ { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, { codec_type: 'subtitle', codec_name: 'hdmv_pgs_subtitle', tags: { language: 'eng' }, disposition: {} }, ], }))); child.emit('close', 0); }); return child; } const mapIndex = args.indexOf('-map'); const mappedValue = mapIndex > -1 ? String(args[mapIndex + 1] || '') : ''; // Fail subtitle extraction but keep HLS transcoding path successful. if (mappedValue.startsWith('0:s:')) { process.nextTick(() => { child.stderr.emit('data', Buffer.from('Subtitle codec not supported')); child.emit('close', 1); }); return child; } const playlistPath = String(args[args.length - 1] || ''); const outputDir = path.dirname(playlistPath); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }); return child; }); const { createVideoStreamSession } = require('../server/video-stream'); await expect(createVideoStreamSession(sourceFile)).resolves.toEqual({ sessionId: expect.any(String), durationSeconds: null, subtitleTracks: [], subtitleSummary: { total: 1, converted: 0, skipped: 1, }, }); }); test('sendVideoStreamAsset prunes old segment files after playback moves far ahead', async () => { mockSpawn.mockImplementation((command, args) => { const child = makeChildProcess(); const exeName = path.basename(String(command || '')).toLowerCase(); if (exeName.includes('ffprobe')) { process.nextTick(() => { child.stdout.emit('data', Buffer.from(JSON.stringify({ streams: [ { codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, ], }))); child.emit('close', 0); }); return child; } const playlistPath = String(args[args.length - 1] || ''); const outputDir = path.dirname(playlistPath); process.nextTick(() => { fs.mkdirSync(outputDir, { recursive: true }); fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }); return child; }); const streamModule = require('../server/video-stream'); const session = await streamModule.createVideoStreamSession(sourceFile); const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, session.sessionId); for (let segmentIndex = 0; segmentIndex <= 220; segmentIndex += 1) { const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`; fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`); } const { req, res } = makeReqRes(); await streamModule.sendVideoStreamAsset(session.sessionId, 'stream_0_segment_000220.ts', req, res); await new Promise((resolve) => setTimeout(resolve, 80)); expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false); expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true); streamModule.releaseVideoStreamSession(session.sessionId); }); });