'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', width: 1920, height: 1080, 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, videoWidth: 1920, videoHeight: 1080, subtitleTracks: [], imageSubtitleTracks: [], subtitleSummary: { total: 0, converted: 0, imageBased: 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', width: 1280, height: 720, 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, videoWidth: 1280, videoHeight: 720, subtitleTracks: [], imageSubtitleTracks: [], subtitleSummary: { total: 0, converted: 0, imageBased: 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', width: 640, height: 360, 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', width: 1024, height: 576, 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, videoWidth: 1024, videoHeight: 576, subtitleTracks: [ expect.objectContaining({ fileName: 'subtitle-0.vtt', language: 'eng', }), ], imageSubtitleTracks: [], subtitleSummary: { total: 1, converted: 1, imageBased: 0, 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', width: 1920, height: 1080, 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, videoWidth: 1920, videoHeight: 1080, subtitleTracks: [], imageSubtitleTracks: [ expect.objectContaining({ label: 'Subtitle 1 (eng)', language: 'eng', streamIndex: 0, }), ], subtitleSummary: { total: 1, converted: 0, imageBased: 1, skipped: 0, }, }); }); 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 beforeDirs = new Set( fs.existsSync(streamModule.STREAM_ROOT_DIR) ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) : [] ); const session = await streamModule.createVideoStreamSession(sourceFile); const afterDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); const newDirName = afterDirs.find((dirName) => !beforeDirs.has(dirName)); expect(newDirName).toEqual(expect.any(String)); const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true); const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; 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_${String(targetSegmentIndex).padStart(6, '0')}.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); }); test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', 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 firstViewer = await streamModule.createVideoStreamSession(sourceFile); const secondViewer = await streamModule.createVideoStreamSession(sourceFile); expect(firstViewer.sessionId).not.toBe(secondViewer.sessionId); const ffmpegSpawns = mockSpawn.mock.calls.filter(([command]) => path.basename(String(command || '')).toLowerCase().includes('ffmpeg') ); expect(ffmpegSpawns).toHaveLength(1); const firstReqRes = makeReqRes(); await streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', firstReqRes.req, firstReqRes.res); const secondReqRes = makeReqRes(); await streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', secondReqRes.req, secondReqRes.res); streamModule.releaseVideoStreamSession(firstViewer.sessionId); const stillActiveReqRes = makeReqRes(); await expect( streamModule.sendVideoStreamAsset(secondViewer.sessionId, 'master.m3u8', stillActiveReqRes.req, stillActiveReqRes.res) ).resolves.toBeUndefined(); const releasedReqRes = makeReqRes(); await expect( streamModule.sendVideoStreamAsset(firstViewer.sessionId, 'master.m3u8', releasedReqRes.req, releasedReqRes.res) ).rejects.toMatchObject({ status: 404 }); streamModule.releaseVideoStreamSession(secondViewer.sessionId); }); });