Merge fix/image-subtitle-cross-session-pruning
@@ -130,9 +130,9 @@
130
130
## server/video-stream.js
131
131
- 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.
132
132
- 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.
133
- 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.
133
- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup only clears image subtitle frame/event caches once no other active stream session for the same source file remains.
134
134
- 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.
135
- 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.
135
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() using the slowest active viewer across all live sessions for the same source file, so file-wide subtitle buffers are not pruned ahead of a newly started second session; segment filename regex also uses named-variant pattern to match production filenames correctly.
136
136
- 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.
137
137
- 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.
138
138
- 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.
@@ -130,9 +130,9 @@130
## server/video-stream.js
130
## server/video-stream.js
131
- 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.
131
- 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.
132
- 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.
132
- 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.
133
- 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.
133
- releaseVideoStreamSession(sessionId) - Releases one viewer lease; only destroys the underlying transcode session when no active leases remain; cleanup only clears image subtitle frame/event caches once no other active stream session for the same source file remains.
134
- 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.
134
- 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.
135
- 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.
135
- runSegmentPrune(session) - Removes HLS segment files that fall behind the slowest active viewer and calls pruneImageSubtitleCachesForSession() using the slowest active viewer across all live sessions for the same source file, so file-wide subtitle buffers are not pruned ahead of a newly started second session; segment filename regex also uses named-variant pattern to match production filenames correctly.
136
- 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.
136
- 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.
137
- 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.
137
- 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.
138
- 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.
138
- 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.
@@ -12,6 +12,7 @@ const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;
12
12
const STREAM_READY_TIMEOUT_MS = 20 * 1000;
13
13
const STREAM_IDLE_STOP_MS = 5 * 60 * 1000;
14
14
const ESTIMATED_SEGMENT_BYTES = 1024 * 1024;
15
const ESTIMATED_SEGMENT_DURATION_SECONDS = 6;
15
16
const MAX_STREAM_SEGMENT_RETENTION_COUNT = 360;
16
17
const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT);
17
18
const IMAGE_BASED_SUBTITLE_CODECS = new Set([
@@ -243,8 +244,12 @@ function destroySession (sessionId)
243
244
244
245
fs.rmSync(session.outputDir, { recursive: true, force: true });
245
246
246
// Clear image subtitle caches associated with this file.
247
clearCachesForFile(session.sourcePath);
247
// Only clear file-wide subtitle caches when no other active stream session
248
// for the same source file remains.
249
if (!hasActiveSessionForSourcePath(session.sourcePath))
250
{
251
clearCachesForFile(session.sourcePath);
252
}
248
253
249
254
return true;
250
255
}
@@ -253,14 +258,50 @@ function pruneImageSubtitleCachesForSession (session)
253
258
{
254
259
if (!session || !session.sourcePath) return;
255
260
256
const slowestIndex = slowestLeaseSegmentIndex(session);
257
if (!Number.isInteger(slowestIndex)) return;
258
259
const estimatedSegmentDurationSeconds = 6;
260
const slowestViewerTimeSeconds = slowestIndex * estimatedSegmentDurationSeconds;
261
const slowestViewerTimeSeconds = slowestViewerTimeSecondsForSourcePath(session.sourcePath);
262
if (!Number.isFinite(slowestViewerTimeSeconds)) return;
261
263
pruneOldImageSubtitleCaches(session.sourcePath, slowestViewerTimeSeconds);
262
264
}
263
265
266
function hasActiveSessionForSourcePath (sourcePath)
267
{
268
const wantedPath = String(sourcePath || '');
269
if (!wantedPath) return false;
270
271
for (const session of sessions.values())
272
{
273
if (session && session.sourcePath === wantedPath) return true;
274
}
275
276
return false;
277
}
278
279
function slowestViewerTimeSecondsForSourcePath (sourcePath)
280
{
281
const wantedPath = String(sourcePath || '');
282
if (!wantedPath) return null;
283
284
let slowestIndex = null;
285
let hasActiveViewers = false;
286
287
for (const session of sessions.values())
288
{
289
if (!session || session.sourcePath !== wantedPath) continue;
290
if (!session.leaseIds || session.leaseIds.size === 0) continue;
291
292
hasActiveViewers = true;
293
const sessionSlowestIndex = slowestLeaseSegmentIndex(session);
294
if (!Number.isInteger(sessionSlowestIndex)) return null;
295
if (slowestIndex === null || sessionSlowestIndex < slowestIndex)
296
{
297
slowestIndex = sessionSlowestIndex;
298
}
299
}
300
301
if (!hasActiveViewers || slowestIndex === null) return null;
302
return slowestIndex * ESTIMATED_SEGMENT_DURATION_SECONDS;
303
}
304
264
305
function getSessionForLease (leaseId)
265
306
{
266
307
const lease = leases.get(leaseId);
@@ -12,6 +12,7 @@ const STREAM_SESSION_TTL_MS = 30 * 60 * 1000;12
const STREAM_READY_TIMEOUT_MS = 20 * 1000;12
const STREAM_READY_TIMEOUT_MS = 20 * 1000;13
const STREAM_IDLE_STOP_MS = 5 * 60 * 1000;13
const STREAM_IDLE_STOP_MS = 5 * 60 * 1000;14
const ESTIMATED_SEGMENT_BYTES = 1024 * 1024;14
const ESTIMATED_SEGMENT_BYTES = 1024 * 1024;15
const ESTIMATED_SEGMENT_DURATION_SECONDS = 6;15
const MAX_STREAM_SEGMENT_RETENTION_COUNT = 360;16
const MAX_STREAM_SEGMENT_RETENTION_COUNT = 360;16
const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT);17
const STREAM_SEGMENT_RETENTION_COUNT = parseSegmentRetentionCount(process.env.VIDEO_STREAM_SEGMENT_RETENTION_COUNT);17
const IMAGE_BASED_SUBTITLE_CODECS = new Set([18
const IMAGE_BASED_SUBTITLE_CODECS = new Set([@@ -243,8 +244,12 @@ function destroySession (sessionId)243
244
244
fs.rmSync(session.outputDir, { recursive: true, force: true });245
fs.rmSync(session.outputDir, { recursive: true, force: true });245
246
246
// Clear image subtitle caches associated with this file.247
// Only clear file-wide subtitle caches when no other active stream session247
clearCachesForFile(session.sourcePath);248
// for the same source file remains.249
if (!hasActiveSessionForSourcePath(session.sourcePath))250
{251
clearCachesForFile(session.sourcePath);252
}248
253
249
return true;254
return true;250
}255
}@@ -253,14 +258,50 @@ function pruneImageSubtitleCachesForSession (session)253
{258
{254
if (!session || !session.sourcePath) return;259
if (!session || !session.sourcePath) return;255
260
256
const slowestIndex = slowestLeaseSegmentIndex(session);261
const slowestViewerTimeSeconds = slowestViewerTimeSecondsForSourcePath(session.sourcePath);257
if (!Number.isInteger(slowestIndex)) return;262
if (!Number.isFinite(slowestViewerTimeSeconds)) return;258
259
const estimatedSegmentDurationSeconds = 6;260
const slowestViewerTimeSeconds = slowestIndex * estimatedSegmentDurationSeconds;261
pruneOldImageSubtitleCaches(session.sourcePath, slowestViewerTimeSeconds);263
pruneOldImageSubtitleCaches(session.sourcePath, slowestViewerTimeSeconds);262
}264
}263
265
266
function hasActiveSessionForSourcePath (sourcePath)267
{268
const wantedPath = String(sourcePath || '');269
if (!wantedPath) return false;270
271
for (const session of sessions.values())272
{273
if (session && session.sourcePath === wantedPath) return true;274
}275
276
return false;277
}278
279
function slowestViewerTimeSecondsForSourcePath (sourcePath)280
{281
const wantedPath = String(sourcePath || '');282
if (!wantedPath) return null;283
284
let slowestIndex = null;285
let hasActiveViewers = false;286
287
for (const session of sessions.values())288
{289
if (!session || session.sourcePath !== wantedPath) continue;290
if (!session.leaseIds || session.leaseIds.size === 0) continue;291
292
hasActiveViewers = true;293
const sessionSlowestIndex = slowestLeaseSegmentIndex(session);294
if (!Number.isInteger(sessionSlowestIndex)) return null;295
if (slowestIndex === null || sessionSlowestIndex < slowestIndex)296
{297
slowestIndex = sessionSlowestIndex;298
}299
}300
301
if (!hasActiveViewers || slowestIndex === null) return null;302
return slowestIndex * ESTIMATED_SEGMENT_DURATION_SECONDS;303
}304
264
function getSessionForLease (leaseId)305
function getSessionForLease (leaseId)265
{306
{266
const lease = leases.get(leaseId);307
const lease = leases.get(leaseId);@@ -643,6 +643,102 @@ describe('video stream bootstrap', () =>
643
643
streamModule.releaseVideoStreamSession(secondViewer.sessionId);
644
644
});
645
645
646
test('prunes subtitle caches using the slowest viewer across same-file sessions', async () =>
647
{
648
mockSpawn.mockImplementation((command, args) =>
649
{
650
const child = makeChildProcess();
651
const exeName = path.basename(String(command || '')).toLowerCase();
652
653
if (exeName.includes('ffprobe'))
654
{
655
process.nextTick(() =>
656
{
657
child.stdout.emit('data', Buffer.from(JSON.stringify({
658
streams: [
659
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
660
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
661
],
662
})));
663
child.emit('close', 0);
664
});
665
return child;
666
}
667
668
const playlistPath = String(args[args.length - 1] || '');
669
const outputDir = path.dirname(playlistPath);
670
process.nextTick(() =>
671
{
672
fs.mkdirSync(outputDir, { recursive: true });
673
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
674
});
675
return child;
676
});
677
678
const streamModule = require('../server/video-stream');
679
const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles');
680
const beforeDirs = new Set(
681
fs.existsSync(streamModule.STREAM_ROOT_DIR)
682
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
683
: []
684
);
685
686
const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
687
const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
688
const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));
689
const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));
690
const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
691
692
for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1)
693
{
694
const pad = String(segmentIndex).padStart(6, '0');
695
fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
696
fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
697
}
698
699
let reqRes = makeReqRes();
700
await streamModule.sendVideoStreamAsset(
701
firstViewer.sessionId,
702
`stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,
703
reqRes.req,
704
reqRes.res
705
);
706
707
await new Promise((resolve) => setTimeout(resolve, 80));
708
709
const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
710
const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
711
const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName));
712
const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || ''));
713
714
fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1');
715
716
reqRes = makeReqRes();
717
await streamModule.sendVideoStreamAsset(
718
secondViewer.sessionId,
719
'stream_video_segment_000001.ts',
720
reqRes.req,
721
reqRes.res
722
);
723
724
pruneOldImageSubtitleCaches.mockClear();
725
726
reqRes = makeReqRes();
727
await streamModule.sendVideoStreamAsset(
728
firstViewer.sessionId,
729
`stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`,
730
reqRes.req,
731
reqRes.res
732
);
733
734
await new Promise((resolve) => setTimeout(resolve, 80));
735
736
expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6);
737
738
streamModule.releaseVideoStreamSession(firstViewer.sessionId);
739
streamModule.releaseVideoStreamSession(secondViewer.sessionId);
740
});
741
646
742
test('purges subtitle disk cache when the module is first loaded', () =>
647
743
{
648
744
const { purgeSubtitleCacheDir } = require('../server/image-subtitles');
@@ -714,4 +810,77 @@ describe('video stream bootstrap', () =>
714
810
streamModule.releaseVideoStreamSession(session.sessionId);
715
811
expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);
716
812
});
813
814
test('keeps subtitle caches while another same-file session is still active', async () =>
815
{
816
mockSpawn.mockImplementation((command, args) =>
817
{
818
const child = makeChildProcess();
819
const exeName = path.basename(String(command || '')).toLowerCase();
820
821
if (exeName.includes('ffprobe'))
822
{
823
process.nextTick(() =>
824
{
825
child.stdout.emit('data', Buffer.from(JSON.stringify({
826
streams: [
827
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },
828
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },
829
],
830
})));
831
child.emit('close', 0);
832
});
833
return child;
834
}
835
836
const playlistPath = String(args[args.length - 1] || '');
837
const outputDir = path.dirname(playlistPath);
838
process.nextTick(() =>
839
{
840
fs.mkdirSync(outputDir, { recursive: true });
841
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');
842
});
843
return child;
844
});
845
846
const streamModule = require('../server/video-stream');
847
const { clearCachesForFile } = require('../server/image-subtitles');
848
const beforeDirs = new Set(
849
fs.existsSync(streamModule.STREAM_ROOT_DIR)
850
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)
851
: []
852
);
853
854
const firstViewer = await streamModule.createVideoStreamSession(sourceFile);
855
const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);
856
const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));
857
const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));
858
const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;
859
860
for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1)
861
{
862
const pad = String(segmentIndex).padStart(6, '0');
863
fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);
864
fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);
865
}
866
867
let reqRes = makeReqRes();
868
await streamModule.sendVideoStreamAsset(
869
firstViewer.sessionId,
870
`stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,
871
reqRes.req,
872
reqRes.res
873
);
874
875
await new Promise((resolve) => setTimeout(resolve, 80));
876
877
const secondViewer = await streamModule.createVideoStreamSession(sourceFile);
878
clearCachesForFile.mockClear();
879
880
streamModule.releaseVideoStreamSession(firstViewer.sessionId);
881
expect(clearCachesForFile).not.toHaveBeenCalled();
882
883
streamModule.releaseVideoStreamSession(secondViewer.sessionId);
884
expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);
885
});
717
886
});
@@ -643,6 +643,102 @@ describe('video stream bootstrap', () =>643
streamModule.releaseVideoStreamSession(secondViewer.sessionId);643
streamModule.releaseVideoStreamSession(secondViewer.sessionId);644
});644
});645
645
646
test('prunes subtitle caches using the slowest viewer across same-file sessions', async () =>647
{648
mockSpawn.mockImplementation((command, args) =>649
{650
const child = makeChildProcess();651
const exeName = path.basename(String(command || '')).toLowerCase();652
653
if (exeName.includes('ffprobe'))654
{655
process.nextTick(() =>656
{657
child.stdout.emit('data', Buffer.from(JSON.stringify({658
streams: [659
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },660
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },661
],662
})));663
child.emit('close', 0);664
});665
return child;666
}667
668
const playlistPath = String(args[args.length - 1] || '');669
const outputDir = path.dirname(playlistPath);670
process.nextTick(() =>671
{672
fs.mkdirSync(outputDir, { recursive: true });673
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');674
});675
return child;676
});677
678
const streamModule = require('../server/video-stream');679
const { pruneOldImageSubtitleCaches } = require('../server/image-subtitles');680
const beforeDirs = new Set(681
fs.existsSync(streamModule.STREAM_ROOT_DIR)682
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)683
: []684
);685
686
const firstViewer = await streamModule.createVideoStreamSession(sourceFile);687
const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);688
const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));689
const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));690
const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;691
692
for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex + 1; segmentIndex += 1)693
{694
const pad = String(segmentIndex).padStart(6, '0');695
fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);696
fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);697
}698
699
let reqRes = makeReqRes();700
await streamModule.sendVideoStreamAsset(701
firstViewer.sessionId,702
`stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,703
reqRes.req,704
reqRes.res705
);706
707
await new Promise((resolve) => setTimeout(resolve, 80));708
709
const secondViewer = await streamModule.createVideoStreamSession(sourceFile);710
const afterSecondDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);711
const secondDirName = afterSecondDirs.find((dirName) => !afterFirstDirs.includes(dirName));712
const secondSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(secondDirName || ''));713
714
fs.writeFileSync(path.join(secondSessionDir, 'stream_video_segment_000001.ts'), 'segment-1');715
716
reqRes = makeReqRes();717
await streamModule.sendVideoStreamAsset(718
secondViewer.sessionId,719
'stream_video_segment_000001.ts',720
reqRes.req,721
reqRes.res722
);723
724
pruneOldImageSubtitleCaches.mockClear();725
726
reqRes = makeReqRes();727
await streamModule.sendVideoStreamAsset(728
firstViewer.sessionId,729
`stream_video_segment_${String(firstTargetSegmentIndex + 1).padStart(6, '0')}.ts`,730
reqRes.req,731
reqRes.res732
);733
734
await new Promise((resolve) => setTimeout(resolve, 80));735
736
expect(pruneOldImageSubtitleCaches).toHaveBeenCalledWith(sourceFile, 6);737
738
streamModule.releaseVideoStreamSession(firstViewer.sessionId);739
streamModule.releaseVideoStreamSession(secondViewer.sessionId);740
});741
646
test('purges subtitle disk cache when the module is first loaded', () =>742
test('purges subtitle disk cache when the module is first loaded', () =>647
{743
{648
const { purgeSubtitleCacheDir } = require('../server/image-subtitles');744
const { purgeSubtitleCacheDir } = require('../server/image-subtitles');@@ -714,4 +810,77 @@ describe('video stream bootstrap', () =>714
streamModule.releaseVideoStreamSession(session.sessionId);810
streamModule.releaseVideoStreamSession(session.sessionId);715
expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);811
expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);716
});812
});813
814
test('keeps subtitle caches while another same-file session is still active', async () =>815
{816
mockSpawn.mockImplementation((command, args) =>817
{818
const child = makeChildProcess();819
const exeName = path.basename(String(command || '')).toLowerCase();820
821
if (exeName.includes('ffprobe'))822
{823
process.nextTick(() =>824
{825
child.stdout.emit('data', Buffer.from(JSON.stringify({826
streams: [827
{ codec_type: 'video', codec_name: 'h264', tags: {}, disposition: {} },828
{ codec_type: 'audio', codec_name: 'aac', tags: {}, disposition: { default: 1 } },829
],830
})));831
child.emit('close', 0);832
});833
return child;834
}835
836
const playlistPath = String(args[args.length - 1] || '');837
const outputDir = path.dirname(playlistPath);838
process.nextTick(() =>839
{840
fs.mkdirSync(outputDir, { recursive: true });841
fs.writeFileSync(path.join(outputDir, 'master.m3u8'), '#EXTM3U\n');842
});843
return child;844
});845
846
const streamModule = require('../server/video-stream');847
const { clearCachesForFile } = require('../server/image-subtitles');848
const beforeDirs = new Set(849
fs.existsSync(streamModule.STREAM_ROOT_DIR)850
? fs.readdirSync(streamModule.STREAM_ROOT_DIR)851
: []852
);853
854
const firstViewer = await streamModule.createVideoStreamSession(sourceFile);855
const afterFirstDirs = fs.readdirSync(streamModule.STREAM_ROOT_DIR);856
const firstDirName = afterFirstDirs.find((dirName) => !beforeDirs.has(dirName));857
const firstSessionDir = path.join(streamModule.STREAM_ROOT_DIR, String(firstDirName || ''));858
const firstTargetSegmentIndex = streamModule.STREAM_SEGMENT_RETENTION_COUNT + 40;859
860
for (let segmentIndex = 0; segmentIndex <= firstTargetSegmentIndex; segmentIndex += 1)861
{862
const pad = String(segmentIndex).padStart(6, '0');863
fs.writeFileSync(path.join(firstSessionDir, `stream_video_segment_${pad}.ts`), `segment-${segmentIndex}`);864
fs.writeFileSync(path.join(firstSessionDir, `stream_Audio-1_segment_${pad}.ts`), `audio-${segmentIndex}`);865
}866
867
let reqRes = makeReqRes();868
await streamModule.sendVideoStreamAsset(869
firstViewer.sessionId,870
`stream_video_segment_${String(firstTargetSegmentIndex).padStart(6, '0')}.ts`,871
reqRes.req,872
reqRes.res873
);874
875
await new Promise((resolve) => setTimeout(resolve, 80));876
877
const secondViewer = await streamModule.createVideoStreamSession(sourceFile);878
clearCachesForFile.mockClear();879
880
streamModule.releaseVideoStreamSession(firstViewer.sessionId);881
expect(clearCachesForFile).not.toHaveBeenCalled();882
883
streamModule.releaseVideoStreamSession(secondViewer.sessionId);884
expect(clearCachesForFile).toHaveBeenCalledWith(sourceFile);885
});717
});886
});