'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(), })); jest.mock('../server/image-subtitles', () => ({ clearCachesForFile: jest.fn(), pruneOldImageSubtitleCaches: jest.fn(), purgeSubtitleCacheDir: 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 includes matching sidecar srt subtitles', async () => { fs.writeFileSync(path.join(path.dirname(sourceFile), 'clip.srt'), '1\n00:00:00,000 --> 00:00:01,000\nHello\n'); 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: 854, height: 480, tags: {}, disposition: {} }, { codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } }, ], }))); child.emit('close', 0); }); return child; } const subtitleTarget = String(args[args.length - 1] || ''); if (args.includes('-c:s') && args.includes('webvtt') && subtitleTarget.endsWith('.vtt')) { process.nextTick(() => { fs.mkdirSync(path.dirname(subtitleTarget), { recursive: true }); fs.writeFileSync(subtitleTarget, [ 'WEBVTT', '', '00:00:01.000 --> 00:00:02.000', 'Hello {editor note} world', '', ].join('\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 }); fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n'); }); return child; }); const { createVideoStreamSession, STREAM_ROOT_DIR } = require('../server/video-stream'); const session = await createVideoStreamSession(sourceFile); expect(session).toEqual({ sessionId: expect.any(String), durationSeconds: null, videoWidth: 854, videoHeight: 480, subtitleTracks: [ expect.objectContaining({ fileName: 'subtitle-0.vtt', language: 'und', isDefault: true, }), ], imageSubtitleTracks: [], subtitleSummary: { total: 1, converted: 1, imageBased: 0, skipped: 0, }, }); const vttPath = path.join( STREAM_ROOT_DIR, fs.readdirSync(STREAM_ROOT_DIR)[0], 'subtitle-0.vtt', ); const vttText = fs.readFileSync(vttPath, 'utf8'); expect(vttText).toContain('Hello world'); expect(vttText).not.toContain('{editor note}'); }); 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 { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); 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; // ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries. // With one video + one audio stream the names are 'video' and 'Audio-1'. for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1) { const pad = String(segmentIndex).padStart(6, '0'); fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); } const { req, res } = makeReqRes(); await streamModule.sendVideoStreamAsset( session.sessionId, `stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`, req, res ); await new Promise((resolve) => setTimeout(resolve, 80)); expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false); expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true); expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false); expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true); expect(pruneOldImageSubtitleCaches).toHaveBeenCalled(); const debugSnapshot = streamModule.getVideoStreamDebugSnapshot(); const activeStream = debugSnapshot.activeStreams.find((stream) => stream.sourcePath === sourceFile); expect(debugSnapshot.streamPruneDeleteBatchSize).toBe(16); expect(activeStream).toEqual(expect.objectContaining({ lastSegmentPrune: expect.objectContaining({ cutoff: 40, deletedSegments: expect.any(Number), durationMs: expect.any(Number), completedAt: expect.any(Number), }), })); expect(activeStream.lastSegmentPrune.deletedSegments).toBeGreaterThan(0); streamModule.releaseVideoStreamSession(session.sessionId); }); test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', 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: {} }, ], }))); child.emit('close', 0); }); return child; } const outputDir = path.dirname(String(args[args.length - 1] || '')); 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 newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d)); const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || '')); // Write a small number of named-variant segments (below the retention window). const segmentCount = 10; for (let i = 0; i < segmentCount; i += 1) { fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`); } const { req, res } = makeReqRes(); await streamModule.sendVideoStreamAsset( session.sessionId, `stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`, req, res ); // Segment count is below retention threshold — nothing should be deleted. expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount); 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); }); test('prunes subtitle caches using the slowest viewer across same-file sessions', 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 { pruneOldImageSubtitleCaches } = require('../server/image-subtitles'); const beforeDirs = new Set( fs.existsSync(streamModule.STREAM_ROOT_DIR) ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) : [] ); const firstViewer = await streamModule.createVideoStreamSession(sourceFile); const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1) { const pad = String(segmentIndex).padStart(6, '0'); fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); } let reqRes = makeReqRes(); await streamModule.sendVideoStreamAsset( firstViewer.sessionId, `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, reqRes.req, reqRes.res ); await new Promise((resolve) => setTimeout(resolve, 80)); const secondViewer = await streamModule.createVideoStreamSession(sourceFile); const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName)); const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || '')); fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1'); reqRes = makeReqRes(); await streamModule.sendVideoStreamAsset( secondViewer.sessionId, 'stream_video_segment_000001.ts', reqRes.req, reqRes.res ); pruneOldImageSubtitleCaches.mockClear(); reqRes = makeReqRes(); await streamModule.sendVideoStreamAsset( firstViewer.sessionId, `stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`, reqRes.req, reqRes.res ); await new Promise((resolve) => setTimeout(resolve, 80)); expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6); streamModule.releaseVideoStreamSession(firstViewer.sessionId); streamModule.releaseVideoStreamSession(secondViewer.sessionId); }); test('purges subtitle disk cache when the module is first loaded', () => { const { purgeSubtitleCacheDir } = require('../server/image-subtitles'); require('../server/video-stream'); expect(purgeSubtitleCacheDir).toHaveBeenCalledTimes(1); }); test('purges stream output directory when the module is first loaded', () => { const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); const orphanDir = path.join(streamRoot, 'orphan-after-restart'); fs.mkdirSync(orphanDir, { recursive: true }); fs.writeFileSync(path.join(orphanDir, 'stream_0_segment_000001.ts'), 'segment'); require('../server/video-stream'); expect(fs.existsSync(orphanDir)).toBe(false); }); test('cleanupIdleStreamArtifacts removes stream output directory when no streams are active', () => { const streamRoot = path.join(os.tmpdir(), 'filemanager-video-streams'); const orphanDir = path.join(streamRoot, 'orphan-idle-cleanup'); fs.mkdirSync(orphanDir, { recursive: true }); fs.writeFileSync(path.join(orphanDir, 'stream_0.m3u8'), '#EXTM3U\n'); const streamModule = require('../server/video-stream'); streamModule.cleanupIdleStreamArtifacts(); expect(fs.existsSync(orphanDir)).toBe(false); }); test('clears subtitle caches for a video when its last stream is released', 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: {} }, ], }))); 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 { clearCachesForFile } = require('../server/image-subtitles'); const session = await streamModule.createVideoStreamSession(sourceFile); clearCachesForFile.mockClear(); streamModule.releaseVideoStreamSession(session.sessionId); expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); }); test('keeps subtitle caches while another same-file session is still active', 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 { clearCachesForFile } = require('../server/image-subtitles'); const beforeDirs = new Set( fs.existsSync(streamModule.STREAM_ROOT_DIR) ? fs.readdirSync(streamModule.STREAM_ROOT_DIR) : [] ); const firstViewer = await streamModule.createVideoStreamSession(sourceFile); const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR); const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName)); const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || '')); const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40; for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1) { const pad = String(segmentIndex).padStart(6, '0'); fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`); fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`); } let reqRes = makeReqRes(); await streamModule.sendVideoStreamAsset( firstViewer.sessionId, `stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`, reqRes.req, reqRes.res ); await new Promise((resolve) => setTimeout(resolve, 80)); const secondViewer = await streamModule.createVideoStreamSession(sourceFile); clearCachesForFile.mockClear(); streamModule.releaseVideoStreamSession(firstViewer.sessionId); expect(clearCachesForFile).not.toHaveBeenCalled(); streamModule.releaseVideoStreamSession(secondViewer.sessionId); expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); }); test('destroys zero-viewer sessions immediately even with an in-flight asset response', 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: {} }, ], }))); 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 { clearCachesForFile } = require('../server/image-subtitles'); const session = await streamModule.createVideoStreamSession(sourceFile); clearCachesForFile.mockClear(); const req = new EventEmitter(); const res = new EventEmitter(); let finishSendFile; res.set = () => res; res.type = () => res; res.sendFile = (targetPath, cb) => { finishSendFile = () => { res.emit('finish'); cb(); }; expect(fs.existsSync(targetPath)).toBe(true); }; const assetPromise = streamModule.sendVideoStreamAsset(session.sessionId, 'master.m3u8', req, res); await new Promise((resolve) => setImmediate(resolve)); streamModule.releaseVideoStreamSession(session.sessionId); const debugAfterRelease = streamModule.getVideoStreamDebugSnapshot(); expect(debugAfterRelease.activeSessionCount).toBe(0); expect(debugAfterRelease.activeLeaseCount).toBe(0); expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile); finishSendFile(); await expect(assetPromise).resolves.toBeUndefined(); }); }); describe('text subtitle editor-note sanitization', () => { const { stripSubtitleEditorNotes, sanitizeWebVttContent } = require('../server/video-stream'); test('stripSubtitleEditorNotes removes brace-wrapped notes from cue text', () => { const input = "He grabs the handle{Maybe rephrase, don't make it this short} and jumps"; expect(stripSubtitleEditorNotes(input)).toBe('He grabs the handle and jumps'); }); test('stripSubtitleEditorNotes removes multiple notes in one line', () => { expect(stripSubtitleEditorNotes('Hello {note one} there {note two} friend')) .toBe('Hello there friend'); }); test('sanitizeWebVttContent preserves timestamps and strips cue text notes', () => { const vtt = [ 'WEBVTT', '', '00:00:01.000 --> 00:00:04.000', "He grabs the handle{Maybe rephrase, don't make it this short} and jumps", '', ].join('\n'); const sanitized = sanitizeWebVttContent(vtt); expect(sanitized).toContain('00:00:01.000 --> 00:00:04.000'); expect(sanitized).toContain('He grabs the handle and jumps'); expect(sanitized).not.toContain('{Maybe rephrase'); }); });