@videojs/spf 10.0.0-beta.26 → 10.0.0-beta.28
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/default/core/signals/when.js +38 -0
- package/dist/default/core/signals/when.js.map +1 -0
- package/dist/default/core/tasks/delayed-reschedule.js +31 -0
- package/dist/default/core/tasks/delayed-reschedule.js.map +1 -0
- package/dist/default/core/tasks/task.js +133 -3
- package/dist/default/core/tasks/task.js.map +1 -1
- package/dist/default/hls-audio.js +3 -0
- package/dist/default/hls-background-video.js +3 -0
- package/dist/default/hls-video.js +4 -0
- package/dist/default/hls.js +6 -5
- package/dist/default/media/dom/capabilities.js +2 -0
- package/dist/default/media/dom/capabilities.js.map +1 -1
- package/dist/default/media/errors.js +62 -0
- package/dist/default/media/errors.js.map +1 -0
- package/dist/default/media/hls/parse-media-playlist.js +167 -16
- package/dist/default/media/hls/parse-media-playlist.js.map +1 -1
- package/dist/default/media/hls/parse-multivariant.js +14 -3
- package/dist/default/media/hls/parse-multivariant.js.map +1 -1
- package/dist/default/media/hls/reload-policy.js +71 -0
- package/dist/default/media/hls/reload-policy.js.map +1 -0
- package/dist/default/media/live-window.js +36 -0
- package/dist/default/media/live-window.js.map +1 -0
- package/dist/default/media/primitives/select-tracks.js +1 -24
- package/dist/default/media/primitives/select-tracks.js.map +1 -1
- package/dist/default/media/types/index.js +15 -1
- package/dist/default/media/types/index.js.map +1 -1
- package/dist/default/media/utils/tracks.js +14 -0
- package/dist/default/media/utils/tracks.js.map +1 -1
- package/dist/default/mux-audio.js +3 -0
- package/dist/default/mux-background-video.js +3 -0
- package/dist/default/mux-video.js +3 -0
- package/dist/default/playback/adapters/hls-audio/adapter.js +186 -0
- package/dist/default/playback/adapters/hls-audio/adapter.js.map +1 -0
- package/dist/default/playback/adapters/hls-audio/media.js +9 -0
- package/dist/default/playback/adapters/hls-audio/media.js.map +1 -0
- package/dist/default/playback/adapters/hls-background-video/adapter.js +123 -0
- package/dist/default/playback/adapters/hls-background-video/adapter.js.map +1 -0
- package/dist/default/playback/adapters/hls-background-video/host.js +60 -0
- package/dist/default/playback/adapters/hls-background-video/host.js.map +1 -0
- package/dist/default/playback/adapters/hls-background-video/media.js +21 -0
- package/dist/default/playback/adapters/hls-background-video/media.js.map +1 -0
- package/dist/default/playback/adapters/hls-video/adapter.js +316 -0
- package/dist/default/playback/adapters/hls-video/adapter.js.map +1 -0
- package/dist/default/playback/adapters/hls-video/error-surface.js +51 -0
- package/dist/default/playback/adapters/hls-video/error-surface.js.map +1 -0
- package/dist/default/playback/adapters/hls-video/media-tracks.js +126 -0
- package/dist/default/playback/adapters/hls-video/media-tracks.js.map +1 -0
- package/dist/default/playback/adapters/hls-video/media.js +11 -0
- package/dist/default/playback/adapters/hls-video/media.js.map +1 -0
- package/dist/default/playback/adapters/mux-audio/media.js +26 -0
- package/dist/default/playback/adapters/mux-audio/media.js.map +1 -0
- package/dist/default/playback/adapters/mux-video/adapter.js +92 -0
- package/dist/default/playback/adapters/mux-video/adapter.js.map +1 -0
- package/dist/default/playback/adapters/mux-video/media.js +23 -0
- package/dist/default/playback/adapters/mux-video/media.js.map +1 -0
- package/dist/default/playback/behaviors/collect-errors.js +77 -0
- package/dist/default/playback/behaviors/collect-errors.js.map +1 -0
- package/dist/default/playback/behaviors/dom/end-of-stream.js +1 -0
- package/dist/default/playback/behaviors/dom/end-of-stream.js.map +1 -1
- package/dist/default/playback/behaviors/dom/seek-to-live-edge.js +132 -0
- package/dist/default/playback/behaviors/dom/seek-to-live-edge.js.map +1 -0
- package/dist/default/playback/behaviors/dom/sync-live-seekable-range.js +26 -0
- package/dist/default/playback/behaviors/dom/sync-live-seekable-range.js.map +1 -0
- package/dist/default/playback/behaviors/dom/update-mediasource-duration.js +29 -7
- package/dist/default/playback/behaviors/dom/update-mediasource-duration.js.map +1 -1
- package/dist/default/playback/behaviors/establish-start-media-time.js +78 -4
- package/dist/default/playback/behaviors/establish-start-media-time.js.map +1 -1
- package/dist/default/playback/behaviors/resolve-track.js +29 -8
- package/dist/default/playback/behaviors/resolve-track.js.map +1 -1
- package/dist/default/playback/behaviors/track-switching.js +18 -9
- package/dist/default/playback/behaviors/track-switching.js.map +1 -1
- package/dist/default/playback/engines/hls/engine-audio-only.js +9 -5
- package/dist/default/playback/engines/hls/engine-audio-only.js.map +1 -1
- package/dist/{dev/playback/engines/background-video/engine.js → default/playback/engines/hls/engine-background-video.js} +3 -3
- package/dist/default/playback/engines/hls/engine-background-video.js.map +1 -0
- package/dist/default/playback/engines/hls/engine.js +19 -6
- package/dist/default/playback/engines/hls/engine.js.map +1 -1
- package/dist/default/playback/primitives/error-messages.js +39 -0
- package/dist/default/playback/primitives/error-messages.js.map +1 -0
- package/dist/default/playback/primitives/live-window.js +66 -0
- package/dist/default/playback/primitives/live-window.js.map +1 -0
- package/dist/default/playback/primitives/report-track-conditions.js +86 -0
- package/dist/default/playback/primitives/report-track-conditions.js.map +1 -0
- package/dist/dev/core/signals/when.js +38 -0
- package/dist/dev/core/signals/when.js.map +1 -0
- package/dist/dev/core/tasks/delayed-reschedule.js +31 -0
- package/dist/dev/core/tasks/delayed-reschedule.js.map +1 -0
- package/dist/dev/core/tasks/task.d.ts +52 -1
- package/dist/dev/core/tasks/task.d.ts.map +1 -1
- package/dist/dev/core/tasks/task.js +133 -3
- package/dist/dev/core/tasks/task.js.map +1 -1
- package/dist/dev/hls-audio.d.ts +3 -0
- package/dist/dev/hls-audio.js +3 -0
- package/dist/dev/hls-background-video.d.ts +3 -0
- package/dist/dev/hls-background-video.js +3 -0
- package/dist/dev/hls-video.d.ts +5 -0
- package/dist/dev/hls-video.js +4 -0
- package/dist/dev/hls.d.ts +6 -5
- package/dist/dev/hls.js +6 -5
- package/dist/dev/media/dom/capabilities.js +2 -0
- package/dist/dev/media/dom/capabilities.js.map +1 -1
- package/dist/dev/media/errors.d.ts +82 -0
- package/dist/dev/media/errors.d.ts.map +1 -0
- package/dist/dev/media/errors.js +62 -0
- package/dist/dev/media/errors.js.map +1 -0
- package/dist/dev/media/hls/parse-media-playlist.js +167 -16
- package/dist/dev/media/hls/parse-media-playlist.js.map +1 -1
- package/dist/dev/media/hls/parse-multivariant.js +14 -3
- package/dist/dev/media/hls/parse-multivariant.js.map +1 -1
- package/dist/dev/media/hls/reload-policy.js +71 -0
- package/dist/dev/media/hls/reload-policy.js.map +1 -0
- package/dist/dev/media/live-window.js +36 -0
- package/dist/dev/media/live-window.js.map +1 -0
- package/dist/dev/media/primitives/select-tracks.js +1 -24
- package/dist/dev/media/primitives/select-tracks.js.map +1 -1
- package/dist/dev/media/types/index.d.ts +125 -9
- package/dist/dev/media/types/index.d.ts.map +1 -1
- package/dist/dev/media/types/index.js +15 -1
- package/dist/dev/media/types/index.js.map +1 -1
- package/dist/dev/media/utils/tracks.js +14 -0
- package/dist/dev/media/utils/tracks.js.map +1 -1
- package/dist/dev/mux-audio.d.ts +4 -0
- package/dist/dev/mux-audio.js +3 -0
- package/dist/dev/mux-background-video.d.ts +3 -0
- package/dist/dev/mux-background-video.js +3 -0
- package/dist/dev/mux-video.d.ts +4 -0
- package/dist/dev/mux-video.js +3 -0
- package/dist/dev/playback/adapters/hls-audio/adapter.d.ts +54 -0
- package/dist/dev/playback/adapters/hls-audio/adapter.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-audio/adapter.js +186 -0
- package/dist/dev/playback/adapters/hls-audio/adapter.js.map +1 -0
- package/dist/dev/playback/adapters/hls-audio/media.d.ts +10 -0
- package/dist/dev/playback/adapters/hls-audio/media.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-audio/media.js +9 -0
- package/dist/dev/playback/adapters/hls-audio/media.js.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/adapter.d.ts +59 -0
- package/dist/dev/playback/adapters/hls-background-video/adapter.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/adapter.js +123 -0
- package/dist/dev/playback/adapters/hls-background-video/adapter.js.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/host.d.ts +38 -0
- package/dist/dev/playback/adapters/hls-background-video/host.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/host.js +60 -0
- package/dist/dev/playback/adapters/hls-background-video/host.js.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/media.d.ts +20 -0
- package/dist/dev/playback/adapters/hls-background-video/media.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-background-video/media.js +21 -0
- package/dist/dev/playback/adapters/hls-background-video/media.js.map +1 -0
- package/dist/dev/playback/adapters/hls-video/adapter.d.ts +63 -0
- package/dist/dev/playback/adapters/hls-video/adapter.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-video/adapter.js +316 -0
- package/dist/dev/playback/adapters/hls-video/adapter.js.map +1 -0
- package/dist/dev/playback/adapters/hls-video/error-surface.d.ts +18 -0
- package/dist/dev/playback/adapters/hls-video/error-surface.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-video/error-surface.js +51 -0
- package/dist/dev/playback/adapters/hls-video/error-surface.js.map +1 -0
- package/dist/dev/playback/adapters/hls-video/media-tracks.d.ts +22 -0
- package/dist/dev/playback/adapters/hls-video/media-tracks.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-video/media-tracks.js +126 -0
- package/dist/dev/playback/adapters/hls-video/media-tracks.js.map +1 -0
- package/dist/dev/playback/adapters/hls-video/media.d.ts +10 -0
- package/dist/dev/playback/adapters/hls-video/media.d.ts.map +1 -0
- package/dist/dev/playback/adapters/hls-video/media.js +11 -0
- package/dist/dev/playback/adapters/hls-video/media.js.map +1 -0
- package/dist/dev/playback/adapters/mux-audio/media.d.ts +28 -0
- package/dist/dev/playback/adapters/mux-audio/media.d.ts.map +1 -0
- package/dist/dev/playback/adapters/mux-audio/media.js +26 -0
- package/dist/dev/playback/adapters/mux-audio/media.js.map +1 -0
- package/dist/dev/playback/adapters/mux-video/adapter.d.ts +33 -0
- package/dist/dev/playback/adapters/mux-video/adapter.d.ts.map +1 -0
- package/dist/dev/playback/adapters/mux-video/adapter.js +92 -0
- package/dist/dev/playback/adapters/mux-video/adapter.js.map +1 -0
- package/dist/dev/playback/adapters/mux-video/media.d.ts +24 -0
- package/dist/dev/playback/adapters/mux-video/media.d.ts.map +1 -0
- package/dist/dev/playback/adapters/mux-video/media.js +23 -0
- package/dist/dev/playback/adapters/mux-video/media.js.map +1 -0
- package/dist/dev/playback/behaviors/collect-errors.js +77 -0
- package/dist/dev/playback/behaviors/collect-errors.js.map +1 -0
- package/dist/dev/playback/behaviors/dom/end-of-stream.js +1 -0
- package/dist/dev/playback/behaviors/dom/end-of-stream.js.map +1 -1
- package/dist/dev/playback/behaviors/dom/seek-to-live-edge.js +132 -0
- package/dist/dev/playback/behaviors/dom/seek-to-live-edge.js.map +1 -0
- package/dist/dev/playback/behaviors/dom/sync-live-seekable-range.js +26 -0
- package/dist/dev/playback/behaviors/dom/sync-live-seekable-range.js.map +1 -0
- package/dist/dev/playback/behaviors/dom/update-mediasource-duration.js +29 -7
- package/dist/dev/playback/behaviors/dom/update-mediasource-duration.js.map +1 -1
- package/dist/dev/playback/behaviors/establish-start-media-time.d.ts +5 -0
- package/dist/dev/playback/behaviors/establish-start-media-time.d.ts.map +1 -1
- package/dist/dev/playback/behaviors/establish-start-media-time.js +78 -4
- package/dist/dev/playback/behaviors/establish-start-media-time.js.map +1 -1
- package/dist/dev/playback/behaviors/resolve-track.js +29 -8
- package/dist/dev/playback/behaviors/resolve-track.js.map +1 -1
- package/dist/dev/playback/behaviors/track-switching.js +18 -9
- package/dist/dev/playback/behaviors/track-switching.js.map +1 -1
- package/dist/dev/playback/engines/hls/engine-audio-only.d.ts +34 -17
- package/dist/dev/playback/engines/hls/engine-audio-only.d.ts.map +1 -1
- package/dist/dev/playback/engines/hls/engine-audio-only.js +9 -5
- package/dist/dev/playback/engines/hls/engine-audio-only.js.map +1 -1
- package/dist/dev/playback/engines/{background-video/engine.d.ts → hls/engine-background-video.d.ts} +7 -7
- package/dist/dev/playback/engines/hls/engine-background-video.d.ts.map +1 -0
- package/dist/{default/playback/engines/background-video/engine.js → dev/playback/engines/hls/engine-background-video.js} +3 -3
- package/dist/dev/playback/engines/hls/engine-background-video.js.map +1 -0
- package/dist/dev/playback/engines/hls/engine.d.ts +43 -15
- package/dist/dev/playback/engines/hls/engine.d.ts.map +1 -1
- package/dist/dev/playback/engines/hls/engine.js +19 -6
- package/dist/dev/playback/engines/hls/engine.js.map +1 -1
- package/dist/dev/playback/primitives/error-messages.js +39 -0
- package/dist/dev/playback/primitives/error-messages.js.map +1 -0
- package/dist/dev/playback/primitives/live-window.js +66 -0
- package/dist/dev/playback/primitives/live-window.js.map +1 -0
- package/dist/dev/playback/primitives/report-track-conditions.d.ts +11 -0
- package/dist/dev/playback/primitives/report-track-conditions.d.ts.map +1 -0
- package/dist/dev/playback/primitives/report-track-conditions.js +86 -0
- package/dist/dev/playback/primitives/report-track-conditions.js.map +1 -0
- package/package.json +32 -6
- package/dist/default/background-video.js +0 -3
- package/dist/default/playback/engines/background-video/adapter.js +0 -158
- package/dist/default/playback/engines/background-video/adapter.js.map +0 -1
- package/dist/default/playback/engines/background-video/engine.js.map +0 -1
- package/dist/default/playback/engines/hls/adapter-audio-only.js +0 -124
- package/dist/default/playback/engines/hls/adapter-audio-only.js.map +0 -1
- package/dist/default/playback/engines/hls/adapter.js +0 -120
- package/dist/default/playback/engines/hls/adapter.js.map +0 -1
- package/dist/dev/background-video.d.ts +0 -3
- package/dist/dev/background-video.js +0 -3
- package/dist/dev/playback/engines/background-video/adapter.d.ts +0 -59
- package/dist/dev/playback/engines/background-video/adapter.d.ts.map +0 -1
- package/dist/dev/playback/engines/background-video/adapter.js +0 -158
- package/dist/dev/playback/engines/background-video/adapter.js.map +0 -1
- package/dist/dev/playback/engines/background-video/engine.d.ts.map +0 -1
- package/dist/dev/playback/engines/background-video/engine.js.map +0 -1
- package/dist/dev/playback/engines/hls/adapter-audio-only.d.ts +0 -46
- package/dist/dev/playback/engines/hls/adapter-audio-only.d.ts.map +0 -1
- package/dist/dev/playback/engines/hls/adapter-audio-only.js +0 -124
- package/dist/dev/playback/engines/hls/adapter-audio-only.js.map +0 -1
- package/dist/dev/playback/engines/hls/adapter.d.ts +0 -42
- package/dist/dev/playback/engines/hls/adapter.d.ts.map +0 -1
- package/dist/dev/playback/engines/hls/adapter.js +0 -120
- package/dist/dev/playback/engines/hls/adapter.js.map +0 -1
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"engine-background-video.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine-background-video.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport { pickHighestResolutionVideoTrack, type TrackPicker } from '../../../media/primitives/select-tracks';\nimport type { MaybeResolvedPresentation } from '../../../media/types';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport { calculatePresentationDuration } from '../../behaviors/calculate-presentation-duration';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveVideoTrack } from '../../behaviors/resolve-track';\nimport { type SelectVideoTrackConfig, selectVideoTrack } from '../../behaviors/select-tracks';\n\n// ============================================================================\n// Background-video engine state & context\n// ============================================================================\n\n/**\n * State shape for the background-video playback engine.\n *\n * Narrower than `HlsVideoEngineState`: audio/text track slots are absent\n * because their selection/resolution behaviors are subtracted. `bandwidthState`\n * is present because `setupVideoBufferActors` declares it and `loadVideoSegments`\n * samples into it (wasted work in this variant — a Phase 3 alt-impl will skip\n * sampling).\n */\nexport interface BackgroundVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n loadActivated?: boolean;\n}\n\n/**\n * Context shape for the background-video engine.\n */\nexport interface BackgroundVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type BackgroundVideoEngineSignals = {\n state: StateSignals<BackgroundVideoEngineState>;\n context: ContextSignals<BackgroundVideoEngineContext>;\n};\n\n/**\n * Configuration for the background-video engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read. Compared to\n * `HlsVideoEngineConfig`, audio/text/ABR/bandwidth/quality knobs are\n * dropped: the variant subtracts the behaviors that read them.\n */\nexport interface BackgroundVideoEngineConfig\n extends ShareSignalsConfig<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n /**\n * Track picker handed to `selectVideoTrack`. Default:\n * `pickHighestResolutionVideoTrack` — picks the highest-resolution variant on\n * presentation resolve and pins it for the session. Override for\n * mobile-aware or content-aware caps.\n *\n * Adapters (e.g. `HlsBackgroundVideoMediaElement`) install their own\n * picker; this default applies when the engine is constructed directly.\n */\n picker?: TrackPicker<SelectVideoTrackConfig>;\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser.\n */\n parsePresentation?: ParsePresentation;\n}\n\n// ============================================================================\n// Background-video playback engine\n// ============================================================================\n\nconst shareSignals = makeShareSignals<BackgroundVideoEngineState, BackgroundVideoEngineContext>();\n\n/**\n * Create a background-video playback engine.\n *\n * Subtractive composition over the HLS engine baseline:\n * audio-side, text-side, ABR-driven, preload-monitoring, and play/seek\n * load-trigger behaviors are removed. `selectVideoTrack` (with a\n * max-resolution picker by default) replaces `switchVideoQuality`, pinning\n * a single rendition for the session. The initial state seeds\n * `loadActivated: true` so the composition behaves as if preload has\n * already been activated — appropriate for ambient / hero / GIF-replacement\n * surfaces that should start loading the moment a src is set.\n *\n * Native `loop` / `muted` / `autoplay` are adapter concerns and live on\n * `HlsBackgroundVideoMediaElement` rather than the engine.\n *\n * @example\n * ```ts\n * let signals: BackgroundVideoEngineSignals;\n * const engine = createBackgroundVideoEngine({\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * await engine.destroy();\n * ```\n */\nexport function createBackgroundVideoEngine(\n config: BackgroundVideoEngineConfig = {}\n): Composition<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n const finalConfig = {\n ...config,\n picker: config.picker ?? pickHighestResolutionVideoTrack,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n resolveDuration: getResolvedSelectedTrackDuration,\n };\n\n return createComposition(\n [\n resolvePresentation,\n // Presentation duration\n calculatePresentationDuration,\n\n // Track selection - pinned single-rendition pick on presentation resolve.\n selectVideoTrack,\n // Resolve selected video track (fetch its media playlist)\n resolveVideoTrack,\n // Segment loading — video-only.\n loadVideoSegments,\n\n // MSE setup — video-only.\n setupMediaSource,\n updateMediaSourceDuration,\n setupVideoBufferActors,\n\n // Playback tracking\n trackCurrentTime,\n\n // End of stream coordination\n endOfStream,\n\n // Behavior whose sole purpose is to expose signal refs via a callback\n // (e.g. to an adapter). Listed last so initial signal setup has run\n // before the callback fires.\n shareSignals,\n ],\n {\n config: finalConfig,\n initialState: {\n // Note: Set to true until we add preload configuration\n loadActivated: true,\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;AAoGA,MAAM,eAAe,iBAA2E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgChG,SAAgB,4BACd,SAAsC,CAAC,GACgC;CACvE,MAAM,cAAc;EAClB,GAAG;EACH,QAAQ,OAAO,UAAU;EACzB,mBAAmB,OAAO,qBAAqB;EAC/C,iBAAiB;CACnB;CAEA,OAAO,kBACL;EACE;EAEA;EAGA;EAEA;EAEA;EAGA;EACA;EACA;EAGA;EAGA;EAKA;CACF,GACA;EACE,QAAQ;EACR,cAAc,EAEZ,eAAe,KACjB;CACF,CACF;AACF"}
|
|
@@ -5,20 +5,25 @@ import { loadAudioSegments, loadTextTrackSegments, loadVideoSegments } from "../
|
|
|
5
5
|
import { setupTextTrackActors } from "../../behaviors/dom/setup-text-track-actors.js";
|
|
6
6
|
import { trackCurrentTime } from "../../behaviors/dom/track-current-time.js";
|
|
7
7
|
import { trackLoadTriggers } from "../../behaviors/dom/track-load-triggers.js";
|
|
8
|
-
import { deriveSharedMinStartMediaTime, establishStartMediaTime } from "../../behaviors/establish-start-media-time.js";
|
|
8
|
+
import { deriveSharedMinStartMediaTime, establishStartMediaTime, gateFirstParseOnAnchor } from "../../behaviors/establish-start-media-time.js";
|
|
9
|
+
import { delayedReschedule } from "../../../core/tasks/delayed-reschedule.js";
|
|
9
10
|
import { attachMediaSourceAsSourceElement } from "../../../media/dom/mse/mediasource-setup.js";
|
|
10
11
|
import { canPlayTrack } from "../../../media/dom/capabilities.js";
|
|
11
12
|
import { addSubtitlesTracksToMedia, getShowingSubtitlesTrackFromMedia, removeAllSubtitlesTracksFromMedia } from "../../../media/dom/text/text-track-slots.js";
|
|
12
13
|
import { parseMultivariantPlaylist } from "../../../media/hls/parse-multivariant.js";
|
|
14
|
+
import { mediaPlaylistReloadDelay, resolveLiveLatency } from "../../../media/hls/reload-policy.js";
|
|
13
15
|
import { getResolvedSelectedTrackDuration } from "../../../media/utils/track-selection.js";
|
|
14
16
|
import { calculatePresentationDuration } from "../../behaviors/calculate-presentation-duration.js";
|
|
17
|
+
import { collectErrors } from "../../behaviors/collect-errors.js";
|
|
15
18
|
import { deriveCdnPriority } from "../../behaviors/derive-cdn-priority.js";
|
|
16
19
|
import { setupAirPlay } from "../../behaviors/dom/airplay.js";
|
|
17
20
|
import { applyStartPosition } from "../../behaviors/dom/apply-start-position.js";
|
|
18
21
|
import { endOfStream } from "../../behaviors/dom/end-of-stream.js";
|
|
19
22
|
import { recoverEndStall } from "../../behaviors/dom/recover-end-stall.js";
|
|
23
|
+
import { seekToLiveEdge } from "../../behaviors/dom/seek-to-live-edge.js";
|
|
20
24
|
import { setupAudioBufferActors, setupVideoBufferActors } from "../../behaviors/dom/setup-buffer-actors.js";
|
|
21
25
|
import { setupMediaSource } from "../../behaviors/dom/setup-mediasource.js";
|
|
26
|
+
import { syncLiveSeekableRange } from "../../behaviors/dom/sync-live-seekable-range.js";
|
|
22
27
|
import { syncTextTracks } from "../../behaviors/dom/sync-text-tracks.js";
|
|
23
28
|
import { updateMediaSourceDuration } from "../../behaviors/dom/update-mediasource-duration.js";
|
|
24
29
|
import { resolvePresentation } from "../../behaviors/resolve-presentation.js";
|
|
@@ -27,6 +32,7 @@ import { setupFailoverMonitor } from "../../behaviors/setup-failover-monitor.js"
|
|
|
27
32
|
import { syncPreload } from "../../behaviors/sync-preload.js";
|
|
28
33
|
import { switchAudioTrack, switchTextTrack, switchVideoTrack } from "../../behaviors/track-switching.js";
|
|
29
34
|
import { relocatingTextPipelines, relocationPipelinesFor } from "../../primitives/relocation-pipelines.js";
|
|
35
|
+
import { reportUnsupportedTrackConditions } from "../../primitives/report-track-conditions.js";
|
|
30
36
|
//#region src/playback/engines/hls/engine.ts
|
|
31
37
|
/**
|
|
32
38
|
* Generic `shareSignals` instantiated against the HLS engine's full state
|
|
@@ -52,8 +58,8 @@ const shareSignals = makeShareSignals([
|
|
|
52
58
|
*
|
|
53
59
|
* @example
|
|
54
60
|
* ```ts
|
|
55
|
-
* let signals:
|
|
56
|
-
* const engine =
|
|
61
|
+
* let signals: HlsVideoEngineSignals;
|
|
62
|
+
* const engine = createHlsVideoEngine({
|
|
57
63
|
* initialBandwidth: 2_000_000,
|
|
58
64
|
* preferredAudioLanguage: 'en',
|
|
59
65
|
* onSignalsReady: (refs) => {
|
|
@@ -69,13 +75,14 @@ const shareSignals = makeShareSignals([
|
|
|
69
75
|
* await engine.destroy();
|
|
70
76
|
* ```
|
|
71
77
|
*/
|
|
72
|
-
function
|
|
78
|
+
function createHlsVideoEngine(config = {}) {
|
|
73
79
|
const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;
|
|
74
80
|
const finalConfig = {
|
|
75
81
|
...config,
|
|
76
82
|
deriveStartMediaTime,
|
|
77
83
|
attachMediaSource: attachMediaSourceAsSourceElement,
|
|
78
84
|
canPlayTrack: config.canPlayTrack ?? canPlayTrack,
|
|
85
|
+
reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,
|
|
79
86
|
resolveTextTrackSegment: config.resolveTextTrackSegment ?? resolveVttSegment,
|
|
80
87
|
textMessagePipelines: relocatingTextPipelines,
|
|
81
88
|
resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,
|
|
@@ -84,7 +91,10 @@ function createSimpleHlsEngine(config = {}) {
|
|
|
84
91
|
getShowingSubtitlesTrackFromMedia: config.getShowingSubtitlesTrackFromMedia ?? getShowingSubtitlesTrackFromMedia,
|
|
85
92
|
removeAllSubtitlesTracksFromMedia: config.removeAllSubtitlesTracksFromMedia ?? removeAllSubtitlesTracksFromMedia,
|
|
86
93
|
videoMessagePipelines: relocationPipelinesFor("video", deriveStartMediaTime),
|
|
87
|
-
audioMessagePipelines: relocationPipelinesFor("audio", deriveStartMediaTime)
|
|
94
|
+
audioMessagePipelines: relocationPipelinesFor("audio", deriveStartMediaTime),
|
|
95
|
+
gateFirstParse: gateFirstParseOnAnchor,
|
|
96
|
+
resolveLiveLatency,
|
|
97
|
+
reschedule: config.reschedule ?? delayedReschedule(mediaPlaylistReloadDelay)
|
|
88
98
|
};
|
|
89
99
|
return createComposition([
|
|
90
100
|
syncPreload,
|
|
@@ -92,6 +102,7 @@ function createSimpleHlsEngine(config = {}) {
|
|
|
92
102
|
resolvePresentation,
|
|
93
103
|
deriveCdnPriority,
|
|
94
104
|
setupFailoverMonitor,
|
|
105
|
+
collectErrors,
|
|
95
106
|
resolveVideoTrack,
|
|
96
107
|
resolveAudioTrack,
|
|
97
108
|
resolveTextTrack,
|
|
@@ -109,6 +120,8 @@ function createSimpleHlsEngine(config = {}) {
|
|
|
109
120
|
switchTextTrack,
|
|
110
121
|
loadVideoSegments,
|
|
111
122
|
loadAudioSegments,
|
|
123
|
+
syncLiveSeekableRange,
|
|
124
|
+
seekToLiveEdge,
|
|
112
125
|
endOfStream,
|
|
113
126
|
recoverEndStall,
|
|
114
127
|
syncTextTracks,
|
|
@@ -127,6 +140,6 @@ function createSimpleHlsEngine(config = {}) {
|
|
|
127
140
|
});
|
|
128
141
|
}
|
|
129
142
|
//#endregion
|
|
130
|
-
export {
|
|
143
|
+
export { createHlsVideoEngine };
|
|
131
144
|
|
|
132
145
|
//# sourceMappingURL=engine.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport type { QualityConfig } from '../../../media/abr/quality-selection';\nimport type { BackBufferConfig } from '../../../media/buffer/back-buffer';\nimport type { ForwardBufferConfig } from '../../../media/buffer/forward-buffer';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport { attachMediaSourceAsSourceElement } from '../../../media/dom/mse/mediasource-setup';\nimport { resolveVttSegment } from '../../../media/dom/text/resolve-vtt-segment';\nimport {\n addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia,\n} from '../../../media/dom/text/text-track-slots';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport type {\n AudioTrack,\n CanPlayTrack,\n MaybeResolvedPresentation,\n MediaContainerData,\n TextTrack,\n VideoTrack,\n} from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { BandwidthConfig, BandwidthState } from '../../../network/bandwidth-estimator';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport type { TextTracksActor } from '../../actors/dom/text-tracks';\nimport type { TextTrackSegmentLoaderActor } from '../../actors/text-track-segment-loader';\nimport {\n calculatePresentationDuration,\n type PresentationDurationResolver,\n} from '../../behaviors/calculate-presentation-duration';\nimport { deriveCdnPriority } from '../../behaviors/derive-cdn-priority';\nimport { setupAirPlay } from '../../behaviors/dom/airplay';\nimport { applyStartPosition } from '../../behaviors/dom/apply-start-position';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadAudioSegments, loadTextTrackSegments, loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { setupAudioBufferActors, setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { setupTextTrackActors } from '../../behaviors/dom/setup-text-track-actors';\nimport { syncTextTracks } from '../../behaviors/dom/sync-text-tracks';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackLoadTriggers } from '../../behaviors/dom/track-load-triggers';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\n// Non-zero-PTS relocation (spike): remove this import, the composed reactor, the\n// `video/audio/textMessagePipelines` finalConfig entries, the `mediaContainerData`\n// state slot, and the `deriveStartMediaTime` config field to drop relocation entirely\n// (text then falls back to the plain `resolveVttSegment` resolver).\nimport {\n type DeriveStartMediaTime,\n deriveSharedMinStartMediaTime,\n establishStartMediaTime,\n} from '../../behaviors/establish-start-media-time';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveAudioTrack, resolveTextTrack, resolveVideoTrack } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack, switchTextTrack, switchVideoTrack } from '../../behaviors/track-switching';\nimport { relocatingTextPipelines, relocationPipelinesFor } from '../../primitives/relocation-pipelines';\nimport type { TextTrackSegmentResolver } from '../../primitives/text-segment-load-pipeline';\n\n// ============================================================================\n// HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the HLS playback engine.\n *\n * This is the union of all state required by the behaviors composed into\n * the HLS engine. Each behavior declares its own state interface; this\n * type satisfies all of them.\n */\nexport interface SimpleHlsEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n bandwidthState?: BandwidthState;\n // Non-zero-PTS relocation (spike): transient per-track container data owned by\n // `establishStartMediaTime`. Remove with the composed reactor.\n mediaContainerData?: Record<string, MediaContainerData>;\n userVideoTrackSelection?: Partial<VideoTrack>;\n /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection`. Partial-track shape — `{ language: 'es' }`,\n * `{ id: 'audio-en' }`, etc. `selectAudioTrack` reads this and re-picks\n * when it changes. Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * Consumer-driven *intent* for text selection, resolved into\n * `selectedTextTrackId` by `switchTextTrack`. A language-based partial\n * (`{ language: 'es' }`) selects captions, `'off'` disables them, and absence\n * means auto (the engine's `preferredSubtitleLanguage` / DEFAULT-track policy).\n * Also the write path for the DOM caption UI (via `syncTextTracks`); unlike the\n * resolved id it persists across source changes (sticky preference).\n */\n userTextTrackSelection?: Partial<TextTrack> | 'off';\n /**\n * The CDNs the source is served from (track-URL origins), in manifest\n * priority order — most-preferred first (mirrors HLS content steering's\n * `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`, read by\n * `track-switching`'s `preferActiveCdn` scope, which narrows to the\n * highest-priority CDN with surviving tracks so video / audio / text stay on\n * one host. Only meaningful for redundant-stream sources; a single-CDN source\n * has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids (origins) currently in failover cooldown — written by the CDN\n * monitor when a host fails too often, read by `track-switching`'s\n * `excludeFailedCdns` hard constraint, which prunes their tracks so the\n * active-CDN scope falls to the next CDN in `cdnPriority`. Empty / absent\n * means all CDNs are eligible.\n */\n failedCdns?: string[];\n currentTime?: number;\n loadActivated?: boolean;\n /**\n * One-shot command: start the current source at this position\n * (presentation-timeline seconds). Written by consumers or by\n * `setupAirPlay`'s session-end snapshot; consumed (cleared) by\n * `applyStartPosition` once the element seeks. See\n * `behaviors/dom/apply-start-position.ts`.\n */\n startPosition?: number;\n /**\n * Intent-level loading policy: initiate no new loading work while `true`.\n * Written by `setupAirPlay` (the only behavior declaring the key) while a\n * remote-playback session owns presentation; observed by the\n * `loadXSegments` dispatchers (park in `'dormant'`) and by\n * `setupMediaSource` (a pending rebuild waits). See\n * `SegmentLoadingState['loadingSuspended']`.\n */\n loadingSuspended?: boolean;\n /**\n * Author intent for the AirPlay/remote-playback picker, written by the media\n * adapter's `disableRemotePlayback` IDL property. `true` is an explicit\n * opt-out: `setupAirPlay` reads it at attach and sets nothing up, leaving the\n * element's remote playback disabled. Distinct from the underlying\n * `<video>.disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the HLS playback engine.\n *\n * Platform objects and actor references managed by HLS behaviors.\n */\nexport interface SimpleHlsEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n audioBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n textTracksActor?: TextTracksActor;\n textTrackSegmentLoaderActor?: TextTrackSegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type SimpleHlsEngineSignals = {\n state: StateSignals<SimpleHlsEngineState>;\n context: ContextSignals<SimpleHlsEngineContext>;\n};\n\n/**\n * Configuration for the HLS playback engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read.\n */\nexport interface SimpleHlsEngineConfig extends ShareSignalsConfig<SimpleHlsEngineState, SimpleHlsEngineContext> {\n /**\n * Bandwidth estimate in bps to use before enough samples have been\n * collected. Default: `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\n initialBandwidth?: number;\n /**\n * Codec capability probe injected into `track-switching`'s\n * `excludeUnplayableTracks` constraint — drops renditions the environment\n * can't decode before selection. Defaults to the `MediaSource.isTypeSupported`\n * -backed `canPlayTrack`; supply your own to override (e.g. force-exclude a\n * codec).\n */\n canPlayTrack?: CanPlayTrack;\n preferredAudioLanguage?: string;\n preferredSubtitleLanguage?: string;\n includeForcedTracks?: boolean;\n enableDefaultTrack?: boolean;\n /**\n * Resolver that turns a text-track segment fetch into VTT cues.\n * Defaults to the DOM-bound `resolveVttSegment` resolver, which uses an\n * offscreen `<track>` element to parse WebVTT.\n */\n resolveTextTrackSegment?: TextTrackSegmentResolver<VTTCue>;\n /**\n * Resolver for `presentation.duration`. Defaults to picking the first\n * resolved selected track's duration (video preferred, audio fallback) —\n * appropriate for VoD and audio-only. Live engines should supply a\n * resolver that returns `Number.POSITIVE_INFINITY` once the presentation\n * is established as live; downstream `updateMediaSourceDuration` propagates\n * that value to `mediaSource.duration` per the MSE spec.\n */\n resolveDuration?: PresentationDurationResolver;\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser; supply your own for alternate format\n * support without forking the engine.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Allocate SPF-owned text-track slots on the media element. Defaults to\n * the standard `<track>`-element implementation in\n * `media/dom/text/text-track-slots`.\n */\n addSubtitlesTracksToMedia?: typeof addSubtitlesTracksToMedia;\n /**\n * Return the SPF-owned subtitle/caption `TextTrack` currently in showing\n * mode. Defaults to the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n getShowingSubtitlesTrackFromMedia?: typeof getShowingSubtitlesTrackFromMedia;\n /**\n * Evict all SPF-owned text-track slots from the media element. Defaults to\n * the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n removeAllSubtitlesTracksFromMedia?: typeof removeAllSubtitlesTracksFromMedia;\n /**\n * Forward-buffer tuning. `bufferDuration` controls how far ahead of the\n * playhead segments are loaded (and where forward-flush kicks in).\n * Defaults: see `DEFAULT_FORWARD_BUFFER_CONFIG` (30 seconds). Threaded to\n * segment-loader actors (v/a + text) at construction time and to\n * `loadXSegments` dispatchers for the load-message range.\n */\n forwardBuffer?: Partial<ForwardBufferConfig>;\n /**\n * Back-buffer tuning. `keepSegments` controls how many segments stay\n * behind the playhead before eviction. Defaults: see\n * `DEFAULT_BACK_BUFFER_CONFIG` (2 segments). Threaded to the v/a\n * segment-loader actor only (text tracks don't use back-buffer eviction).\n */\n backBuffer?: Partial<BackBufferConfig>;\n /**\n * Bandwidth-estimator tuning. Overrides any field of `BandwidthConfig`\n * (`fastHalfLife`, `slowHalfLife`, `minTotalBytes`, `minBytes`,\n * `minDuration`). `bandwidth.minTotalBytes` supersedes the flat\n * `minTotalBytes` field above. Defaults: see `DEFAULT_BANDWIDTH_CONFIG`.\n */\n bandwidth?: Partial<BandwidthConfig>;\n /**\n * Quality-selection tuning. `safetyMargin` is the bandwidth-headroom\n * multiplier used by `selectQuality`; `upgradeMargin` is the hysteresis\n * ratio gating ABR upgrades. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15).\n */\n quality?: Partial<QualityConfig>;\n /**\n * Multi-CDN failover monitor tuning. `cooldownMs` is how long a CDN stays\n * excluded after a failed fetch trips it. Defaults:\n * `DEFAULT_FAILOVER_MONITOR_CONFIG` (300s). Only meaningful for redundant-stream\n * sources.\n */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * How to derive a CDN grouping key from a track URL — used to build\n * `cdnPriority`, to record the failover trip in `failedCdns`, and by the\n * track-switching CDN scope + failover constraint. One function, read by all of\n * them, so the keys stay comparable. Defaults to the URL origin; override to\n * key on something else (e.g. Mux's `cdn=` query param).\n */\n getCdnId?: GetCdnId;\n /**\n * Non-zero-PTS relocation (spike): the reduce seam consumed by the\n * `establishStartMediaTime` reactor. Defaults to per-track own origin (Tier 1);\n * a Tier-2 variant returns the shared `min` across selected A/V. Relocation is\n * composed into the standard engine below — see the marked block — so this only\n * needs setting to swap the tier policy. See\n * `internal/design/spf/presentation-timeline-model.md`.\n */\n deriveStartMediaTime?: DeriveStartMediaTime;\n /**\n * Proximity window (seconds) for the `recoverEndStall` behavior — how close the\n * playhead must be to the reachable buffered end for a `waiting` to be treated as the\n * end-of-stream freeze and nudged to `ended`. Defaults to `0.2`. See\n * `behaviors/dom/recover-end-stall`.\n */\n endStallNudgeWindow?: number;\n}\n\n// ============================================================================\n// HLS Playback Engine\n// ============================================================================\n\n/**\n * Generic `shareSignals` instantiated against the HLS engine's full state\n * and context — captures composition signal refs into the consumer's\n * `onSignalsReady` callback at setup time, and materializes input slots that no\n * composed behavior produces: `user*TrackSelection` (track-switching only reads\n * them). `failedCdns` is owned by `setupFailoverMonitor`, so it's already\n * materialized and reachable on the `onSignalsReady` refs without being listed\n * here.\n */\nconst shareSignals = makeShareSignals<SimpleHlsEngineState, SimpleHlsEngineContext>([\n 'userVideoTrackSelection',\n 'userAudioTrackSelection',\n 'userTextTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an HLS playback engine.\n *\n * Composes SPF behaviors into a reactive pipeline for HLS playback over MSE:\n * manifest resolution, track selection, ABR, segment loading, and\n * end-of-stream coordination.\n *\n * @example\n * ```ts\n * let signals: SimpleHlsEngineSignals;\n * const engine = createSimpleHlsEngine({\n * initialBandwidth: 2_000_000,\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * videoEl.play();\n *\n * await engine.destroy();\n * ```\n */\nexport function createSimpleHlsEngine(\n config: SimpleHlsEngineConfig = {}\n): Composition<SimpleHlsEngineState, SimpleHlsEngineContext> {\n // Non-zero-PTS relocation (spike): resolve the coordination seam once so the reactor\n // (model `startMediaTime`) and the loader stamps (buffer `timestampOffset`) apply the\n // SAME derive. Default is shared-`min` across selected A/V (subsumes per-type).\n const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;\n const finalConfig = {\n ...config,\n deriveStartMediaTime,\n // Baked (not user-overridable): this engine composes `setupAirPlay`,\n // whose native fallback `<source>` requires the MSE attachment to keep\n // sibling source alternatives part of resource selection.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n resolveTextTrackSegment: config.resolveTextTrackSegment ?? resolveVttSegment,\n // Non-zero-PTS relocation (spike): the text pipeline rebases cues onto the\n // relocated 0-based timeline. Remove `textMessagePipelines` to drop text relocation.\n textMessagePipelines: relocatingTextPipelines,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n addSubtitlesTracksToMedia: config.addSubtitlesTracksToMedia ?? addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia: config.getShowingSubtitlesTrackFromMedia ?? getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia: config.removeAllSubtitlesTracksFromMedia ?? removeAllSubtitlesTracksFromMedia,\n // Non-zero-PTS relocation (spike): the discover/stamp steps `establishStartMediaTime`\n // pairs with. They apply the same `deriveStartMediaTime` seam as the reactor. Remove\n // these two lines with the reactor.\n videoMessagePipelines: relocationPipelinesFor('video', deriveStartMediaTime),\n audioMessagePipelines: relocationPipelinesFor('audio', deriveStartMediaTime),\n };\n\n return createComposition(\n [\n syncPreload,\n trackLoadTriggers,\n resolvePresentation,\n\n // Session-level CDN priority for redundant-stream sources. Owns\n // `cdnPriority`; `track-switching`'s preferActiveCdn scope reads it so\n // every type stays on one CDN. No-op for single-CDN sources.\n //\n // Placed before switch* so `cdnPriority` is set before the first pick —\n // but this ordering is only *mildly* load-bearing, not required for\n // correctness. Selection is reactive: a late `cdnPriority` re-fires the\n // pick and converges on the same result (see the late-arrival test in\n // track-switching.test.ts). Order affects only a transient, and only for\n // an *asymmetric* manifest (a type listing a non-primary CDN first):\n // composing this after switch* would let that type fire one wasted\n // media-playlist fetch to the wrong CDN before correcting. Symmetric\n // redundant streams (the norm) never hit it — the first-listed CDN is\n // already the primary we'd pick anyway.\n deriveCdnPriority,\n\n // CDN failover cooldown: owns the expiry half of failover — watches\n // `failedCdns` (tripped directly by track resolution on a failed\n // media-playlist fetch) and removes each CDN once its cooldown lapses.\n setupFailoverMonitor,\n\n // Resolve selected tracks (fetch media playlists). Composed before the\n // switch* slot owners; selection is reactive, so a resolve* re-fires once\n // its switch* sets the id (same convergence for all three types).\n resolveVideoTrack,\n resolveAudioTrack,\n resolveTextTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Video cluster is registered first so that, when both\n // per-type variants flip to `'buffer-ready'` on the shared gate's\n // monitor evaluation, `addSourceBuffer(video)` runs before\n // `addSourceBuffer(audio)` — see the Firefox `mozHasAudio` invariant\n // in setup-buffer-actors.ts.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // ── Non-zero-PTS relocation (spike) ──────────────────────────────────\n // Establishes per-track `startMediaTime` and publishes the relocating\n // segment-loader pipelines to context. MUST precede `setup*BufferActors`\n // so the pipelines are published before the loaders read them. Remove this\n // one line (+ the import, the `mediaContainerData`/`*MessagePipelines`\n // slots including `textMessagePipelines`, and the `deriveStartMediaTime`\n // config) to drop relocation and test the Tier-0 baseline / bundle size.\n establishStartMediaTime,\n // ─────────────────────────────────────────────────────────────────────\n\n setupVideoBufferActors,\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere).\n setupAirPlay,\n\n // Playback tracking\n trackCurrentTime,\n // After trackCurrentTime: the one-shot currentTime seed must land after\n // the mirror's attach-time sync (see apply-start-position.ts).\n applyStartPosition,\n switchVideoTrack,\n switchAudioTrack,\n // Mid-stream audio-buffer flush on language switch is handled in\n // `segment-loader`'s `planTasks` (predicate: language differs from\n // the previously-buffered track) — not in switchAudioTrack itself.\n\n // Text selection: resolves `userTextTrackSelection` intent (incl. 'off',\n // or the configured preferred-language / DEFAULT-track policy) against the\n // failed-CDN-pruned, active-CDN-scoped text renditions. Optional selection\n // (captions are opt-in), so it can resolve to none.\n switchTextTrack,\n\n // Segment loading\n loadVideoSegments,\n loadAudioSegments,\n\n // End of stream coordination\n endOfStream,\n // Force native `ended` when Chrome freezes the playhead a few frames short of a\n // skewed-A/V end after `endOfStream` (audio-clock stall). Inert otherwise.\n recoverEndStall,\n\n // Text tracks\n syncTextTracks,\n setupTextTrackActors,\n loadTextTrackSegments,\n\n // Behavior whose sole purpose is to use a callback to allow for signal writing from the outside (e.g. an adapter)\n // NOTE: While not required, adding at the end since behaviors are setup in order, so this increases the likelihood\n // that initial signal setup will have occurred before shareSignals' callback is invoked. (CJP)\n shareSignals,\n ],\n {\n config: finalConfig,\n // Seed bandwidthState so switchVideoTrack fires on initial subscribe\n // with the `initialBandwidth` fallback rather than waiting for the\n // first chunk. The empty sample buffer means `getBandwidthEstimate`\n // returns the configured initial bandwidth until real samples land.\n initialState: {\n bandwidthState: {\n fastEstimate: 0,\n fastTotalWeight: 0,\n slowEstimate: 0,\n slowTotalWeight: 0,\n bytesSampled: 0,\n },\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAkUA,MAAM,eAAe,iBAA+D;CAClF;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,sBACd,SAAgC,CAAC,GAC0B;CAI3D,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAIA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,yBAAyB,OAAO,2BAA2B;EAG3D,sBAAsB;EACtB,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAC/C,2BAA2B,OAAO,6BAA6B;EAC/D,mCAAmC,OAAO,qCAAqC;EAC/E,mCAAmC,OAAO,qCAAqC;EAI/E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAC3E,uBAAuB,uBAAuB,SAAS,oBAAoB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAgBA;EAKA;EAKA;EACA;EACA;EAGA;EAOA;EACA;EASA;EAGA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EASA;EAGA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EAKA;CACF,GACA;EACE,QAAQ;EAKR,cAAc,EACZ,gBAAgB;GACd,cAAc;GACd,iBAAiB;GACjB,cAAc;GACd,iBAAiB;GACjB,cAAc;EAChB,EACF;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"engine.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { delayedReschedule } from '../../../core/tasks/delayed-reschedule';\nimport type { Reschedule } from '../../../core/tasks/task';\nimport type { QualityConfig } from '../../../media/abr/quality-selection';\nimport type { BackBufferConfig } from '../../../media/buffer/back-buffer';\nimport type { ForwardBufferConfig } from '../../../media/buffer/forward-buffer';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport { attachMediaSourceAsSourceElement } from '../../../media/dom/mse/mediasource-setup';\nimport { resolveVttSegment } from '../../../media/dom/text/resolve-vtt-segment';\nimport {\n addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia,\n} from '../../../media/dom/text/text-track-slots';\nimport type { SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport { mediaPlaylistReloadDelay, resolveLiveLatency } from '../../../media/hls/reload-policy';\nimport type {\n AudioTrack,\n CanPlayTrack,\n MaybeResolvedPresentation,\n MediaContainerData,\n ResolvedTrack,\n TextTrack,\n VideoTrack,\n} from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { BandwidthConfig, BandwidthState } from '../../../network/bandwidth-estimator';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport type { TextTracksActor } from '../../actors/dom/text-tracks';\nimport type { TextTrackSegmentLoaderActor } from '../../actors/text-track-segment-loader';\nimport {\n calculatePresentationDuration,\n type PresentationDurationResolver,\n} from '../../behaviors/calculate-presentation-duration';\nimport { collectErrors } from '../../behaviors/collect-errors';\nimport { deriveCdnPriority } from '../../behaviors/derive-cdn-priority';\nimport { setupAirPlay } from '../../behaviors/dom/airplay';\nimport { applyStartPosition } from '../../behaviors/dom/apply-start-position';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadAudioSegments, loadTextTrackSegments, loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { seekToLiveEdge } from '../../behaviors/dom/seek-to-live-edge';\nimport { setupAudioBufferActors, setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { setupTextTrackActors } from '../../behaviors/dom/setup-text-track-actors';\nimport { syncLiveSeekableRange } from '../../behaviors/dom/sync-live-seekable-range';\nimport { syncTextTracks } from '../../behaviors/dom/sync-text-tracks';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackLoadTriggers } from '../../behaviors/dom/track-load-triggers';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\n// Non-zero-PTS relocation (spike): remove this import, the composed reactor, the\n// `video/audio/textMessagePipelines` finalConfig entries, the `mediaContainerData`\n// state slot, and the `deriveStartMediaTime` config field to drop relocation entirely\n// (text then falls back to the plain `resolveVttSegment` resolver).\nimport {\n type DeriveStartMediaTime,\n deriveSharedMinStartMediaTime,\n establishStartMediaTime,\n gateFirstParseOnAnchor,\n} from '../../behaviors/establish-start-media-time';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveAudioTrack, resolveTextTrack, resolveVideoTrack } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack, switchTextTrack, switchVideoTrack } from '../../behaviors/track-switching';\nimport { relocatingTextPipelines, relocationPipelinesFor } from '../../primitives/relocation-pipelines';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\nimport type { TextTrackSegmentResolver } from '../../primitives/text-segment-load-pipeline';\n\n// ============================================================================\n// HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the HLS playback engine.\n *\n * This is the union of all state required by the behaviors composed into\n * the HLS engine. Each behavior declares its own state interface; this\n * type satisfies all of them.\n */\nexport interface HlsVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n bandwidthState?: BandwidthState;\n // Non-zero-PTS relocation (spike): transient per-track container data owned by\n // `establishStartMediaTime`. Remove with the composed reactor.\n mediaContainerData?: Record<string, MediaContainerData>;\n userVideoTrackSelection?: Partial<VideoTrack>;\n /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection`. Partial-track shape — `{ language: 'es' }`,\n * `{ id: 'audio-en' }`, etc. `selectAudioTrack` reads this and re-picks\n * when it changes. Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * Consumer-driven *intent* for text selection, resolved into\n * `selectedTextTrackId` by `switchTextTrack`. A language-based partial\n * (`{ language: 'es' }`) selects captions, `'off'` disables them, and absence\n * means auto (the engine's `preferredSubtitleLanguage` / DEFAULT-track policy).\n * Also the write path for the DOM caption UI (via `syncTextTracks`); unlike the\n * resolved id it persists across source changes (sticky preference).\n */\n userTextTrackSelection?: Partial<TextTrack> | 'off';\n /**\n * The CDNs the source is served from (track-URL origins), in manifest\n * priority order — most-preferred first (mirrors HLS content steering's\n * `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`, read by\n * `track-switching`'s `preferActiveCdn` scope, which narrows to the\n * highest-priority CDN with surviving tracks so video / audio / text stay on\n * one host. Only meaningful for redundant-stream sources; a single-CDN source\n * has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids (origins) currently in failover cooldown — written by the CDN\n * monitor when a host fails too often, read by `track-switching`'s\n * `excludeFailedCdns` hard constraint, which prunes their tracks so the\n * active-CDN scope falls to the next CDN in `cdnPriority`. Empty / absent\n * means all CDNs are eligible.\n */\n failedCdns?: string[];\n /**\n * Conditions reported during playback, in the order encountered — appended by\n * whichever behavior detects one (`emitError`), owned and cleared per source by\n * `collectErrors`. Carries no severity: which of these is fatal is decided\n * above the engine, at the adapter. See\n * `internal/design/spf/features/errors.md`.\n */\n errors?: SvtaError[];\n currentTime?: number;\n loadActivated?: boolean;\n /**\n * One-shot command: start the current source at this position\n * (presentation-timeline seconds). Written by consumers or by\n * `setupAirPlay`'s session-end snapshot; consumed (cleared) by\n * `applyStartPosition` once the element seeks. See\n * `behaviors/dom/apply-start-position.ts`.\n */\n startPosition?: number;\n /**\n * Intent-level loading policy: initiate no new loading work while `true`.\n * Written by `setupAirPlay` (the only behavior declaring the key) while a\n * remote-playback session owns presentation; observed by the\n * `loadXSegments` dispatchers (park in `'dormant'`) and by\n * `setupMediaSource` (a pending rebuild waits). See\n * `SegmentLoadingState['loadingSuspended']`.\n */\n loadingSuspended?: boolean;\n /**\n * Author intent for the AirPlay/remote-playback picker, written by the media\n * adapter's `disableRemotePlayback` IDL property. `true` is an explicit\n * opt-out: `setupAirPlay` reads it at attach and sets nothing up, leaving the\n * element's remote playback disabled. Distinct from the underlying\n * `<video>.disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the HLS playback engine.\n *\n * Platform objects and actor references managed by HLS behaviors.\n */\nexport interface HlsVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n audioBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n textTracksActor?: TextTracksActor;\n textTrackSegmentLoaderActor?: TextTrackSegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type HlsVideoEngineSignals = {\n state: StateSignals<HlsVideoEngineState>;\n context: ContextSignals<HlsVideoEngineContext>;\n};\n\n/**\n * Configuration for the HLS playback engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read.\n */\nexport interface HlsVideoEngineConfig extends ShareSignalsConfig<HlsVideoEngineState, HlsVideoEngineContext> {\n /**\n * Bandwidth estimate in bps to use before enough samples have been\n * collected. Default: `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\n initialBandwidth?: number;\n /**\n * Codec capability probe injected into `track-switching`'s\n * `excludeUnplayableTracks` constraint — drops renditions the environment\n * can't decode before selection. Defaults to the `MediaSource.isTypeSupported`\n * -backed `canPlayTrack`; supply your own to override (e.g. force-exclude a\n * codec).\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Conditions reported about each rendition as it resolves — the *causes* behind\n * a later verdict, and the copy a verdict reuses when they agree. Defaults to\n * {@link reportUnsupportedTrackConditions}, which reports non-fMP4 containers\n * and encryption; supply your own to report a different set (a provider that\n * never ships MPEG-TS can drop that check) or `() => []` to report nothing.\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n preferredAudioLanguage?: string;\n preferredSubtitleLanguage?: string;\n includeForcedTracks?: boolean;\n enableDefaultTrack?: boolean;\n /**\n * Resolver that turns a text-track segment fetch into VTT cues.\n * Defaults to the DOM-bound `resolveVttSegment` resolver, which uses an\n * offscreen `<track>` element to parse WebVTT.\n */\n resolveTextTrackSegment?: TextTrackSegmentResolver<VTTCue>;\n /**\n * Resolver for `presentation.duration`. Defaults to picking the first\n * resolved selected track's duration (video preferred, audio fallback) —\n * appropriate for VoD and audio-only. Live engines should supply a\n * resolver that returns `Number.POSITIVE_INFINITY` once the presentation\n * is established as live; downstream `updateMediaSourceDuration` propagates\n * that value to `mediaSource.duration` per the MSE spec.\n */\n resolveDuration?: PresentationDurationResolver;\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser; supply your own for alternate format\n * support without forking the engine.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Allocate SPF-owned text-track slots on the media element. Defaults to\n * the standard `<track>`-element implementation in\n * `media/dom/text/text-track-slots`.\n */\n addSubtitlesTracksToMedia?: typeof addSubtitlesTracksToMedia;\n /**\n * Return the SPF-owned subtitle/caption `TextTrack` currently in showing\n * mode. Defaults to the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n getShowingSubtitlesTrackFromMedia?: typeof getShowingSubtitlesTrackFromMedia;\n /**\n * Evict all SPF-owned text-track slots from the media element. Defaults to\n * the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n removeAllSubtitlesTracksFromMedia?: typeof removeAllSubtitlesTracksFromMedia;\n /**\n * Forward-buffer tuning. `bufferDuration` controls how far ahead of the\n * playhead segments are loaded (and where forward-flush kicks in).\n * Defaults: see `DEFAULT_FORWARD_BUFFER_CONFIG` (30 seconds). Threaded to\n * segment-loader actors (v/a + text) at construction time and to\n * `loadXSegments` dispatchers for the load-message range.\n */\n forwardBuffer?: Partial<ForwardBufferConfig>;\n /**\n * Back-buffer tuning. `keepSegments` controls how many segments stay\n * behind the playhead before eviction. Defaults: see\n * `DEFAULT_BACK_BUFFER_CONFIG` (2 segments). Threaded to the v/a\n * segment-loader actor only (text tracks don't use back-buffer eviction).\n */\n backBuffer?: Partial<BackBufferConfig>;\n /**\n * Bandwidth-estimator tuning. Overrides any field of `BandwidthConfig`\n * (`fastHalfLife`, `slowHalfLife`, `minTotalBytes`, `minBytes`,\n * `minDuration`). `bandwidth.minTotalBytes` supersedes the flat\n * `minTotalBytes` field above. Defaults: see `DEFAULT_BANDWIDTH_CONFIG`.\n */\n bandwidth?: Partial<BandwidthConfig>;\n /**\n * Quality-selection tuning. `safetyMargin` is the bandwidth-headroom\n * multiplier used by `selectQuality`; `upgradeMargin` is the hysteresis\n * ratio gating ABR upgrades. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15).\n */\n quality?: Partial<QualityConfig>;\n /**\n * Multi-CDN failover monitor tuning. `cooldownMs` is how long a CDN stays\n * excluded after a failed fetch trips it. Defaults:\n * `DEFAULT_FAILOVER_MONITOR_CONFIG` (300s). Only meaningful for redundant-stream\n * sources.\n */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * How to derive a CDN grouping key from a track URL — used to build\n * `cdnPriority`, to record the failover trip in `failedCdns`, and by the\n * track-switching CDN scope + failover constraint. One function, read by all of\n * them, so the keys stay comparable. Defaults to the URL origin; override to\n * key on something else (e.g. Mux's `cdn=` query param).\n */\n getCdnId?: GetCdnId;\n /**\n * Non-zero-PTS relocation (spike): the reduce seam consumed by the\n * `establishStartMediaTime` reactor. Defaults to per-track own origin (Tier 1);\n * a Tier-2 variant returns the shared `min` across selected A/V. Relocation is\n * composed into the standard engine below — see the marked block — so this only\n * needs setting to swap the tier policy. See\n * `internal/design/spf/presentation-timeline-model.md`.\n */\n deriveStartMediaTime?: DeriveStartMediaTime;\n /**\n * Proximity window (seconds) for the `recoverEndStall` behavior — how close the\n * playhead must be to the reachable buffered end for a `waiting` to be treated as the\n * end-of-stream freeze and nudged to `ended`. Defaults to `0.2`. See\n * `behaviors/dom/recover-end-stall`.\n */\n endStallNudgeWindow?: number;\n /**\n * Live media-playlist re-run policy for the resolve* loaders' `RecurringRunner`:\n * returns a promise that resolves when the playlist should reload, or `null` to\n * stop. Defaults to `mediaPlaylistReloadDelay` (target-duration cadence, half on\n * an unchanged window, stop on `#EXT-X-ENDLIST`) composed with a cancellable\n * `sleep`. Inert for VoD (a complete playlist stops it after the first resolve).\n * Override to tune live reload timing.\n */\n reschedule?: Reschedule<ResolvedTrack>;\n}\n\n// ============================================================================\n// HLS Playback Engine\n// ============================================================================\n\n/**\n * Generic `shareSignals` instantiated against the HLS engine's full state\n * and context — captures composition signal refs into the consumer's\n * `onSignalsReady` callback at setup time, and materializes input slots that no\n * composed behavior produces: `user*TrackSelection` (track-switching only reads\n * them). `failedCdns` is owned by `setupFailoverMonitor`, so it's already\n * materialized and reachable on the `onSignalsReady` refs without being listed\n * here.\n */\nconst shareSignals = makeShareSignals<HlsVideoEngineState, HlsVideoEngineContext>([\n 'userVideoTrackSelection',\n 'userAudioTrackSelection',\n 'userTextTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an HLS playback engine.\n *\n * Composes SPF behaviors into a reactive pipeline for HLS playback over MSE:\n * manifest resolution, track selection, ABR, segment loading, and\n * end-of-stream coordination.\n *\n * @example\n * ```ts\n * let signals: HlsVideoEngineSignals;\n * const engine = createHlsVideoEngine({\n * initialBandwidth: 2_000_000,\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * videoEl.play();\n *\n * await engine.destroy();\n * ```\n */\nexport function createHlsVideoEngine(\n config: HlsVideoEngineConfig = {}\n): Composition<HlsVideoEngineState, HlsVideoEngineContext> {\n // Non-zero-PTS relocation (spike): resolve the coordination seam once so the reactor\n // (model `startMediaTime`) and the loader stamps (buffer `timestampOffset`) apply the\n // SAME derive. Default is shared-`min` across selected A/V (subsumes per-type).\n const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;\n const finalConfig = {\n ...config,\n deriveStartMediaTime,\n // Baked (not user-overridable): this engine composes `setupAirPlay`,\n // whose native fallback `<source>` requires the MSE attachment to keep\n // sibling source alternatives part of resource selection.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n resolveTextTrackSegment: config.resolveTextTrackSegment ?? resolveVttSegment,\n // Non-zero-PTS relocation (spike): the text pipeline rebases cues onto the\n // relocated 0-based timeline. Remove `textMessagePipelines` to drop text relocation.\n textMessagePipelines: relocatingTextPipelines,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n addSubtitlesTracksToMedia: config.addSubtitlesTracksToMedia ?? addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia: config.getShowingSubtitlesTrackFromMedia ?? getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia: config.removeAllSubtitlesTracksFromMedia ?? removeAllSubtitlesTracksFromMedia,\n // Non-zero-PTS relocation (spike): the discover/stamp steps `establishStartMediaTime`\n // pairs with. They apply the same `deriveStartMediaTime` seam as the reactor. Remove\n // these two lines with the reactor.\n videoMessagePipelines: relocationPipelinesFor('video', deriveStartMediaTime),\n audioMessagePipelines: relocationPipelinesFor('audio', deriveStartMediaTime),\n // Live-anchor establishment order: each non-reference track's first parse\n // waits for the reference track to settle the wall-clock anchor question\n // (see `gate-first-parse.ts`); pairs with the reactor's anchor stamp.\n gateFirstParse: gateFirstParseOnAnchor,\n // Format-neutral live-latency seam for `seekToLiveEdge` — the HLS resolver\n // (HOLD-BACK); a DASH engine would inject `suggestedPresentationDelay`.\n resolveLiveLatency,\n // The resolve* loaders' RecurringRunner re-runs on this `reschedule`: the pure\n // target-duration cadence, start-anchored + made awaitable by `delayedReschedule`.\n // Inert for VoD (the cadence returns null once a playlist is complete), so it\n // composes always.\n reschedule: config.reschedule ?? delayedReschedule(mediaPlaylistReloadDelay),\n };\n\n return createComposition(\n [\n syncPreload,\n trackLoadTriggers,\n resolvePresentation,\n\n // Session-level CDN priority for redundant-stream sources. Owns\n // `cdnPriority`; `track-switching`'s preferActiveCdn scope reads it so\n // every type stays on one CDN. No-op for single-CDN sources.\n //\n // Placed before switch* so `cdnPriority` is set before the first pick —\n // but this ordering is only *mildly* load-bearing, not required for\n // correctness. Selection is reactive: a late `cdnPriority` re-fires the\n // pick and converges on the same result (see the late-arrival test in\n // track-switching.test.ts). Order affects only a transient, and only for\n // an *asymmetric* manifest (a type listing a non-primary CDN first):\n // composing this after switch* would let that type fire one wasted\n // media-playlist fetch to the wrong CDN before correcting. Symmetric\n // redundant streams (the norm) never hit it — the first-listed CDN is\n // already the primary we'd pick anyway.\n deriveCdnPriority,\n\n // CDN failover cooldown: owns the expiry half of failover — watches\n // `failedCdns` (tripped directly by track resolution on a failed\n // media-playlist fetch) and removes each CDN once its cooldown lapses.\n setupFailoverMonitor,\n\n // Owns `errors` and its per-source lifecycle. Composed before the\n // behaviors that report into it so the slot exists when they first run;\n // reporting no-ops if it isn't composed at all.\n collectErrors,\n\n // Resolve selected tracks (fetch media playlists). Composed before the\n // switch* slot owners; selection is reactive, so a resolve* re-fires once\n // its switch* sets the id (same convergence for all three types).\n resolveVideoTrack,\n resolveAudioTrack,\n resolveTextTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Video cluster is registered first so that, when both\n // per-type variants flip to `'buffer-ready'` on the shared gate's\n // monitor evaluation, `addSourceBuffer(video)` runs before\n // `addSourceBuffer(audio)` — see the Firefox `mozHasAudio` invariant\n // in setup-buffer-actors.ts.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // ── Non-zero-PTS relocation (spike) ──────────────────────────────────\n // Establishes per-track `startMediaTime` and publishes the relocating\n // segment-loader pipelines to context. MUST precede `setup*BufferActors`\n // so the pipelines are published before the loaders read them. Remove this\n // one line (+ the import, the `mediaContainerData`/`*MessagePipelines`\n // slots including `textMessagePipelines`, and the `deriveStartMediaTime`\n // config) to drop relocation and test the Tier-0 baseline / bundle size.\n establishStartMediaTime,\n // ─────────────────────────────────────────────────────────────────────\n\n setupVideoBufferActors,\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere).\n setupAirPlay,\n\n // Playback tracking\n trackCurrentTime,\n // After trackCurrentTime: the one-shot currentTime seed must land after\n // the mirror's attach-time sync (see apply-start-position.ts).\n applyStartPosition,\n switchVideoTrack,\n switchAudioTrack,\n // Mid-stream audio-buffer flush on language switch is handled in\n // `segment-loader`'s `planTasks` (predicate: language differs from\n // the previously-buffered track) — not in switchAudioTrack itself.\n\n // Text selection: resolves `userTextTrackSelection` intent (incl. 'off',\n // or the configured preferred-language / DEFAULT-track policy) against the\n // failed-CDN-pruned, active-CDN-scoped text renditions. Optional selection\n // (captions are opt-in), so it can resolve to none.\n switchTextTrack,\n\n // Segment loading\n loadVideoSegments,\n loadAudioSegments,\n\n // Live: declare the seekable window, then command the live-edge start\n // position + keep the playhead in-window. No-op for complete playlists\n // (VoD / ended). `seekToLiveEdge` commands `state.startPosition`;\n // `applyStartPosition` (composed above) performs the seek.\n syncLiveSeekableRange,\n seekToLiveEdge,\n\n // End of stream coordination\n endOfStream,\n // Force native `ended` when Chrome freezes the playhead a few frames short of a\n // skewed-A/V end after `endOfStream` (audio-clock stall). Inert otherwise.\n recoverEndStall,\n\n // Text tracks\n syncTextTracks,\n setupTextTrackActors,\n loadTextTrackSegments,\n\n // Behavior whose sole purpose is to use a callback to allow for signal writing from the outside (e.g. an adapter)\n // NOTE: While not required, adding at the end since behaviors are setup in order, so this increases the likelihood\n // that initial signal setup will have occurred before shareSignals' callback is invoked. (CJP)\n shareSignals,\n ],\n {\n config: finalConfig,\n // Seed bandwidthState so switchVideoTrack fires on initial subscribe\n // with the `initialBandwidth` fallback rather than waiting for the\n // first chunk. The empty sample buffer means `getBandwidthEstimate`\n // returns the configured initial bandwidth until real samples land.\n initialState: {\n bandwidthState: {\n fastEstimate: 0,\n fastTotalWeight: 0,\n slowEstimate: 0,\n slowTotalWeight: 0,\n bytesSampled: 0,\n },\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwWA,MAAM,eAAe,iBAA6D;CAChF;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,qBACd,SAA+B,CAAC,GACyB;CAIzD,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAIA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;EAC7E,yBAAyB,OAAO,2BAA2B;EAG3D,sBAAsB;EACtB,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAC/C,2BAA2B,OAAO,6BAA6B;EAC/D,mCAAmC,OAAO,qCAAqC;EAC/E,mCAAmC,OAAO,qCAAqC;EAI/E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAC3E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAI3E,gBAAgB;EAGhB;EAKA,YAAY,OAAO,cAAc,kBAAkB,wBAAwB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAgBA;EAKA;EAKA;EAKA;EACA;EACA;EAGA;EAOA;EACA;EASA;EAGA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EASA;EAGA;EACA;EAMA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EAKA;CACF,GACA;EACE,QAAQ;EAKR,cAAc,EACZ,gBAAgB;GACd,cAAc;GACd,iBAAiB;GACjB,cAAc;GACd,iBAAiB;GACjB,cAAc;EAChB,EACF;CACF,CACF;AACF"}
|
|
@@ -0,0 +1,39 @@
|
|
|
1
|
+
//#region src/playback/primitives/error-messages.ts
|
|
2
|
+
/**
|
|
3
|
+
* Developer-facing copy for what this engine reports.
|
|
4
|
+
*
|
|
5
|
+
* Everything here reaches a **console**, never a viewer. Viewer-facing copy for
|
|
6
|
+
* a fatal condition is the presentation layer's to compose: the engine reports a
|
|
7
|
+
* code, and a consumer maps that code to localized text it owns.
|
|
8
|
+
*
|
|
9
|
+
* Plain string constants, one export each. Nothing is parameterized — a message
|
|
10
|
+
* that names the engine has to be built at the call site from state the engine
|
|
11
|
+
* carries around solely to say it, which is a lot of plumbing for a console
|
|
12
|
+
* prefix. Separate exports rather than one object so a composition that logs
|
|
13
|
+
* neither notice doesn't carry their bytes.
|
|
14
|
+
*/
|
|
15
|
+
/**
|
|
16
|
+
* Logged when a fatal `SVTA_UNSUPPORTED_PLAYBACK_FEATURE` is surfaced.
|
|
17
|
+
*
|
|
18
|
+
* The developer's half of that event; the viewer gets the localized copy the
|
|
19
|
+
* code maps to. One sentence is enough because the specifics — which container,
|
|
20
|
+
* which rendition, whether it was DRM — stay structured on the reported
|
|
21
|
+
* conditions logged beside it.
|
|
22
|
+
*/
|
|
23
|
+
const UNSUPPORTED_PLAYBACK_FEATURE_MESSAGE = "Can't play this source: it requires an unsupported playback feature.";
|
|
24
|
+
/**
|
|
25
|
+
* LL-HLS delivery, played as standard live. The parser ignores partial segments
|
|
26
|
+
* and the loader fetches whole ones, so latency lands wherever `HOLD-BACK` puts
|
|
27
|
+
* it — the stream plays, just not at the latency it was published for.
|
|
28
|
+
*/
|
|
29
|
+
const LOW_LATENCY_UNSUPPORTED_MESSAGE = "Low-Latency HLS is unsupported; playing as standard live at higher latency.";
|
|
30
|
+
/**
|
|
31
|
+
* `#EXT-X-PLAYLIST-TYPE:EVENT` — a growing window, which is how DVR is
|
|
32
|
+
* delivered. It plays, but the seekable-range and live-edge handling for it is
|
|
33
|
+
* newer and less exercised than sliding-window live.
|
|
34
|
+
*/
|
|
35
|
+
const DVR_EXPERIMENTAL_MESSAGE = "DVR support for EVENT playlists is experimental.";
|
|
36
|
+
//#endregion
|
|
37
|
+
export { DVR_EXPERIMENTAL_MESSAGE, LOW_LATENCY_UNSUPPORTED_MESSAGE, UNSUPPORTED_PLAYBACK_FEATURE_MESSAGE };
|
|
38
|
+
|
|
39
|
+
//# sourceMappingURL=error-messages.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"error-messages.js","names":[],"sources":["../../../../src/playback/primitives/error-messages.ts"],"sourcesContent":["/**\n * Developer-facing copy for what this engine reports.\n *\n * Everything here reaches a **console**, never a viewer. Viewer-facing copy for\n * a fatal condition is the presentation layer's to compose: the engine reports a\n * code, and a consumer maps that code to localized text it owns.\n *\n * Plain string constants, one export each. Nothing is parameterized — a message\n * that names the engine has to be built at the call site from state the engine\n * carries around solely to say it, which is a lot of plumbing for a console\n * prefix. Separate exports rather than one object so a composition that logs\n * neither notice doesn't carry their bytes.\n */\n\n/**\n * Logged when a fatal `SVTA_UNSUPPORTED_PLAYBACK_FEATURE` is surfaced.\n *\n * The developer's half of that event; the viewer gets the localized copy the\n * code maps to. One sentence is enough because the specifics — which container,\n * which rendition, whether it was DRM — stay structured on the reported\n * conditions logged beside it.\n */\nexport const UNSUPPORTED_PLAYBACK_FEATURE_MESSAGE =\n \"Can't play this source: it requires an unsupported playback feature.\";\n\n/**\n * LL-HLS delivery, played as standard live. The parser ignores partial segments\n * and the loader fetches whole ones, so latency lands wherever `HOLD-BACK` puts\n * it — the stream plays, just not at the latency it was published for.\n */\nexport const LOW_LATENCY_UNSUPPORTED_MESSAGE =\n 'Low-Latency HLS is unsupported; playing as standard live at higher latency.';\n\n/**\n * `#EXT-X-PLAYLIST-TYPE:EVENT` — a growing window, which is how DVR is\n * delivered. It plays, but the seekable-range and live-edge handling for it is\n * newer and less exercised than sliding-window live.\n */\nexport const DVR_EXPERIMENTAL_MESSAGE = 'DVR support for EVENT playlists is experimental.';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAsBA,MAAa,uCACX;;;;;;AAOF,MAAa,kCACX;;;;;;AAOF,MAAa,2BAA2B"}
|
|
@@ -0,0 +1,66 @@
|
|
|
1
|
+
import { getTracksByType } from "../../media/utils/tracks.js";
|
|
2
|
+
import { liveWindowFor } from "../../media/live-window.js";
|
|
3
|
+
//#region src/playback/primitives/live-window.ts
|
|
4
|
+
/**
|
|
5
|
+
* The id of the timeline-bearing track: the selected video track when present,
|
|
6
|
+
* else the selected audio track. The single pick both the window derivation and
|
|
7
|
+
* the live-latency resolution (`seek-to-live-edge`) share, so they can't drift.
|
|
8
|
+
*/
|
|
9
|
+
function liveTrackId(state) {
|
|
10
|
+
return state.selectedVideoTrackId?.get() ?? state.selectedAudioTrackId?.get();
|
|
11
|
+
}
|
|
12
|
+
/**
|
|
13
|
+
* One type's window: the selected track's when it's resolved, else any resolved
|
|
14
|
+
* track of the type. The fallback keeps the window from blinking to `null`
|
|
15
|
+
* mid ABR / user switch — all renditions of a type are time-aligned and share
|
|
16
|
+
* the anchor, so a deselected track's window may trail live by up to one reload
|
|
17
|
+
* during the switch gap (acceptable; the selected track's fresh window resumes
|
|
18
|
+
* the moment it resolves). A null blink would flip `seekToLiveEdge` out of
|
|
19
|
+
* `live` and stall the seekable-range writer.
|
|
20
|
+
*/
|
|
21
|
+
function liveWindowForType(presentation, selectedId, type) {
|
|
22
|
+
if (!presentation || selectedId === void 0) return null;
|
|
23
|
+
const selected = liveWindowFor(presentation, selectedId);
|
|
24
|
+
if (selected) return selected;
|
|
25
|
+
for (const track of getTracksByType(presentation, type)) {
|
|
26
|
+
const window = liveWindowFor(presentation, track.id);
|
|
27
|
+
if (window) return window;
|
|
28
|
+
}
|
|
29
|
+
return null;
|
|
30
|
+
}
|
|
31
|
+
function liveWindowFromState(state) {
|
|
32
|
+
const presentation = state.presentation.get();
|
|
33
|
+
const video = liveWindowForType(presentation, state.selectedVideoTrackId?.get(), "video");
|
|
34
|
+
const audio = liveWindowForType(presentation, state.selectedAudioTrackId?.get(), "audio");
|
|
35
|
+
if (video && audio) {
|
|
36
|
+
const start = Math.max(video.start, audio.start);
|
|
37
|
+
const end = Math.min(video.end, audio.end);
|
|
38
|
+
return start < end ? {
|
|
39
|
+
start,
|
|
40
|
+
end
|
|
41
|
+
} : null;
|
|
42
|
+
}
|
|
43
|
+
return video ?? audio;
|
|
44
|
+
}
|
|
45
|
+
/**
|
|
46
|
+
* Resolve the live edge — the window bounds plus the target playhead position —
|
|
47
|
+
* from a behavior's setup arguments. Bundles the window geometry and the
|
|
48
|
+
* format-specific latency policy (`config.resolveLiveLatency`) so the consuming
|
|
49
|
+
* behavior never has to compose them; it just forwards its `{ state, config }`.
|
|
50
|
+
* `null` when there is no live edge (VOD / ended / unresolved).
|
|
51
|
+
*
|
|
52
|
+
* Reads signals lazily — call it inside a reactive context (an effect).
|
|
53
|
+
*/
|
|
54
|
+
function getLiveEdge({ state, config }) {
|
|
55
|
+
const window = liveWindowFromState(state);
|
|
56
|
+
if (!window) return null;
|
|
57
|
+
const latency = config?.resolveLiveLatency?.(state.presentation.get(), liveTrackId(state)) ?? 0;
|
|
58
|
+
return {
|
|
59
|
+
...window,
|
|
60
|
+
liveEdgeStart: Math.max(window.start, window.end - latency)
|
|
61
|
+
};
|
|
62
|
+
}
|
|
63
|
+
//#endregion
|
|
64
|
+
export { getLiveEdge, liveTrackId, liveWindowFromState };
|
|
65
|
+
|
|
66
|
+
//# sourceMappingURL=live-window.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"live-window.js","names":[],"sources":["../../../../src/playback/primitives/live-window.ts"],"sourcesContent":["/**\n * Resolve the live window from engine state — the single call site the\n * seek-to-live-edge and live-seekable-range behaviors share, so their window\n * derivation can't drift apart.\n *\n * The window is the **intersection over the selected A/V tracks'** windows\n * (`max` of starts, `min` of ends): publication skew between the two playlists\n * shrinks the window to what both can actually serve, and the `max` also clamps\n * the legitimate *negative* early `startTime` of a non-reference track whose\n * window precedes the join point (presentation-0) — see\n * `internal/design/spf/live-presentation-timeline-model.md` (Phase 2 window\n * math). With one selected type (video-only / audio-only) its window stands\n * alone.\n *\n * Reads signals lazily — call it inside a reactive context (an effect) so the\n * read tracks `presentation` + the selected-track ids.\n */\nimport type { ReadonlySignal } from '../../core/signals/primitives';\nimport { type LiveWindow, liveWindowFor } from '../../media/live-window';\nimport type { MaybeResolvedPresentation, TrackType } from '../../media/types';\nimport { getTracksByType } from '../../media/utils/tracks';\n\nexport interface LiveWindowState {\n presentation: ReadonlySignal<MaybeResolvedPresentation | undefined>;\n selectedVideoTrackId?: ReadonlySignal<string | undefined>;\n selectedAudioTrackId?: ReadonlySignal<string | undefined>;\n}\n\n/**\n * The id of the timeline-bearing track: the selected video track when present,\n * else the selected audio track. The single pick both the window derivation and\n * the live-latency resolution (`seek-to-live-edge`) share, so they can't drift.\n */\nexport function liveTrackId(state: LiveWindowState): string | undefined {\n return state.selectedVideoTrackId?.get() ?? state.selectedAudioTrackId?.get();\n}\n\n/**\n * One type's window: the selected track's when it's resolved, else any resolved\n * track of the type. The fallback keeps the window from blinking to `null`\n * mid ABR / user switch — all renditions of a type are time-aligned and share\n * the anchor, so a deselected track's window may trail live by up to one reload\n * during the switch gap (acceptable; the selected track's fresh window resumes\n * the moment it resolves). A null blink would flip `seekToLiveEdge` out of\n * `live` and stall the seekable-range writer.\n */\nfunction liveWindowForType(\n presentation: MaybeResolvedPresentation | undefined,\n selectedId: string | undefined,\n type: TrackType\n): LiveWindow | null {\n if (!presentation || selectedId === undefined) return null;\n const selected = liveWindowFor(presentation, selectedId);\n if (selected) return selected;\n for (const track of getTracksByType(presentation, type)) {\n const window = liveWindowFor(presentation, track.id);\n if (window) return window;\n }\n return null;\n}\n\nexport function liveWindowFromState(state: LiveWindowState): LiveWindow | null {\n const presentation = state.presentation.get();\n const video = liveWindowForType(presentation, state.selectedVideoTrackId?.get(), 'video');\n const audio = liveWindowForType(presentation, state.selectedAudioTrackId?.get(), 'audio');\n if (video && audio) {\n const start = Math.max(video.start, audio.start);\n const end = Math.min(video.end, audio.end);\n // A degenerate intersection (disjoint windows — one playlist stalled a full\n // window behind the other) means there is no position both types can serve:\n // no live edge, rather than an invented one.\n return start < end ? { start, end } : null;\n }\n return video ?? audio;\n}\n\n/**\n * Resolve the target live latency (seconds the playhead should trail the live\n * edge) for the timeline-bearing track. Format-specific — supplied by the engine\n * (HLS: `HOLD-BACK`; DASH would use `suggestedPresentationDelay`) — so the live\n * edge stays format-neutral.\n */\nexport type ResolveLiveLatency = (\n presentation: MaybeResolvedPresentation | undefined,\n trackId: string | undefined\n) => number;\n\n/** The live window plus the target playhead position within it. */\nexport interface LiveEdge extends LiveWindow {\n /** Where to sit near the live edge: `end` − live latency, clamped to `start`. */\n liveEdgeStart: number;\n}\n\n/**\n * Resolve the live edge — the window bounds plus the target playhead position —\n * from a behavior's setup arguments. Bundles the window geometry and the\n * format-specific latency policy (`config.resolveLiveLatency`) so the consuming\n * behavior never has to compose them; it just forwards its `{ state, config }`.\n * `null` when there is no live edge (VOD / ended / unresolved).\n *\n * Reads signals lazily — call it inside a reactive context (an effect).\n */\nexport function getLiveEdge({\n state,\n // context, // not needed yet; in the shape for setup-parity when it is\n config,\n}: {\n state: LiveWindowState;\n config?: { resolveLiveLatency?: ResolveLiveLatency };\n}): LiveEdge | null {\n const window = liveWindowFromState(state);\n if (!window) return null;\n const latency = config?.resolveLiveLatency?.(state.presentation.get(), liveTrackId(state)) ?? 0;\n return { ...window, liveEdgeStart: Math.max(window.start, window.end - latency) };\n}\n"],"mappings":";;;;;;;;AAiCA,SAAgB,YAAY,OAA4C;CACtE,OAAO,MAAM,sBAAsB,IAAI,KAAK,MAAM,sBAAsB,IAAI;AAC9E;;;;;;;;;;AAWA,SAAS,kBACP,cACA,YACA,MACmB;CACnB,IAAI,CAAC,gBAAgB,eAAe,KAAA,GAAW,OAAO;CACtD,MAAM,WAAW,cAAc,cAAc,UAAU;CACvD,IAAI,UAAU,OAAO;CACrB,KAAK,MAAM,SAAS,gBAAgB,cAAc,IAAI,GAAG;EACvD,MAAM,SAAS,cAAc,cAAc,MAAM,EAAE;EACnD,IAAI,QAAQ,OAAO;CACrB;CACA,OAAO;AACT;AAEA,SAAgB,oBAAoB,OAA2C;CAC7E,MAAM,eAAe,MAAM,aAAa,IAAI;CAC5C,MAAM,QAAQ,kBAAkB,cAAc,MAAM,sBAAsB,IAAI,GAAG,OAAO;CACxF,MAAM,QAAQ,kBAAkB,cAAc,MAAM,sBAAsB,IAAI,GAAG,OAAO;CACxF,IAAI,SAAS,OAAO;EAClB,MAAM,QAAQ,KAAK,IAAI,MAAM,OAAO,MAAM,KAAK;EAC/C,MAAM,MAAM,KAAK,IAAI,MAAM,KAAK,MAAM,GAAG;EAIzC,OAAO,QAAQ,MAAM;GAAE;GAAO;EAAI,IAAI;CACxC;CACA,OAAO,SAAS;AAClB;;;;;;;;;;AA4BA,SAAgB,YAAY,EAC1B,OAEA,UAIkB;CAClB,MAAM,SAAS,oBAAoB,KAAK;CACxC,IAAI,CAAC,QAAQ,OAAO;CACpB,MAAM,UAAU,QAAQ,qBAAqB,MAAM,aAAa,IAAI,GAAG,YAAY,KAAK,CAAC,KAAK;CAC9F,OAAO;EAAE,GAAG;EAAQ,eAAe,KAAK,IAAI,OAAO,OAAO,OAAO,MAAM,OAAO;CAAE;AAClF"}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
import { getMediaPlaylistMetadata } from "../../media/types/index.js";
|
|
2
|
+
import { SVTA_UNSUPPORTED_AUDIO_FORMAT, SVTA_UNSUPPORTED_DRM_SYSTEM, SVTA_UNSUPPORTED_VIDEO_FORMAT } from "../../media/errors.js";
|
|
3
|
+
import { NON_FMP4_CONTAINER_MIMES } from "../../media/hls/parse-media-playlist.js";
|
|
4
|
+
//#region src/playback/primitives/report-track-conditions.ts
|
|
5
|
+
/**
|
|
6
|
+
* The seam `resolve-track` uses to report conditions discovered in a freshly
|
|
7
|
+
* parsed media playlist.
|
|
8
|
+
*
|
|
9
|
+
* Injected rather than baked in so `resolve-track` stays free of format and
|
|
10
|
+
* policy knowledge: it parses and commits, and whatever the composition wants
|
|
11
|
+
* noticed about the result is this function's business. Which conditions matter,
|
|
12
|
+
* and which codes they carry, therefore vary per composition — a provider that
|
|
13
|
+
* never ships MPEG-TS can drop that check, and future playlist-derived notices
|
|
14
|
+
* (LL-HLS or DVR support that's partial rather than absent) attach here without
|
|
15
|
+
* touching the resolver.
|
|
16
|
+
*
|
|
17
|
+
* Reported **per rendition, as it resolves**, which is why these are causes and
|
|
18
|
+
* not verdicts: one rendition being unplayable doesn't make the source
|
|
19
|
+
* unplayable. The verdict is `track-switching`'s, which reports
|
|
20
|
+
* `SVTA_NO_SUPPORTED_{VIDEO,AUDIO}_TRACK` when a type's candidates actually
|
|
21
|
+
* empty. Keeping the two apart is what lets a mixed source — some renditions
|
|
22
|
+
* encrypted or MPEG-TS, others playable — log its causes and still play.
|
|
23
|
+
*/
|
|
24
|
+
/** Unsupported-format code per type; text has none — absent captions aren't a failure. */
|
|
25
|
+
const UNSUPPORTED_FORMAT_CODE = {
|
|
26
|
+
video: SVTA_UNSUPPORTED_VIDEO_FORMAT,
|
|
27
|
+
audio: SVTA_UNSUPPORTED_AUDIO_FORMAT
|
|
28
|
+
};
|
|
29
|
+
/**
|
|
30
|
+
* The types a reported cause can legitimately describe: the ones whose candidates
|
|
31
|
+
* `canPlayTrack` actually prunes, via `track-switching`'s `excludeUnplayableTracks`
|
|
32
|
+
* pre-pass.
|
|
33
|
+
*
|
|
34
|
+
* Text is outside it by design — its switching chain runs failed-CDN constraints
|
|
35
|
+
* alone, because an MSE codec probe is the wrong question for a WebVTT rendition
|
|
36
|
+
* (see `track-switching.ts`). So nothing prunes a text rendition, no verdict can
|
|
37
|
+
* follow from one, and a cause reported against it would be an orphan: the
|
|
38
|
+
* adapter's unsupported-feature substitution scans the sequence as a whole, so a
|
|
39
|
+
* lone encrypted subtitle would otherwise recode an unrelated verdict — an
|
|
40
|
+
* all-CDN cooldown among them — as "this engine can't play the source".
|
|
41
|
+
*/
|
|
42
|
+
const CAPABILITY_PRUNED_TYPES = /* @__PURE__ */ new Set(["video", "audio"]);
|
|
43
|
+
/**
|
|
44
|
+
* The default: report what makes a rendition unplayable *to this engine* — a
|
|
45
|
+
* container MSE can't accept, or encryption with no decryption pipeline. Both
|
|
46
|
+
* mirror what `canPlayTrack` prunes on, so a reported cause always has a
|
|
47
|
+
* corresponding exclusion.
|
|
48
|
+
*
|
|
49
|
+
* A condition carries its code and its context, not copy. `data.mimeType` is
|
|
50
|
+
* what preserves the specificity — the format codes cover every non-fMP4
|
|
51
|
+
* container, so "which one" lives there for a consumer that wants to say, rather
|
|
52
|
+
* than being flattened into an English sentence here.
|
|
53
|
+
*
|
|
54
|
+
* Both carry `trackType`, redundantly for the format codes (1004/1005 are
|
|
55
|
+
* already per type) but not for 4008, which isn't per type — SVTA has one
|
|
56
|
+
* content-protection code for both. Nothing branches on the tag: it's diagnostic
|
|
57
|
+
* context, reaching a developer through the logged sequence and `error.data`,
|
|
58
|
+
* which is why it goes on every condition rather than only where the code can't
|
|
59
|
+
* carry it. `trackId` alongside it is what distinguishes two renditions of the
|
|
60
|
+
* same type.
|
|
61
|
+
*/
|
|
62
|
+
function reportUnsupportedTrackConditions(track) {
|
|
63
|
+
if (!CAPABILITY_PRUNED_TYPES.has(track.type)) return [];
|
|
64
|
+
const conditions = [];
|
|
65
|
+
const data = {
|
|
66
|
+
trackType: track.type,
|
|
67
|
+
trackId: track.id
|
|
68
|
+
};
|
|
69
|
+
const formatCode = UNSUPPORTED_FORMAT_CODE[track.type];
|
|
70
|
+
if (formatCode !== void 0 && NON_FMP4_CONTAINER_MIMES.has(track.mimeType)) conditions.push({
|
|
71
|
+
code: formatCode,
|
|
72
|
+
data: {
|
|
73
|
+
...data,
|
|
74
|
+
mimeType: track.mimeType
|
|
75
|
+
}
|
|
76
|
+
});
|
|
77
|
+
if (getMediaPlaylistMetadata(track)?.encrypted) conditions.push({
|
|
78
|
+
code: SVTA_UNSUPPORTED_DRM_SYSTEM,
|
|
79
|
+
data
|
|
80
|
+
});
|
|
81
|
+
return conditions;
|
|
82
|
+
}
|
|
83
|
+
//#endregion
|
|
84
|
+
export { reportUnsupportedTrackConditions };
|
|
85
|
+
|
|
86
|
+
//# sourceMappingURL=report-track-conditions.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"report-track-conditions.js","names":[],"sources":["../../../../src/playback/primitives/report-track-conditions.ts"],"sourcesContent":["/**\n * The seam `resolve-track` uses to report conditions discovered in a freshly\n * parsed media playlist.\n *\n * Injected rather than baked in so `resolve-track` stays free of format and\n * policy knowledge: it parses and commits, and whatever the composition wants\n * noticed about the result is this function's business. Which conditions matter,\n * and which codes they carry, therefore vary per composition — a provider that\n * never ships MPEG-TS can drop that check, and future playlist-derived notices\n * (LL-HLS or DVR support that's partial rather than absent) attach here without\n * touching the resolver.\n *\n * Reported **per rendition, as it resolves**, which is why these are causes and\n * not verdicts: one rendition being unplayable doesn't make the source\n * unplayable. The verdict is `track-switching`'s, which reports\n * `SVTA_NO_SUPPORTED_{VIDEO,AUDIO}_TRACK` when a type's candidates actually\n * empty. Keeping the two apart is what lets a mixed source — some renditions\n * encrypted or MPEG-TS, others playable — log its causes and still play.\n */\nimport {\n SVTA_UNSUPPORTED_AUDIO_FORMAT,\n SVTA_UNSUPPORTED_DRM_SYSTEM,\n SVTA_UNSUPPORTED_VIDEO_FORMAT,\n type SvtaError,\n} from '../../media/errors';\nimport { NON_FMP4_CONTAINER_MIMES } from '../../media/hls/parse-media-playlist';\nimport { getMediaPlaylistMetadata, type ResolvedTrack, type TrackType } from '../../media/types';\n\n/**\n * Conditions worth reporting about a just-resolved track. Return an empty array\n * (or omit the seam) to report nothing.\n */\nexport type ReportUnsupportedTrackConditions = (track: ResolvedTrack) => readonly SvtaError[];\n\n/** Unsupported-format code per type; text has none — absent captions aren't a failure. */\nconst UNSUPPORTED_FORMAT_CODE: Partial<Record<TrackType, number>> = {\n video: SVTA_UNSUPPORTED_VIDEO_FORMAT,\n audio: SVTA_UNSUPPORTED_AUDIO_FORMAT,\n};\n\n/**\n * The types a reported cause can legitimately describe: the ones whose candidates\n * `canPlayTrack` actually prunes, via `track-switching`'s `excludeUnplayableTracks`\n * pre-pass.\n *\n * Text is outside it by design — its switching chain runs failed-CDN constraints\n * alone, because an MSE codec probe is the wrong question for a WebVTT rendition\n * (see `track-switching.ts`). So nothing prunes a text rendition, no verdict can\n * follow from one, and a cause reported against it would be an orphan: the\n * adapter's unsupported-feature substitution scans the sequence as a whole, so a\n * lone encrypted subtitle would otherwise recode an unrelated verdict — an\n * all-CDN cooldown among them — as \"this engine can't play the source\".\n */\nconst CAPABILITY_PRUNED_TYPES: ReadonlySet<TrackType> = new Set<TrackType>(['video', 'audio']);\n\n/**\n * The default: report what makes a rendition unplayable *to this engine* — a\n * container MSE can't accept, or encryption with no decryption pipeline. Both\n * mirror what `canPlayTrack` prunes on, so a reported cause always has a\n * corresponding exclusion.\n *\n * A condition carries its code and its context, not copy. `data.mimeType` is\n * what preserves the specificity — the format codes cover every non-fMP4\n * container, so \"which one\" lives there for a consumer that wants to say, rather\n * than being flattened into an English sentence here.\n *\n * Both carry `trackType`, redundantly for the format codes (1004/1005 are\n * already per type) but not for 4008, which isn't per type — SVTA has one\n * content-protection code for both. Nothing branches on the tag: it's diagnostic\n * context, reaching a developer through the logged sequence and `error.data`,\n * which is why it goes on every condition rather than only where the code can't\n * carry it. `trackId` alongside it is what distinguishes two renditions of the\n * same type.\n */\nexport function reportUnsupportedTrackConditions(track: ResolvedTrack): readonly SvtaError[] {\n if (!CAPABILITY_PRUNED_TYPES.has(track.type)) return [];\n\n const conditions: SvtaError[] = [];\n const data = { trackType: track.type, trackId: track.id };\n\n const formatCode = UNSUPPORTED_FORMAT_CODE[track.type];\n if (formatCode !== undefined && NON_FMP4_CONTAINER_MIMES.has(track.mimeType)) {\n conditions.push({ code: formatCode, data: { ...data, mimeType: track.mimeType } });\n }\n if (getMediaPlaylistMetadata(track)?.encrypted) {\n conditions.push({ code: SVTA_UNSUPPORTED_DRM_SYSTEM, data });\n }\n return conditions;\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,0BAA8D;CAClE,OAAO;CACP,OAAO;AACT;;;;;;;;;;;;;;AAeA,MAAM,0CAAkD,IAAI,IAAe,CAAC,SAAS,OAAO,CAAC;;;;;;;;;;;;;;;;;;;;AAqB7F,SAAgB,iCAAiC,OAA4C;CAC3F,IAAI,CAAC,wBAAwB,IAAI,MAAM,IAAI,GAAG,OAAO,CAAC;CAEtD,MAAM,aAA0B,CAAC;CACjC,MAAM,OAAO;EAAE,WAAW,MAAM;EAAM,SAAS,MAAM;CAAG;CAExD,MAAM,aAAa,wBAAwB,MAAM;CACjD,IAAI,eAAe,KAAA,KAAa,yBAAyB,IAAI,MAAM,QAAQ,GACzE,WAAW,KAAK;EAAE,MAAM;EAAY,MAAM;GAAE,GAAG;GAAM,UAAU,MAAM;EAAS;CAAE,CAAC;CAEnF,IAAI,yBAAyB,KAAK,CAAC,EAAE,WACnC,WAAW,KAAK;EAAE,MAAM;EAA6B;CAAK,CAAC;CAE7D,OAAO;AACT"}
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
import { effect } from "./effect.js";
|
|
2
|
+
//#region src/core/signals/when.ts
|
|
3
|
+
/**
|
|
4
|
+
* Resolve once `condition` returns true. The condition is a tracked read — it
|
|
5
|
+
* re-evaluates whenever a signal it read changes — so this is the promise
|
|
6
|
+
* bridge from signal space into async task bodies (await a state condition
|
|
7
|
+
* mid-task without polling).
|
|
8
|
+
*
|
|
9
|
+
* Settles synchronously when the condition already holds. Rejects with the
|
|
10
|
+
* abort reason when `signal` aborts first (an already-aborted signal rejects
|
|
11
|
+
* without evaluating the condition), so a task awaiting a condition dies with
|
|
12
|
+
* its runner instead of leaking the subscription.
|
|
13
|
+
*/
|
|
14
|
+
function when(condition, options = {}) {
|
|
15
|
+
const { signal } = options;
|
|
16
|
+
if (signal?.aborted) return Promise.reject(signal.reason);
|
|
17
|
+
return new Promise((resolve, reject) => {
|
|
18
|
+
let settled = false;
|
|
19
|
+
const settle = (complete) => {
|
|
20
|
+
if (settled) return;
|
|
21
|
+
settled = true;
|
|
22
|
+
complete();
|
|
23
|
+
queueMicrotask(() => {
|
|
24
|
+
signal?.removeEventListener("abort", onAbort);
|
|
25
|
+
stop();
|
|
26
|
+
});
|
|
27
|
+
};
|
|
28
|
+
const onAbort = () => settle(() => reject(signal?.reason));
|
|
29
|
+
signal?.addEventListener("abort", onAbort, { once: true });
|
|
30
|
+
const stop = effect(() => {
|
|
31
|
+
if (!settled && condition()) settle(resolve);
|
|
32
|
+
});
|
|
33
|
+
});
|
|
34
|
+
}
|
|
35
|
+
//#endregion
|
|
36
|
+
export { when };
|
|
37
|
+
|
|
38
|
+
//# sourceMappingURL=when.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"when.js","names":[],"sources":["../../../../src/core/signals/when.ts"],"sourcesContent":["import { effect } from './effect';\n\n/**\n * Resolve once `condition` returns true. The condition is a tracked read — it\n * re-evaluates whenever a signal it read changes — so this is the promise\n * bridge from signal space into async task bodies (await a state condition\n * mid-task without polling).\n *\n * Settles synchronously when the condition already holds. Rejects with the\n * abort reason when `signal` aborts first (an already-aborted signal rejects\n * without evaluating the condition), so a task awaiting a condition dies with\n * its runner instead of leaking the subscription.\n */\nexport function when(condition: () => boolean, options: { signal?: AbortSignal } = {}): Promise<void> {\n const { signal } = options;\n if (signal?.aborted) return Promise.reject(signal.reason);\n\n return new Promise<void>((resolve, reject) => {\n let settled = false;\n const settle = (complete: () => void) => {\n if (settled) return;\n settled = true;\n complete();\n // Deferred: on the effect's synchronous initial run `stop` isn't\n // assigned yet, and stopping an effect from inside its own body is\n // undefined behavior for the scheduler either way.\n queueMicrotask(() => {\n signal?.removeEventListener('abort', onAbort);\n stop();\n });\n };\n const onAbort = () => settle(() => reject(signal?.reason));\n signal?.addEventListener('abort', onAbort, { once: true });\n const stop = effect(() => {\n if (!settled && condition()) settle(resolve);\n });\n });\n}\n"],"mappings":";;;;;;;;;;;;;AAaA,SAAgB,KAAK,WAA0B,UAAoC,CAAC,GAAkB;CACpG,MAAM,EAAE,WAAW;CACnB,IAAI,QAAQ,SAAS,OAAO,QAAQ,OAAO,OAAO,MAAM;CAExD,OAAO,IAAI,SAAe,SAAS,WAAW;EAC5C,IAAI,UAAU;EACd,MAAM,UAAU,aAAyB;GACvC,IAAI,SAAS;GACb,UAAU;GACV,SAAS;GAIT,qBAAqB;IACnB,QAAQ,oBAAoB,SAAS,OAAO;IAC5C,KAAK;GACP,CAAC;EACH;EACA,MAAM,gBAAgB,aAAa,OAAO,QAAQ,MAAM,CAAC;EACzD,QAAQ,iBAAiB,SAAS,SAAS,EAAE,MAAM,KAAK,CAAC;EACzD,MAAM,OAAO,aAAa;GACxB,IAAI,CAAC,WAAW,UAAU,GAAG,OAAO,OAAO;EAC7C,CAAC;CACH,CAAC;AACH"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { sleep } from "@videojs/utils/time";
|
|
2
|
+
//#region src/core/tasks/delayed-reschedule.ts
|
|
3
|
+
/**
|
|
4
|
+
* Build a {@link Reschedule} from a pure cadence function — the common
|
|
5
|
+
* timer-based, *start-anchored* implementation.
|
|
6
|
+
*
|
|
7
|
+
* Invoked concurrently with the run, it observes the result, then waits
|
|
8
|
+
* `cadence(current, previous)` milliseconds **measured from when it was invoked**
|
|
9
|
+
* (≈ the run's start): it subtracts the run's own elapsed time, so consecutive
|
|
10
|
+
* runs begin one cadence apart regardless of how long each run takes (per
|
|
11
|
+
* RFC 8216 §6.3.4's "measured from the last time the client began loading"). If
|
|
12
|
+
* the run takes longer than the cadence, the next run starts immediately.
|
|
13
|
+
*
|
|
14
|
+
* A `null` cadence stops the recurrence. A rejected run rejects this reschedule,
|
|
15
|
+
* which the `RecurringRunner` propagates as the recurrence's failure — error
|
|
16
|
+
* recovery (e.g. retrying transient fetch failures) belongs below, at the fetch
|
|
17
|
+
* layer, not in the cadence.
|
|
18
|
+
*/
|
|
19
|
+
function delayedReschedule(cadence) {
|
|
20
|
+
return async (task) => {
|
|
21
|
+
const startedAt = Date.now();
|
|
22
|
+
const ms = cadence(await task.run(), task.previous);
|
|
23
|
+
if (ms === null) return false;
|
|
24
|
+
await sleep(Math.max(0, ms - (Date.now() - startedAt)), task.signal);
|
|
25
|
+
return true;
|
|
26
|
+
};
|
|
27
|
+
}
|
|
28
|
+
//#endregion
|
|
29
|
+
export { delayedReschedule };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=delayed-reschedule.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"delayed-reschedule.js","names":[],"sources":["../../../../src/core/tasks/delayed-reschedule.ts"],"sourcesContent":["import { sleep } from '@videojs/utils/time';\nimport type { Reschedule } from './task';\n\n/**\n * Build a {@link Reschedule} from a pure cadence function — the common\n * timer-based, *start-anchored* implementation.\n *\n * Invoked concurrently with the run, it observes the result, then waits\n * `cadence(current, previous)` milliseconds **measured from when it was invoked**\n * (≈ the run's start): it subtracts the run's own elapsed time, so consecutive\n * runs begin one cadence apart regardless of how long each run takes (per\n * RFC 8216 §6.3.4's \"measured from the last time the client began loading\"). If\n * the run takes longer than the cadence, the next run starts immediately.\n *\n * A `null` cadence stops the recurrence. A rejected run rejects this reschedule,\n * which the `RecurringRunner` propagates as the recurrence's failure — error\n * recovery (e.g. retrying transient fetch failures) belongs below, at the fetch\n * layer, not in the cadence.\n */\nexport function delayedReschedule<TValue>(\n cadence: (current: TValue, previous: TValue | undefined) => number | null\n): Reschedule<TValue> {\n return async (task) => {\n const startedAt = Date.now();\n const current = await task.run();\n // `task.previous` is the prior successful value (carried by the runner's\n // clone); read-only for the cadence, hence the cast off `DeepReadonly`.\n const ms = cadence(current, task.previous as TValue | undefined);\n if (ms === null) return false;\n await sleep(Math.max(0, ms - (Date.now() - startedAt)), task.signal);\n return true;\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;AAmBA,SAAgB,kBACd,SACoB;CACpB,OAAO,OAAO,SAAS;EACrB,MAAM,YAAY,KAAK,IAAI;EAI3B,MAAM,KAAK,QAAQ,MAHG,KAAK,IAAI,GAGH,KAAK,QAA8B;EAC/D,IAAI,OAAO,MAAM,OAAO;EACxB,MAAM,MAAM,KAAK,IAAI,GAAG,MAAM,KAAK,IAAI,IAAI,UAAU,GAAG,KAAK,MAAM;EACnE,OAAO;CACT;AACF"}
|