BlueGit

timfa filemanager

er2

timfa Tim Falken · pushed by timfa

Authored 2026-05-26 · 5 months ago

Hash
0a373efcb58154fa14e13fc0bd521fad2c3096fe
Parent
b92cf2b3
3 files changed +109 −6
.github/technical-reference.md +2 −2
@@ -183,8 +183,8 @@
183 183 - applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184 184 - bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185 185 - bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186 - bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress (primary from playlist segment durations, with filename-based segment-index fallback when timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
187 - bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates and removes itself on detach.
186 - bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress (primary from playlist segment durations, with filename-based segment-index fallback for `.ts/.m4s` naming and a media-asset-count fallback when timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
187 - bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates, updates tooltip text with formatted cached-through time, and removes itself on detach.
188 188 - enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
189 189 - clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
190 190
@@ -183,8 +183,8 @@
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
183- applyDefaultTextTrackPrefs() - Writes the default Video.js caption override settings (transparent background, uniform edge style) so all streamed players start from the same text-track baseline.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
184- bindTrackPrefs(player, prefs, savePrefs) - Restores subtitle/audio track selections by track name and persists later track changes; shared by the authenticated player and the share page so both resolve track matches the same way.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
185- bindImageSubtitleOverlay(player, videojs, prefs, session, opts) - Adds the shared IM button/menu/overlay for bitmap subtitle tracks, restores saved image-subtitle selections, fetches rendered frames through a caller-supplied request builder, keeps a separate rolling lookahead-prefetch worker alive across timeupdates (including gaps where no subtitle is currently visible), extends prefetch target to at least the latest buffered video end (not only fixed lookahead seconds), merges buffered-end signals from both Video.js/player APIs and underlying media buffered ranges so under-reported player values do not cap subtitle prefetch early, keeps the prefetch frontier pinned to at least current playback time so it chases buffered-ahead range instead of replaying stale lag after video/session changes, coalesces overlapping current-frame refreshes into a single in-flight fetch (only force-refresh paths abort/restart), applies per-request timeouts (`currentRequestTimeoutMs`, `prefetchRequestTimeoutMs`) so hung subtitle frame requests cannot stall updates indefinitely, paces prefetch polling (`prefetchRequestIntervalMs`) to reduce request bursts, logs current and prefetch subtitle request/send/receive/not-available timing to the browser console and optional batch sink, caches received subtitle PNG frames client-side for the lifetime of the player session (including prefetched frames) so rewind playback can render from local cache even after server-side purge, ensures force-seek aborts still clear in-flight current-request state so subtitle refreshes continue instead of deadlocking, updates seek-bar bracket markers only after responses resolve (no in-flight jump-back flicker), keeps both marker positions forward-only (never regressing to earlier times), allows the two bracket glyphs to overlap naturally when positions match, advances markers even when responses are 204/no-frame, and disables the track after the first hard failure.
186- bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress (primary from playlist segment durations, with filename-based segment-index fallback when timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
186- bindStreamAheadPrefetch(opts) - Starts a background HLS walker that repeatedly fetches the session playlist, discovers variant playlists and media segments, and prefetches those assets into the browser cache so playback can read already-fetched segments while the backend prunes old files; tracks cached-through timeline progress (primary from playlist segment durations, with filename-based segment-index fallback for `.ts/.m4s` naming and a media-asset-count fallback when timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
187- bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates and removes itself on detach.
187- bindStreamAheadSeekMarker(player, streamAheadPrefetch, opts) - Renders a non-interactive `:` marker on the playback seek bar showing how far the stream-ahead walker has cached through the timeline; subscribes to walker progress updates, updates tooltip text with formatted cached-through time, and removes itself on detach.
188- enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
188- enableVideoStreamClientCache() - Registers a shared service worker (`/stream-cache-sw.js`) that caches HLS playlist/segment responses so already-downloaded stream assets remain playable on rewind after server-side segment pruning.
189- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
189- clearVideoStreamClientCache(playlistUrl) - Best-effort cache cleanup helper that removes cached HLS entries for one stream session when preview playback is closed.
190
190
public/shared-video-player.js +49 −4
@@ -20,6 +20,23 @@
20 20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
21 21 const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4;
22 22
23 function formatClockTime (value)
24 {
25 const seconds = Number(value);
26 if (!Number.isFinite(seconds) || seconds < 0) return '00:00';
27
28 const total = Math.floor(seconds);
29 const hours = Math.floor(total / 3600);
30 const minutes = Math.floor((total % 3600) / 60);
31 const remainingSeconds = total % 60;
32
33 if (hours > 0)
34 {
35 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
36 }
37 return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
38 }
39
23 40 function roundLogNumber (value, digits = 3)
24 41 {
25 42 const numeric = Number(value);
@@ -1724,7 +1741,8 @@
1724 1741 // Ignore URL parsing failures and fall back to raw value matching.
1725 1742 }
1726 1743
1727 const match = pathname.match(/_segment_(\d+)\.ts(?:$|\?)/i);
1744 const match = pathname.match(/_segment_(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i)
1745 || pathname.match(/(?:^|[/._-])seg(?:ment)?[_-]?(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i);
1728 1746 if (!match) return null;
1729 1747
1730 1748 const segmentIndex = Number.parseInt(match[1], 10);
@@ -1738,6 +1756,7 @@
1738 1756
1739 1757 const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':';
1740 1758 const markerColor = String(opts.markerColor || '#d6d6d6');
1759 const showTimeTooltip = opts.showTimeTooltip === true;
1741 1760 let markerEl = null;
1742 1761 let markerContainerEl = null;
1743 1762 let cachedThroughSeconds = null;
@@ -1763,6 +1782,13 @@
1763 1782 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1764 1783 markerEl.style.display = 'block';
1765 1784 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1785 if (showTimeTooltip)
1786 {
1787 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1788 } else
1789 {
1790 markerEl.removeAttribute('title');
1791 }
1766 1792 };
1767 1793
1768 1794 const ensureMarker = () =>
@@ -1812,7 +1838,10 @@
1812 1838 markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)';
1813 1839 markerEl.textContent = markerChar;
1814 1840 markerEl.setAttribute('aria-hidden', 'true');
1815 markerEl.title = 'Walker cached through';
1841 if (showTimeTooltip)
1842 {
1843 markerEl.title = 'Walker cached through 00:00';
1844 }
1816 1845
1817 1846 markerContainerEl.appendChild(markerEl);
1818 1847 seekBarEl.appendChild(markerContainerEl);
@@ -1890,6 +1919,7 @@
1890 1919 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1891 1920 let stopped = false;
1892 1921 let cachedThroughSeconds = null;
1922 let fetchedTimelineAssetCount = 0;
1893 1923
1894 1924 const resolveUrl = (value, parentUrl) =>
1895 1925 {
@@ -1935,10 +1965,14 @@
1935 1965 cachedThroughSeconds,
1936 1966 knownPlaylistCount: knownPlaylistUrls.size,
1937 1967 fetchedAssetCount: fetchedAssetUrls.size,
1968 fetchedTimelineAssetCount,
1938 1969 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1939 1970 stopped,
1940 1971 });
1941 1972
1973 const appearsTimelineAsset = (assetUrl) =>
1974 /(?:\.ts|\.m4s|\.mp4|\.aac|\.m4a)(?:$|\?)/i.test(String(assetUrl || ''));
1975
1942 1976 const emitProgress = () =>
1943 1977 {
1944 1978 const status = getStatus();
@@ -2002,8 +2036,19 @@
2002 2036 if (!fetched) continue;
2003 2037
2004 2038 fetchedAssetUrls.add(assetUrl);
2005 const segmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl)
2006 ?? inferSegmentEndSecondsFromAssetUrl(assetUrl);
2039 const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
2040 const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl);
2041 let fallbackSegmentEndSeconds = null;
2042 if (!Number.isFinite(mappedSegmentEndSeconds) && !Number.isFinite(inferredSegmentEndSeconds) && appearsTimelineAsset(assetUrl))
2043 {
2044 fetchedTimelineAssetCount += 1;
2045 fallbackSegmentEndSeconds = fetchedTimelineAssetCount * VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS;
2046 }
2047
2048 const segmentEndSeconds = [mappedSegmentEndSeconds, inferredSegmentEndSeconds, fallbackSegmentEndSeconds]
2049 .filter((value) => Number.isFinite(value))
2050 .reduce((maxValue, value) => (value > maxValue ? value : maxValue), -1);
2051
2007 2052 if (Number.isFinite(segmentEndSeconds))
2008 2053 {
2009 2054 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
@@ -20,6 +20,23 @@
20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
20 const VIDEO_STREAM_AHEAD_PREFETCH_POLL_MS_DEFAULT = 750;
21 const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4;
21 const VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS = 4;
22
22
23 function formatClockTime (value)
24 {
25 const seconds = Number(value);
26 if (!Number.isFinite(seconds) || seconds < 0) return '00:00';
27
28 const total = Math.floor(seconds);
29 const hours = Math.floor(total / 3600);
30 const minutes = Math.floor((total % 3600) / 60);
31 const remainingSeconds = total % 60;
32
33 if (hours > 0)
34 {
35 return `${String(hours).padStart(2, '0')}:${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
36 }
37 return `${String(minutes).padStart(2, '0')}:${String(remainingSeconds).padStart(2, '0')}`;
38 }
39
23 function roundLogNumber (value, digits = 3)
40 function roundLogNumber (value, digits = 3)
24 {
41 {
25 const numeric = Number(value);
42 const numeric = Number(value);
@@ -1724,7 +1741,8 @@
1724 // Ignore URL parsing failures and fall back to raw value matching.
1741 // Ignore URL parsing failures and fall back to raw value matching.
1725 }
1742 }
1726
1743
1727 const match = pathname.match(/_segment_(\d+)\.ts(?:$|\?)/i);
1744 const match = pathname.match(/_segment_(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i)
1745 || pathname.match(/(?:^|[/._-])seg(?:ment)?[_-]?(\d+)(?:\.[a-z0-9]+)?(?:$|\?)/i);
1728 if (!match) return null;
1746 if (!match) return null;
1729
1747
1730 const segmentIndex = Number.parseInt(match[1], 10);
1748 const segmentIndex = Number.parseInt(match[1], 10);
@@ -1738,6 +1756,7 @@
1738
1756
1739 const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':';
1757 const markerChar = String(opts.markerChar || ':').slice(0, 1) || ':';
1740 const markerColor = String(opts.markerColor || '#d6d6d6');
1758 const markerColor = String(opts.markerColor || '#d6d6d6');
1759 const showTimeTooltip = opts.showTimeTooltip === true;
1741 let markerEl = null;
1760 let markerEl = null;
1742 let markerContainerEl = null;
1761 let markerContainerEl = null;
1743 let cachedThroughSeconds = null;
1762 let cachedThroughSeconds = null;
@@ -1763,6 +1782,13 @@
1763 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1782 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1764 markerEl.style.display = 'block';
1783 markerEl.style.display = 'block';
1765 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1784 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1785 if (showTimeTooltip)
1786 {
1787 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1788 } else
1789 {
1790 markerEl.removeAttribute('title');
1791 }
1766 };
1792 };
1767
1793
1768 const ensureMarker = () =>
1794 const ensureMarker = () =>
@@ -1812,7 +1838,10 @@
1812 markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)';
1838 markerEl.style.textShadow = '0 0 2px rgba(0, 0, 0, 0.65)';
1813 markerEl.textContent = markerChar;
1839 markerEl.textContent = markerChar;
1814 markerEl.setAttribute('aria-hidden', 'true');
1840 markerEl.setAttribute('aria-hidden', 'true');
1815 markerEl.title = 'Walker cached through';
1841 if (showTimeTooltip)
1842 {
1843 markerEl.title = 'Walker cached through 00:00';
1844 }
1816
1845
1817 markerContainerEl.appendChild(markerEl);
1846 markerContainerEl.appendChild(markerEl);
1818 seekBarEl.appendChild(markerContainerEl);
1847 seekBarEl.appendChild(markerContainerEl);
@@ -1890,6 +1919,7 @@
1890 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1919 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1891 let stopped = false;
1920 let stopped = false;
1892 let cachedThroughSeconds = null;
1921 let cachedThroughSeconds = null;
1922 let fetchedTimelineAssetCount = 0;
1893
1923
1894 const resolveUrl = (value, parentUrl) =>
1924 const resolveUrl = (value, parentUrl) =>
1895 {
1925 {
@@ -1935,10 +1965,14 @@
1935 cachedThroughSeconds,
1965 cachedThroughSeconds,
1936 knownPlaylistCount: knownPlaylistUrls.size,
1966 knownPlaylistCount: knownPlaylistUrls.size,
1937 fetchedAssetCount: fetchedAssetUrls.size,
1967 fetchedAssetCount: fetchedAssetUrls.size,
1968 fetchedTimelineAssetCount,
1938 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1969 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1939 stopped,
1970 stopped,
1940 });
1971 });
1941
1972
1973 const appearsTimelineAsset = (assetUrl) =>
1974 /(?:\.ts|\.m4s|\.mp4|\.aac|\.m4a)(?:$|\?)/i.test(String(assetUrl || ''));
1975
1942 const emitProgress = () =>
1976 const emitProgress = () =>
1943 {
1977 {
1944 const status = getStatus();
1978 const status = getStatus();
@@ -2002,8 +2036,19 @@
2002 if (!fetched) continue;
2036 if (!fetched) continue;
2003
2037
2004 fetchedAssetUrls.add(assetUrl);
2038 fetchedAssetUrls.add(assetUrl);
2005 const segmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl)
2039 const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
2006 ?? inferSegmentEndSecondsFromAssetUrl(assetUrl);
2040 const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl);
2041 let fallbackSegmentEndSeconds = null;
2042 if (!Number.isFinite(mappedSegmentEndSeconds) && !Number.isFinite(inferredSegmentEndSeconds) && appearsTimelineAsset(assetUrl))
2043 {
2044 fetchedTimelineAssetCount += 1;
2045 fallbackSegmentEndSeconds = fetchedTimelineAssetCount * VIDEO_STREAM_SEGMENT_DURATION_FALLBACK_SECONDS;
2046 }
2047
2048 const segmentEndSeconds = [mappedSegmentEndSeconds, inferredSegmentEndSeconds, fallbackSegmentEndSeconds]
2049 .filter((value) => Number.isFinite(value))
2050 .reduce((maxValue, value) => (value > maxValue ? value : maxValue), -1);
2051
2007 if (Number.isFinite(segmentEndSeconds))
2052 if (Number.isFinite(segmentEndSeconds))
2008 {
2053 {
2009 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
2054 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
tests/shared-video-player.test.js +58 −0
@@ -1222,6 +1222,64 @@ describe('shared image subtitle prefetching', () =>
1222 1222 window.close();
1223 1223 });
1224 1224
1225 test('stream-ahead prefetch infers cached-through progress for m4s segment filenames', async () =>
1226 {
1227 const window = createWindow();
1228 const helper = loadSharedVideoPlayer(window);
1229 const progressSamples = [];
1230
1231 window.fetch = jest.fn(async (input) =>
1232 {
1233 const url = String(input && input.url ? input.url : input);
1234
1235 if (url === 'http://localhost/master.m3u8')
1236 {
1237 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1238 status: 200,
1239 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1240 });
1241 }
1242
1243 if (url === 'http://localhost/stream_0.m3u8')
1244 {
1245 return new Response('#EXTM3U\nstream_0_segment_000000.m4s\nstream_0_segment_000001.m4s\n#EXT-X-ENDLIST\n', {
1246 status: 200,
1247 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1248 });
1249 }
1250
1251 if (url === 'http://localhost/stream_0_segment_000000.m4s' || url === 'http://localhost/stream_0_segment_000001.m4s')
1252 {
1253 return new Response(new Uint8Array([1, 2, 3, 4]), {
1254 status: 200,
1255 headers: { 'Content-Type': 'video/mp4' },
1256 });
1257 }
1258
1259 return new Response(null, { status: 404 });
1260 });
1261
1262 const controller = helper.bindStreamAheadPrefetch({
1263 playlistUrl: 'http://localhost/master.m3u8',
1264 pollIntervalMs: 0,
1265 credentials: 'same-origin',
1266 });
1267
1268 expect(controller).toBeTruthy();
1269 const unsubscribe = controller.subscribe((status) =>
1270 {
1271 progressSamples.push(status && status.cachedThroughSeconds);
1272 });
1273
1274 await controller.done();
1275 unsubscribe();
1276
1277 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1278
1279 controller.stop();
1280 window.close();
1281 });
1282
1225 1283 test('clears cached stream assets for a finished playlist session', async () =>
1226 1284 {
1227 1285 const window = createWindow();
@@ -1222,6 +1222,64 @@ describe('shared image subtitle prefetching', () =>
1222 window.close();
1222 window.close();
1223 });
1223 });
1224
1224
1225 test('stream-ahead prefetch infers cached-through progress for m4s segment filenames', async () =>
1226 {
1227 const window = createWindow();
1228 const helper = loadSharedVideoPlayer(window);
1229 const progressSamples = [];
1230
1231 window.fetch = jest.fn(async (input) =>
1232 {
1233 const url = String(input && input.url ? input.url : input);
1234
1235 if (url === 'http://localhost/master.m3u8')
1236 {
1237 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1238 status: 200,
1239 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1240 });
1241 }
1242
1243 if (url === 'http://localhost/stream_0.m3u8')
1244 {
1245 return new Response('#EXTM3U\nstream_0_segment_000000.m4s\nstream_0_segment_000001.m4s\n#EXT-X-ENDLIST\n', {
1246 status: 200,
1247 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1248 });
1249 }
1250
1251 if (url === 'http://localhost/stream_0_segment_000000.m4s' || url === 'http://localhost/stream_0_segment_000001.m4s')
1252 {
1253 return new Response(new Uint8Array([1, 2, 3, 4]), {
1254 status: 200,
1255 headers: { 'Content-Type': 'video/mp4' },
1256 });
1257 }
1258
1259 return new Response(null, { status: 404 });
1260 });
1261
1262 const controller = helper.bindStreamAheadPrefetch({
1263 playlistUrl: 'http://localhost/master.m3u8',
1264 pollIntervalMs: 0,
1265 credentials: 'same-origin',
1266 });
1267
1268 expect(controller).toBeTruthy();
1269 const unsubscribe = controller.subscribe((status) =>
1270 {
1271 progressSamples.push(status && status.cachedThroughSeconds);
1272 });
1273
1274 await controller.done();
1275 unsubscribe();
1276
1277 expect(progressSamples.some((value) => Number.isFinite(value) && value >= 8)).toBe(true);
1278
1279 controller.stop();
1280 window.close();
1281 });
1282
1225 test('clears cached stream assets for a finished playlist session', async () =>
1283 test('clears cached stream assets for a finished playlist session', async () =>
1226 {
1284 {
1227 const window = createWindow();
1285 const window = createWindow();