BlueGit

timfa filemanager

er3

timfa Tim Falken · pushed by timfa

Authored 2026-05-26 · 5 months ago

Hash
bc97da0b5509b516ff425010d1d7badc754b1178
Parent
0a373efc
3 files changed +131 −4
.github/technical-reference.md +1 −1
@@ -183,7 +183,7 @@
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 for `.ts/.m4s` naming and a media-asset-count 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 section-ratio fallback from fetched segments/total discovered segments when absolute timing metadata is missing) and returns a controller with stop()/done()/getStatus()/subscribe().
187 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.
@@ -183,7 +183,7 @@
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 for `.ts/.m4s` naming and a media-asset-count 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 section-ratio fallback from fetched segments/total discovered segments when absolute 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.
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.
public/shared-video-player.js +69 −3
@@ -1665,6 +1665,7 @@
1665 1665 const lines = String(manifestText || '').split(/\r?\n/);
1666 1666 const childPlaylists = [];
1667 1667 const mediaAssets = [];
1668 const mediaSegmentUris = [];
1668 1669 const mediaSegments = [];
1669 1670 let expectPlaylistUri = false;
1670 1671 let segmentCursorSeconds = 0;
@@ -1705,6 +1706,7 @@
1705 1706 } else
1706 1707 {
1707 1708 mediaAssets.push(line);
1709 mediaSegmentUris.push(line);
1708 1710 if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0)
1709 1711 {
1710 1712 const startTimeSeconds = segmentCursorSeconds;
@@ -1722,6 +1724,7 @@
1722 1724 return {
1723 1725 childPlaylists,
1724 1726 mediaAssets,
1727 mediaSegmentUris,
1725 1728 mediaSegments,
1726 1729 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1727 1730 };
@@ -1760,6 +1763,7 @@
1760 1763 let markerEl = null;
1761 1764 let markerContainerEl = null;
1762 1765 let cachedThroughSeconds = null;
1766 let cachedThroughRatio = null;
1763 1767 let detachProgressListener = null;
1764 1768
1765 1769 const currentDuration = () =>
@@ -1779,12 +1783,35 @@
1779 1783 return;
1780 1784 }
1781 1785
1782 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1786 const ratioFromSeconds = Number.isFinite(cachedThroughSeconds)
1787 ? Math.max(0, Math.min(1, cachedThroughSeconds / duration))
1788 : null;
1789 const ratioFromSections = Number.isFinite(cachedThroughRatio)
1790 ? Math.max(0, Math.min(1, cachedThroughRatio))
1791 : null;
1792 const ratio = Number.isFinite(ratioFromSeconds)
1793 ? ratioFromSeconds
1794 : ratioFromSections;
1795 if (!Number.isFinite(ratio))
1796 {
1797 markerEl.style.display = 'none';
1798 return;
1799 }
1800
1783 1801 markerEl.style.display = 'block';
1784 1802 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1785 1803 if (showTimeTooltip)
1786 1804 {
1787 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1805 if (Number.isFinite(cachedThroughSeconds))
1806 {
1807 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1808 } else if (Number.isFinite(cachedThroughRatio))
1809 {
1810 markerEl.title = `Walker cached through ${Math.round(cachedThroughRatio * 100)}%`;
1811 } else
1812 {
1813 markerEl.title = 'Walker cached through';
1814 }
1788 1815 } else
1789 1816 {
1790 1817 markerEl.removeAttribute('title');
@@ -1867,6 +1894,9 @@
1867 1894 ? Number(status.cachedThroughSeconds)
1868 1895 : null;
1869 1896 cachedThroughSeconds = nextCachedThrough;
1897 cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio))
1898 ? Number(status.cachedThroughRatio)
1899 : null;
1870 1900 ensureMarker();
1871 1901 updateMarker();
1872 1902 });
@@ -1876,6 +1906,9 @@
1876 1906 cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds))
1877 1907 ? Number(status.cachedThroughSeconds)
1878 1908 : null;
1909 cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio))
1910 ? Number(status.cachedThroughRatio)
1911 : null;
1879 1912 ensureMarker();
1880 1913 updateMarker();
1881 1914 }
@@ -1915,12 +1948,26 @@
1915 1948 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1916 1949 const fetchedAssetUrls = new Set();
1917 1950 const segmentEndSecondsByAssetUrl = new Map();
1951 const discoveredSegmentUrls = new Set();
1952 const fetchedSegmentUrls = new Set();
1918 1953 const progressListeners = new Set();
1919 1954 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1920 1955 let stopped = false;
1921 1956 let cachedThroughSeconds = null;
1957 let cachedThroughRatio = null;
1922 1958 let fetchedTimelineAssetCount = 0;
1923 1959
1960 const recalculateSegmentRatio = () =>
1961 {
1962 const totalSegments = discoveredSegmentUrls.size;
1963 if (totalSegments <= 0)
1964 {
1965 cachedThroughRatio = null;
1966 return;
1967 }
1968 cachedThroughRatio = Math.max(0, Math.min(1, fetchedSegmentUrls.size / totalSegments));
1969 };
1970
1924 1971 const resolveUrl = (value, parentUrl) =>
1925 1972 {
1926 1973 try
@@ -1963,9 +2010,12 @@
1963 2010
1964 2011 const getStatus = () => ({
1965 2012 cachedThroughSeconds,
2013 cachedThroughRatio,
1966 2014 knownPlaylistCount: knownPlaylistUrls.size,
1967 2015 fetchedAssetCount: fetchedAssetUrls.size,
1968 2016 fetchedTimelineAssetCount,
2017 totalSegmentCount: discoveredSegmentUrls.size,
2018 fetchedSegmentCount: fetchedSegmentUrls.size,
1969 2019 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1970 2020 stopped,
1971 2021 });
@@ -2026,8 +2076,18 @@
2026 2076 if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue;
2027 2077 segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds));
2028 2078 }
2079
2080 for (const segmentUri of parsed.mediaSegmentUris)
2081 {
2082 const resolved = resolveUrl(segmentUri, playlistUrl);
2083 if (!resolved) continue;
2084 discoveredSegmentUrls.add(resolved);
2085 }
2029 2086 }
2030 2087
2088 recalculateSegmentRatio();
2089 emitProgress();
2090
2031 2091 const nextAssetUrls = Array.from(nextAssetUrlSet);
2032 2092 for (const assetUrl of nextAssetUrls)
2033 2093 {
@@ -2036,6 +2096,10 @@
2036 2096 if (!fetched) continue;
2037 2097
2038 2098 fetchedAssetUrls.add(assetUrl);
2099 if (discoveredSegmentUrls.has(assetUrl))
2100 {
2101 fetchedSegmentUrls.add(assetUrl);
2102 }
2039 2103 const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
2040 2104 const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl);
2041 2105 let fallbackSegmentEndSeconds = null;
@@ -2054,9 +2118,11 @@
2054 2118 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
2055 2119 {
2056 2120 cachedThroughSeconds = segmentEndSeconds;
2057 emitProgress();
2058 2121 }
2059 2122 }
2123
2124 recalculateSegmentRatio();
2125 emitProgress();
2060 2126 }
2061 2127
2062 2128 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
@@ -1665,6 +1665,7 @@
1665 const lines = String(manifestText || '').split(/\r?\n/);
1665 const lines = String(manifestText || '').split(/\r?\n/);
1666 const childPlaylists = [];
1666 const childPlaylists = [];
1667 const mediaAssets = [];
1667 const mediaAssets = [];
1668 const mediaSegmentUris = [];
1668 const mediaSegments = [];
1669 const mediaSegments = [];
1669 let expectPlaylistUri = false;
1670 let expectPlaylistUri = false;
1670 let segmentCursorSeconds = 0;
1671 let segmentCursorSeconds = 0;
@@ -1705,6 +1706,7 @@
1705 } else
1706 } else
1706 {
1707 {
1707 mediaAssets.push(line);
1708 mediaAssets.push(line);
1709 mediaSegmentUris.push(line);
1708 if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0)
1710 if (Number.isFinite(pendingSegmentDurationSeconds) && pendingSegmentDurationSeconds > 0)
1709 {
1711 {
1710 const startTimeSeconds = segmentCursorSeconds;
1712 const startTimeSeconds = segmentCursorSeconds;
@@ -1722,6 +1724,7 @@
1722 return {
1724 return {
1723 childPlaylists,
1725 childPlaylists,
1724 mediaAssets,
1726 mediaAssets,
1727 mediaSegmentUris,
1725 mediaSegments,
1728 mediaSegments,
1726 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1729 endList: /#EXT-X-ENDLIST/i.test(String(manifestText || '')),
1727 };
1730 };
@@ -1760,6 +1763,7 @@
1760 let markerEl = null;
1763 let markerEl = null;
1761 let markerContainerEl = null;
1764 let markerContainerEl = null;
1762 let cachedThroughSeconds = null;
1765 let cachedThroughSeconds = null;
1766 let cachedThroughRatio = null;
1763 let detachProgressListener = null;
1767 let detachProgressListener = null;
1764
1768
1765 const currentDuration = () =>
1769 const currentDuration = () =>
@@ -1779,12 +1783,35 @@
1779 return;
1783 return;
1780 }
1784 }
1781
1785
1782 const ratio = Math.max(0, Math.min(1, cachedThroughSeconds / duration));
1786 const ratioFromSeconds = Number.isFinite(cachedThroughSeconds)
1787 ? Math.max(0, Math.min(1, cachedThroughSeconds / duration))
1788 : null;
1789 const ratioFromSections = Number.isFinite(cachedThroughRatio)
1790 ? Math.max(0, Math.min(1, cachedThroughRatio))
1791 : null;
1792 const ratio = Number.isFinite(ratioFromSeconds)
1793 ? ratioFromSeconds
1794 : ratioFromSections;
1795 if (!Number.isFinite(ratio))
1796 {
1797 markerEl.style.display = 'none';
1798 return;
1799 }
1800
1783 markerEl.style.display = 'block';
1801 markerEl.style.display = 'block';
1784 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1802 markerEl.style.left = `${(ratio * 100).toFixed(4)}%`;
1785 if (showTimeTooltip)
1803 if (showTimeTooltip)
1786 {
1804 {
1787 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1805 if (Number.isFinite(cachedThroughSeconds))
1806 {
1807 markerEl.title = `Walker cached through ${formatClockTime(cachedThroughSeconds)}`;
1808 } else if (Number.isFinite(cachedThroughRatio))
1809 {
1810 markerEl.title = `Walker cached through ${Math.round(cachedThroughRatio * 100)}%`;
1811 } else
1812 {
1813 markerEl.title = 'Walker cached through';
1814 }
1788 } else
1815 } else
1789 {
1816 {
1790 markerEl.removeAttribute('title');
1817 markerEl.removeAttribute('title');
@@ -1867,6 +1894,9 @@
1867 ? Number(status.cachedThroughSeconds)
1894 ? Number(status.cachedThroughSeconds)
1868 : null;
1895 : null;
1869 cachedThroughSeconds = nextCachedThrough;
1896 cachedThroughSeconds = nextCachedThrough;
1897 cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio))
1898 ? Number(status.cachedThroughRatio)
1899 : null;
1870 ensureMarker();
1900 ensureMarker();
1871 updateMarker();
1901 updateMarker();
1872 });
1902 });
@@ -1876,6 +1906,9 @@
1876 cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds))
1906 cachedThroughSeconds = status && Number.isFinite(Number(status.cachedThroughSeconds))
1877 ? Number(status.cachedThroughSeconds)
1907 ? Number(status.cachedThroughSeconds)
1878 : null;
1908 : null;
1909 cachedThroughRatio = status && Number.isFinite(Number(status.cachedThroughRatio))
1910 ? Number(status.cachedThroughRatio)
1911 : null;
1879 ensureMarker();
1912 ensureMarker();
1880 updateMarker();
1913 updateMarker();
1881 }
1914 }
@@ -1915,12 +1948,26 @@
1915 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1948 const knownPlaylistUrls = new Set([basePlaylistUrl]);
1916 const fetchedAssetUrls = new Set();
1949 const fetchedAssetUrls = new Set();
1917 const segmentEndSecondsByAssetUrl = new Map();
1950 const segmentEndSecondsByAssetUrl = new Map();
1951 const discoveredSegmentUrls = new Set();
1952 const fetchedSegmentUrls = new Set();
1918 const progressListeners = new Set();
1953 const progressListeners = new Set();
1919 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1954 const controller = typeof AbortController === 'function' ? new AbortController() : null;
1920 let stopped = false;
1955 let stopped = false;
1921 let cachedThroughSeconds = null;
1956 let cachedThroughSeconds = null;
1957 let cachedThroughRatio = null;
1922 let fetchedTimelineAssetCount = 0;
1958 let fetchedTimelineAssetCount = 0;
1923
1959
1960 const recalculateSegmentRatio = () =>
1961 {
1962 const totalSegments = discoveredSegmentUrls.size;
1963 if (totalSegments <= 0)
1964 {
1965 cachedThroughRatio = null;
1966 return;
1967 }
1968 cachedThroughRatio = Math.max(0, Math.min(1, fetchedSegmentUrls.size / totalSegments));
1969 };
1970
1924 const resolveUrl = (value, parentUrl) =>
1971 const resolveUrl = (value, parentUrl) =>
1925 {
1972 {
1926 try
1973 try
@@ -1963,9 +2010,12 @@
1963
2010
1964 const getStatus = () => ({
2011 const getStatus = () => ({
1965 cachedThroughSeconds,
2012 cachedThroughSeconds,
2013 cachedThroughRatio,
1966 knownPlaylistCount: knownPlaylistUrls.size,
2014 knownPlaylistCount: knownPlaylistUrls.size,
1967 fetchedAssetCount: fetchedAssetUrls.size,
2015 fetchedAssetCount: fetchedAssetUrls.size,
1968 fetchedTimelineAssetCount,
2016 fetchedTimelineAssetCount,
2017 totalSegmentCount: discoveredSegmentUrls.size,
2018 fetchedSegmentCount: fetchedSegmentUrls.size,
1969 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
2019 allPlaylistsComplete: Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true),
1970 stopped,
2020 stopped,
1971 });
2021 });
@@ -2026,8 +2076,18 @@
2026 if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue;
2076 if (!Number.isFinite(segment.endTimeSeconds) || segment.endTimeSeconds < 0) continue;
2027 segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds));
2077 segmentEndSecondsByAssetUrl.set(resolved, Number(segment.endTimeSeconds));
2028 }
2078 }
2079
2080 for (const segmentUri of parsed.mediaSegmentUris)
2081 {
2082 const resolved = resolveUrl(segmentUri, playlistUrl);
2083 if (!resolved) continue;
2084 discoveredSegmentUrls.add(resolved);
2085 }
2029 }
2086 }
2030
2087
2088 recalculateSegmentRatio();
2089 emitProgress();
2090
2031 const nextAssetUrls = Array.from(nextAssetUrlSet);
2091 const nextAssetUrls = Array.from(nextAssetUrlSet);
2032 for (const assetUrl of nextAssetUrls)
2092 for (const assetUrl of nextAssetUrls)
2033 {
2093 {
@@ -2036,6 +2096,10 @@
2036 if (!fetched) continue;
2096 if (!fetched) continue;
2037
2097
2038 fetchedAssetUrls.add(assetUrl);
2098 fetchedAssetUrls.add(assetUrl);
2099 if (discoveredSegmentUrls.has(assetUrl))
2100 {
2101 fetchedSegmentUrls.add(assetUrl);
2102 }
2039 const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
2103 const mappedSegmentEndSeconds = segmentEndSecondsByAssetUrl.get(assetUrl);
2040 const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl);
2104 const inferredSegmentEndSeconds = inferSegmentEndSecondsFromAssetUrl(assetUrl);
2041 let fallbackSegmentEndSeconds = null;
2105 let fallbackSegmentEndSeconds = null;
@@ -2054,9 +2118,11 @@
2054 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
2118 if (!Number.isFinite(cachedThroughSeconds) || segmentEndSeconds > cachedThroughSeconds)
2055 {
2119 {
2056 cachedThroughSeconds = segmentEndSeconds;
2120 cachedThroughSeconds = segmentEndSeconds;
2057 emitProgress();
2058 }
2121 }
2059 }
2122 }
2123
2124 recalculateSegmentRatio();
2125 emitProgress();
2060 }
2126 }
2061
2127
2062 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
2128 const allPlaylistsComplete = Array.from(knownPlaylistUrls).every((url) => playlistStatusByUrl.get(url) === true);
tests/shared-video-player.test.js +61 −0
@@ -1280,6 +1280,67 @@ describe('shared image subtitle prefetching', () =>
1280 1280 window.close();
1281 1281 });
1282 1282
1283 test('stream-ahead prefetch reports ratio progress from fetched sections when timing is unknown', async () =>
1284 {
1285 const window = createWindow();
1286 const helper = loadSharedVideoPlayer(window);
1287 const statusSamples = [];
1288
1289 window.fetch = jest.fn(async (input) =>
1290 {
1291 const url = String(input && input.url ? input.url : input);
1292
1293 if (url === 'http://localhost/master.m3u8')
1294 {
1295 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1296 status: 200,
1297 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1298 });
1299 }
1300
1301 if (url === 'http://localhost/stream_0.m3u8')
1302 {
1303 return new Response('#EXTM3U\nchunk-alpha.bin\nchunk-beta.bin\n#EXT-X-ENDLIST\n', {
1304 status: 200,
1305 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1306 });
1307 }
1308
1309 if (url === 'http://localhost/chunk-alpha.bin' || url === 'http://localhost/chunk-beta.bin')
1310 {
1311 return new Response(new Uint8Array([1, 2, 3, 4]), {
1312 status: 200,
1313 headers: { 'Content-Type': 'application/octet-stream' },
1314 });
1315 }
1316
1317 return new Response(null, { status: 404 });
1318 });
1319
1320 const controller = helper.bindStreamAheadPrefetch({
1321 playlistUrl: 'http://localhost/master.m3u8',
1322 pollIntervalMs: 0,
1323 credentials: 'same-origin',
1324 });
1325
1326 expect(controller).toBeTruthy();
1327 const unsubscribe = controller.subscribe((status) =>
1328 {
1329 statusSamples.push(status || {});
1330 });
1331
1332 await controller.done();
1333 unsubscribe();
1334
1335 const finalStatus = statusSamples[statusSamples.length - 1] || {};
1336 expect(finalStatus.totalSegmentCount).toBe(2);
1337 expect(finalStatus.fetchedSegmentCount).toBe(2);
1338 expect(finalStatus.cachedThroughRatio).toBe(1);
1339
1340 controller.stop();
1341 window.close();
1342 });
1343
1283 1344 test('clears cached stream assets for a finished playlist session', async () =>
1284 1345 {
1285 1346 const window = createWindow();
@@ -1280,6 +1280,67 @@ describe('shared image subtitle prefetching', () =>
1280 window.close();
1280 window.close();
1281 });
1281 });
1282
1282
1283 test('stream-ahead prefetch reports ratio progress from fetched sections when timing is unknown', async () =>
1284 {
1285 const window = createWindow();
1286 const helper = loadSharedVideoPlayer(window);
1287 const statusSamples = [];
1288
1289 window.fetch = jest.fn(async (input) =>
1290 {
1291 const url = String(input && input.url ? input.url : input);
1292
1293 if (url === 'http://localhost/master.m3u8')
1294 {
1295 return new Response('#EXTM3U\n#EXT-X-STREAM-INF:BANDWIDTH=100000\nstream_0.m3u8\n#EXT-X-ENDLIST\n', {
1296 status: 200,
1297 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1298 });
1299 }
1300
1301 if (url === 'http://localhost/stream_0.m3u8')
1302 {
1303 return new Response('#EXTM3U\nchunk-alpha.bin\nchunk-beta.bin\n#EXT-X-ENDLIST\n', {
1304 status: 200,
1305 headers: { 'Content-Type': 'application/vnd.apple.mpegurl' },
1306 });
1307 }
1308
1309 if (url === 'http://localhost/chunk-alpha.bin' || url === 'http://localhost/chunk-beta.bin')
1310 {
1311 return new Response(new Uint8Array([1, 2, 3, 4]), {
1312 status: 200,
1313 headers: { 'Content-Type': 'application/octet-stream' },
1314 });
1315 }
1316
1317 return new Response(null, { status: 404 });
1318 });
1319
1320 const controller = helper.bindStreamAheadPrefetch({
1321 playlistUrl: 'http://localhost/master.m3u8',
1322 pollIntervalMs: 0,
1323 credentials: 'same-origin',
1324 });
1325
1326 expect(controller).toBeTruthy();
1327 const unsubscribe = controller.subscribe((status) =>
1328 {
1329 statusSamples.push(status || {});
1330 });
1331
1332 await controller.done();
1333 unsubscribe();
1334
1335 const finalStatus = statusSamples[statusSamples.length - 1] || {};
1336 expect(finalStatus.totalSegmentCount).toBe(2);
1337 expect(finalStatus.fetchedSegmentCount).toBe(2);
1338 expect(finalStatus.cachedThroughRatio).toBe(1);
1339
1340 controller.stop();
1341 window.close();
1342 });
1343
1283 test('clears cached stream assets for a finished playlist session', async () =>
1344 test('clears cached stream assets for a finished playlist session', async () =>
1284 {
1345 {
1285 const window = createWindow();
1346 const window = createWindow();