Merge fix/segment-prune-named-variants: fix segment pruning for named HLS variants
@@ -129,7 +129,9 @@
129
129
- createVideoStreamSession(sourcePath) - Probes input metadata and reuses a compatible active transcode session per source file when possible; returns a per-viewer lease id as sessionId plus duration, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary data, including same-name sidecar `.srt` subtitles converted to WebVTT.
130
130
- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
131
131
- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
132
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks.
132
- parseSegmentIndexFromAssetPath(assetPath) - Extracts the numeric segment index from an HLS segment filename; matches both numeric variant identifiers (stream_0_segment_000000.ts) and named variants (stream_video_segment_000000.ts, stream_Audio-1-jpn_segment_000000.ts) — ffmpeg substitutes the var_stream_map name: value for %v when named streams are used.
133
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks; segment filename regex also uses named-variant pattern to match production filenames correctly.
134
- hasInitialHlsAssets(outputDir) - Returns true once master.m3u8 or at least one variant playlist/segment exists in an HLS output directory; accepts named variant filenames (stream_video.m3u8) in addition to numeric ones.
133
135
- purgeStreamRootDir() - Best-effort recursive delete of the temporary HLS stream root; used at startup and by idle sweeps to remove orphaned stream session directories from previous runs.
134
136
- cleanupIdleStreamArtifacts() - Periodic idle-time cleaner that purges stream-root artifacts when there are no active sessions or leases, preventing stale segment directories from accumulating after failures.
135
137
- getVideoStreamDebugSnapshot() - Returns active stream sessions with viewer counts and output-dir stats (segment counts/bytes), plus orphaned output directories left under the stream root for diagnostics.
@@ -129,7 +129,9 @@129
- createVideoStreamSession(sourcePath) - Probes input metadata and reuses a compatible active transcode session per source file when possible; returns a per-viewer lease id as sessionId plus duration, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary data, including same-name sidecar `.srt` subtitles converted to WebVTT.
129
- createVideoStreamSession(sourcePath) - Probes input metadata and reuses a compatible active transcode session per source file when possible; returns a per-viewer lease id as sessionId plus duration, videoWidth, videoHeight, subtitleTracks, imageSubtitleTracks, and subtitleSummary data, including same-name sidecar `.srt` subtitles converted to WebVTT.
130
- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
130
- sendVideoStreamAsset(sessionId, assetPath, req, res) - Resolves viewer leases to a shared stream session, serves HLS assets, tracks lease activity, and prunes segments using the slowest active viewer position.
131
- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
131
- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup also clears image subtitle frame/event caches to prevent memory accumulation.
132
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks.
132
- parseSegmentIndexFromAssetPath(assetPath) - Extracts the numeric segment index from an HLS segment filename; matches both numeric variant identifiers (stream_0_segment_000000.ts) and named variants (stream_video_segment_000000.ts, stream_Audio-1-jpn_segment_000000.ts) — ffmpeg substitutes the var_stream_map name: value for %v when named streams are used.
133
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() to drop old subtitle frames once they pass end time + duration + 30 seconds, so subtitle buffers follow the same retention rules as video chunks; segment filename regex also uses named-variant pattern to match production filenames correctly.
134
- hasInitialHlsAssets(outputDir) - Returns true once master.m3u8 or at least one variant playlist/segment exists in an HLS output directory; accepts named variant filenames (stream_video.m3u8) in addition to numeric ones.
133
- purgeStreamRootDir() - Best-effort recursive delete of the temporary HLS stream root; used at startup and by idle sweeps to remove orphaned stream session directories from previous runs.
135
- purgeStreamRootDir() - Best-effort recursive delete of the temporary HLS stream root; used at startup and by idle sweeps to remove orphaned stream session directories from previous runs.
134
- cleanupIdleStreamArtifacts() - Periodic idle-time cleaner that purges stream-root artifacts when there are no active sessions or leases, preventing stale segment directories from accumulating after failures.
136
- cleanupIdleStreamArtifacts() - Periodic idle-time cleaner that purges stream-root artifacts when there are no active sessions or leases, preventing stale segment directories from accumulating after failures.
135
- getVideoStreamDebugSnapshot() - Returns active stream sessions with viewer counts and output-dir stats (segment counts/bytes), plus orphaned output directories left under the stream root for diagnostics.
137
- getVideoStreamDebugSnapshot() - Returns active stream sessions with viewer counts and output-dir stats (segment counts/bytes), plus orphaned output directories left under the stream root for diagnostics.
@@ -5888,7 +5888,7 @@ function renderDebugDashboardData (data)
5888
5888
{ label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },
5889
5889
{ label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },
5890
5890
{ label: 'Retention', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentRetentionCount : 0)) },
5891
{ label: 'Slowest seg', render: (row) => escapeHtml(String(row.stream ? row.stream.slowestViewerSegmentIndex : 0)) },
5891
{ label: 'Slowest seg', render: (row) => { const v = row.stream ? row.stream.slowestViewerSegmentIndex : -1; return escapeHtml(v === -1 ? '\u2014' : String(v)); } },
5892
5892
{ label: 'Pruned until', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentPrunedUntil : 0)) },
5893
5893
{ label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },
5894
5894
],
@@ -5975,7 +5975,7 @@ function copyDebugVideoFilesCsv ()
5975
5975
frameEntries: Number(row.subtitleCache ? row.subtitleCache.frameEntries : 0),
5976
5976
frameBytes: Number(row.subtitleCache ? row.subtitleCache.frameBytes : 0),
5977
5977
segmentRetentionCount: Number(row.stream ? row.stream.segmentRetentionCount : 0),
5978
slowestViewerSegmentIndex: Number(row.stream ? row.stream.slowestViewerSegmentIndex : 0),
5978
slowestViewerSegmentIndex: row.stream ? row.stream.slowestViewerSegmentIndex : -1,
5979
5979
segmentPrunedUntil: Number(row.stream ? row.stream.segmentPrunedUntil : 0),
5980
5980
sessionIds: Array.isArray(row.activeSessionIds) ? row.activeSessionIds.join(';') : '',
5981
5981
}));
@@ -5888,7 +5888,7 @@ function renderDebugDashboardData (data)5888
{ label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },5888
{ label: 'Frame cache', render: (row) => escapeHtml(String(row.subtitleCache ? row.subtitleCache.frameEntries : 0)) },5889
{ label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },5889
{ label: 'Frame bytes', render: (row) => escapeHtml(formatBytes(row.subtitleCache ? row.subtitleCache.frameBytes : 0)) },5890
{ label: 'Retention', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentRetentionCount : 0)) },5890
{ label: 'Retention', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentRetentionCount : 0)) },5891
{ label: 'Slowest seg', render: (row) => escapeHtml(String(row.stream ? row.stream.slowestViewerSegmentIndex : 0)) },5891
{ label: 'Slowest seg', render: (row) => { const v = row.stream ? row.stream.slowestViewerSegmentIndex : -1; return escapeHtml(v === -1 ? '\u2014' : String(v)); } },5892
{ label: 'Pruned until', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentPrunedUntil : 0)) },5892
{ label: 'Pruned until', render: (row) => escapeHtml(String(row.stream ? row.stream.segmentPrunedUntil : 0)) },5893
{ label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },5893
{ label: 'Session ID', render: (row) => escapeHtml((row.activeSessionIds || []).join(', ') || '—') },5894
],5894
],@@ -5975,7 +5975,7 @@ function copyDebugVideoFilesCsv ()5975
frameEntries: Number(row.subtitleCache ? row.subtitleCache.frameEntries : 0),5975
frameEntries: Number(row.subtitleCache ? row.subtitleCache.frameEntries : 0),5976
frameBytes: Number(row.subtitleCache ? row.subtitleCache.frameBytes : 0),5976
frameBytes: Number(row.subtitleCache ? row.subtitleCache.frameBytes : 0),5977
segmentRetentionCount: Number(row.stream ? row.stream.segmentRetentionCount : 0),5977
segmentRetentionCount: Number(row.stream ? row.stream.segmentRetentionCount : 0),5978
slowestViewerSegmentIndex: Number(row.stream ? row.stream.slowestViewerSegmentIndex : 0),5978
slowestViewerSegmentIndex: row.stream ? row.stream.slowestViewerSegmentIndex : -1,5979
segmentPrunedUntil: Number(row.stream ? row.stream.segmentPrunedUntil : 0),5979
segmentPrunedUntil: Number(row.stream ? row.stream.segmentPrunedUntil : 0),5980
sessionIds: Array.isArray(row.activeSessionIds) ? row.activeSessionIds.join(';') : '',5980
sessionIds: Array.isArray(row.activeSessionIds) ? row.activeSessionIds.join(';') : '',5981
}));5981
}));@@ -147,8 +147,8 @@ function hasInitialHlsAssets (outputDir)
147
147
{
148
148
if (!entry.isFile()) return false;
149
149
if (entry.name === 'master.m3u8') return true;
150
if (/^stream_\d+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true;
151
if (/^stream_\d+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true;
150
if (/^stream_.+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true;
151
if (/^stream_.+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true;
152
152
return false;
153
153
});
154
154
} catch
@@ -346,7 +346,7 @@ function finishAssetRequest (session, lease)
346
346
function parseSegmentIndexFromAssetPath (assetPath)
347
347
{
348
348
const baseName = path.basename(String(assetPath || ''));
349
const match = baseName.match(/^stream_\d+_segment_(\d+)\.ts$/i);
349
const match = baseName.match(/^stream_.+_segment_(\d+)\.ts$/i);
350
350
if (!match) return null;
351
351
352
352
const segmentIndex = Number.parseInt(match[1], 10);
@@ -367,7 +367,7 @@ function runSegmentPrune (session)
367
367
const removals = [];
368
368
for (const entryName of entries)
369
369
{
370
const match = String(entryName).match(/^stream_\d+_segment_(\d+)\.ts$/i);
370
const match = String(entryName).match(/^stream_.+_segment_(\d+)\.ts$/i);
371
371
if (!match) continue;
372
372
const segmentIndex = Number.parseInt(match[1], 10);
373
373
if (!Number.isInteger(segmentIndex)) continue;
@@ -1170,7 +1170,7 @@ function getVideoStreamDebugSnapshot ()
1170
1170
segmentRetentionCount: STREAM_SEGMENT_RETENTION_COUNT,
1171
1171
segmentPrunePendingCutoff: Number(session.segmentPrunePendingCutoff || 0),
1172
1172
segmentPrunedUntil: Number(session.segmentPrunedUntil || 0),
1173
slowestViewerSegmentIndex: Number(slowestLeaseSegmentIndex(session) || 0),
1173
slowestViewerSegmentIndex: slowestLeaseSegmentIndex(session) ?? -1,
1174
1174
output: collectOutputDirStats(session.outputDir),
1175
1175
});
1176
1176
}
@@ -147,8 +147,8 @@ function hasInitialHlsAssets (outputDir)147
{147
{148
if (!entry.isFile()) return false;148
if (!entry.isFile()) return false;149
if (entry.name === 'master.m3u8') return true;149
if (entry.name === 'master.m3u8') return true;150
if (/^stream_\d+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true;150
if (/^stream_.+\.m3u8(?:\.tmp)?$/i.test(entry.name)) return true;151
if (/^stream_\d+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true;151
if (/^stream_.+_segment_\d+\.ts(?:\.tmp)?$/i.test(entry.name)) return true;152
return false;152
return false;153
});153
});154
} catch154
} catch@@ -346,7 +346,7 @@ function finishAssetRequest (session, lease)346
function parseSegmentIndexFromAssetPath (assetPath)346
function parseSegmentIndexFromAssetPath (assetPath)347
{347
{348
const baseName = path.basename(String(assetPath || ''));348
const baseName = path.basename(String(assetPath || ''));349
const match = baseName.match(/^stream_\d+_segment_(\d+)\.ts$/i);349
const match = baseName.match(/^stream_.+_segment_(\d+)\.ts$/i);350
if (!match) return null;350
if (!match) return null;351
351
352
const segmentIndex = Number.parseInt(match[1], 10);352
const segmentIndex = Number.parseInt(match[1], 10);@@ -367,7 +367,7 @@ function runSegmentPrune (session)367
const removals = [];367
const removals = [];368
for (const entryName of entries)368
for (const entryName of entries)369
{369
{370
const match = String(entryName).match(/^stream_\d+_segment_(\d+)\.ts$/i);370
const match = String(entryName).match(/^stream_.+_segment_(\d+)\.ts$/i);371
if (!match) continue;371
if (!match) continue;372
const segmentIndex = Number.parseInt(match[1], 10);372
const segmentIndex = Number.parseInt(match[1], 10);373
if (!Number.isInteger(segmentIndex)) continue;373
if (!Number.isInteger(segmentIndex)) continue;@@ -1170,7 +1170,7 @@ function getVideoStreamDebugSnapshot ()1170
segmentRetentionCount: STREAM_SEGMENT_RETENTION_COUNT,1170
segmentRetentionCount: STREAM_SEGMENT_RETENTION_COUNT,1171
segmentPrunePendingCutoff: Number(session.segmentPrunePendingCutoff || 0),1171
segmentPrunePendingCutoff: Number(session.segmentPrunePendingCutoff || 0),1172
segmentPrunedUntil: Number(session.segmentPrunedUntil || 0),1172
segmentPrunedUntil: Number(session.segmentPrunedUntil || 0),1173
slowestViewerSegmentIndex: Number(slowestLeaseSegmentIndex(session) || 0),1173
slowestViewerSegmentIndex: slowestLeaseSegmentIndex(session) ?? -1,1174
output: collectOutputDirStats(session.outputDir),1174
output: collectOutputDirStats(session.outputDir),1175
});1175
});1176
}1176
}@@ -492,29 +492,93 @@ describe('video stream bootstrap', () =>
492
492
expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);
493
493
const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
494
494
495
// ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries.
496
// With one video + one audio stream the names are 'video' and 'Audio-1'.
495
497
for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)
496
498
{
497
const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;
498
fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);
499
const pad = String(segmentIndex).padStart(6, '0');
500
fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
501
fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
499
502
}
500
503
501
504
const { req, res } = makeReqRes();
502
505
await streamModule.sendVideoStreamAsset(
503
506
session.sessionId,
504
`stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
507
`stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,
505
508
req,
506
509
res
507
510
);
508
511
509
512
await new Promise((resolve) => setTimeout(resolve, 80));
510
513
511
expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);
512
expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);
514
expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false);
515
expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true);
516
expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false);
517
expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true);
513
518
expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();
514
519
515
520
streamModule.releaseVideoStreamSession(session.sessionId);
516
521
});
517
522
523
test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () =>
524
{
525
mockSpawn.mockImplementation((command, args) =>
526
{
527
const child = makeChildProcess();
528
const exeName = path.basename(String(command || '')).toLowerCase();
529
if (exeName.includes('ffprobe'))
530
{
531
process.nextTick(() =>
532
{
533
child.stdout.emit('data', Buffer.from(JSON.stringify({
534
streams: [
535
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
536
],
537
})));
538
child.emit('close', 0);
539
});
540
return child;
541
}
542
const outputDir = path.dirname(String(args[args.length - 1] || ''));
543
process.nextTick(() =>
544
{
545
fs.mkdirSync(outputDir, { recursive: true });
546
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
547
});
548
return child;
549
});
550
551
const streamModule = require('../server/video-stream');
552
const beforeDirs = new Set(
553
fs.existsSync(streamModule.STREAM_ROOT_DIR)
554
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
555
: []
556
);
557
const session = await streamModule.createVideoStreamSession(sourceFile);
558
const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d));
559
const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));
560
561
// Write a small number of named-variant segments (below the retention window).
562
const segmentCount = 10;
563
for (let i = 0; i < segmentCount; i += 1)
564
{
565
fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`);
566
}
567
568
const { req, res } = makeReqRes();
569
await streamModule.sendVideoStreamAsset(
570
session.sessionId,
571
`stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`,
572
req,
573
res
574
);
575
576
// Segment count is below retention threshold — nothing should be deleted.
577
expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount);
578
579
streamModule.releaseVideoStreamSession(session.sessionId);
580
});
581
518
582
test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>
519
583
{
520
584
mockSpawn.mockImplementation((command, args) =>
@@ -492,29 +492,93 @@ describe('video stream bootstrap', () =>492
expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);492
expect(Number.isInteger(streamModule.STREAM_SEGMENT_RETENTION_COUNT)).toBe(true);493
const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;493
const targetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;494
494
495
// ffmpeg uses the stream name (not numeric index) when var_stream_map has name: entries.496
// With one video + one audio stream the names are 'video' and 'Audio-1'.495
for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)497
for (let segmentIndex = 0; segmentIndex <= targetSegmentIndex; segmentIndex += 1)496
{498
{497
const fileName = `stream_0_segment_${String(segmentIndex).padStart(6, '0')}.ts`;499
const pad = String(segmentIndex).padStart(6, '0');498
fs.writeFileSync(path.join(sessionDir, fileName), `segment-${segmentIndex}`);500
fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);501
fs.writeFileSync(path.join(sessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);499
}502
}500
503
501
const { req, res } = makeReqRes();504
const { req, res } = makeReqRes();502
await streamModule.sendVideoStreamAsset(505
await streamModule.sendVideoStreamAsset(503
session.sessionId,506
session.sessionId,504
`stream_0_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,507
`stream_video_segment_${String(targetSegmentIndex).padStart(6, '0')}.ts`,505
req,508
req,506
res509
res507
);510
);508
511
509
await new Promise((resolve) => setTimeout(resolve, 80));512
await new Promise((resolve) => setTimeout(resolve, 80));510
513
511
expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000040.ts'))).toBe(false);514
expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000040.ts'))).toBe(false);512
expect(fs.existsSync(path.join(sessionDir, 'stream_0_segment_000041.ts'))).toBe(true);515
expect(fs.existsSync(path.join(sessionDir, 'stream_video_segment_000041.ts'))).toBe(true);516
expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000040.ts'))).toBe(false);517
expect(fs.existsSync(path.join(sessionDir, 'stream_Audio-1_segment_000041.ts'))).toBe(true);513
expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();518
expect(pruneOldImageSubtitleCaches).toHaveBeenCalled();514
519
515
streamModule.releaseVideoStreamSession(session.sessionId);520
streamModule.releaseVideoStreamSession(session.sessionId);516
});521
});517
522
523
test('sendVideoStreamAsset does not prune when named-variant segment index has not advanced past retention window', async () =>524
{525
mockSpawn.mockImplementation((command, args) =>526
{527
const child = makeChildProcess();528
const exeName = path.basename(String(command || '')).toLowerCase();529
if (exeName.includes('ffprobe'))530
{531
process.nextTick(() =>532
{533
child.stdout.emit('data', Buffer.from(JSON.stringify({534
streams: [535
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },536
],537
})));538
child.emit('close', 0);539
});540
return child;541
}542
const outputDir = path.dirname(String(args[args.length - 1] || ''));543
process.nextTick(() =>544
{545
fs.mkdirSync(outputDir, { recursive: true });546
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');547
});548
return child;549
});550
551
const streamModule = require('../server/video-stream');552
const beforeDirs = new Set(553
fs.existsSync(streamModule.STREAM_ROOT_DIR)554
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)555
: []556
);557
const session = await streamModule.createVideoStreamSession(sourceFile);558
const newDirName = fs.readdirSync(streamModule.STREAM_ROOT_DIR).find((d) => !beforeDirs.has(d));559
const sessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(newDirName || ''));560
561
// Write a small number of named-variant segments (below the retention window).562
const segmentCount = 10;563
for (let i = 0; i < segmentCount; i += 1)564
{565
fs.writeFileSync(path.join(sessionDir, `stream_video_segment_${String(i).padStart(6, '0')}.ts`), `seg-${i}`);566
}567
568
const { req, res } = makeReqRes();569
await streamModule.sendVideoStreamAsset(570
session.sessionId,571
`stream_video_segment_${String(segmentCount - 1).padStart(6, '0')}.ts`,572
req,573
res574
);575
576
// Segment count is below retention threshold — nothing should be deleted.577
expect(fs.readdirSync(sessionDir).filter((f) => f.endsWith('.ts')).length).toBe(segmentCount);578
579
streamModule.releaseVideoStreamSession(session.sessionId);580
});581
518
test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>582
test('createVideoStreamSession reuses one transcode for concurrent viewers of the same file', async () =>519
{583
{520
mockSpawn.mockImplementation((command, args) =>584
mockSpawn.mockImplementation((command, args) =>