@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
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"resolve-track.js","names":["defaultFetchResolvableText","fetchResolvableText"],"sources":["../../../../src/playback/behaviors/resolve-track.ts"],"sourcesContent":["import { defineBehavior } from '../../core/composition/create-composition';\nimport { createMachineReactor } from '../../core/reactors/create-machine-reactor';\nimport { computed, peek, type ReadonlySignal, type Signal, update } from '../../core/signals/primitives';\nimport { ConcurrentRunner, Task } from '../../core/tasks/task';\nimport { NON_FMP4_CONTAINER_MIMES, parseMediaPlaylist } from '../../media/hls/parse-media-playlist';\nimport type { MaybeResolvedPresentation, PartiallyResolvedTrack, ResolvedTrack } from '../../media/types';\nimport { isResolvedPresentation, isResolvedTrack } from '../../media/types';\nimport type { GetCdnId } from '../../media/utils/cdn';\nimport { applyContainerMimeType, findTrack, updateTrackInPresentation } from '../../media/utils/tracks';\nimport { fetchResolvableText as defaultFetchResolvableText, type FetchText } from '../../network/fetch';\nimport { failoverFetch } from '../primitives/failover-fetch';\nimport { AUDIO_TYPE_CONFIG, TEXT_TYPE_CONFIG, VIDEO_TYPE_CONFIG } from '../primitives/track-types';\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackResolution` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => cleanup`. Each `resolveXTrack` export below calls it\n// from inside its own `defineBehavior` setup, supplying its per-type config\n// inline. The orchestration — gate on a selection, short-circuit when the\n// track is already resolved or missing, schedule the fetch+parse, and patch\n// the resolved track back into `state.presentation` — is shared.\n// ============================================================================\n\n/**\n * State shape for track resolution. Uses `MaybeResolvedPresentation` so it\n * matches the engine's slot type; resolution narrows internally.\n */\nexport interface ResolveTrackState {\n presentation?: MaybeResolvedPresentation;\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n failedCdns?: string[];\n}\n\ntype SelectedTrackKey = 'selectedVideoTrackId' | 'selectedAudioTrackId' | 'selectedTextTrackId';\n\ntype ResolveTrackStateMap<K extends SelectedTrackKey> = {\n presentation: Signal<ResolveTrackState['presentation']>;\n} & { [P in K]: ReadonlySignal<ResolveTrackState[P]> };\n\ninterface TrackResolutionConfig<K extends SelectedTrackKey> {\n selectedKey: K;\n findTrackToResolve: (\n presentation: MaybeResolvedPresentation,\n trackId: string\n ) => PartiallyResolvedTrack | ResolvedTrack | undefined;\n /** Fetch a track's media-playlist text — already failover-decorated by the behavior. */\n fetchResolvableText?: FetchText;\n}\n\n/**\n * Engine-config slice each `resolve*` behavior reads to build its failover-\n * decorated playlist fetch.\n */\ninterface ResolveTrackConfig {\n /** CDN-id derivation for the failover trip; defaults to origin-based `getCdnId`. */\n getCdnId?: GetCdnId;\n}\n\nfunction setupTrackResolution<K extends SelectedTrackKey>({\n state,\n config: { selectedKey, findTrackToResolve, fetchResolvableText = defaultFetchResolvableText },\n}: {\n state: ResolveTrackStateMap<K>;\n config: TrackResolutionConfig<K>;\n}) {\n // NOTE: This can/maybe will be pulled into a per-use case factory (e.g. something like createTaskRunner() with args TBD),\n // likely eventually passed down via config or a new \"definitions\" argument. This will allow us to decide if we want our task runner/scheduler\n // to e.g. run concurrently (like we currently are), serially with a queue, or abort the previous task and replace it with the newly scheduled one. (CJP).\n const runner = new ConcurrentRunner();\n\n // Reactor states model the FSM the previous effect-based body was\n // hand-rolling. 'presentation-resolved' is entered when the\n // presentation is fully parsed (has a Ham id + selectionSets); leaving\n // it (presentation cleared or reset to an unresolved value) aborts all\n // in-flight tasks via the entry-cleanup. Most URL changes go through\n // 'presentation-unresolved' naturally (set undefined → set new partial\n // → re-parse), so the common case is covered by state-exit alone; the\n // task body's commit-time id check covers the pathological\n // resolved→resolved-without-unresolved transition.\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // `entry` runs on state entry; the function it returns is the\n // state-exit cleanup. Returning `() => runner.abortAll()` binds\n // abort-of-in-flight-resolutions to leaving 'presentation-resolved'\n // (presentation cleared/reset, or behavior destroyed) —\n // source-change cancellation expressed structurally through the\n // state machine.\n entry: () => () => runner.abortAll(),\n effects: [\n () => {\n // The reactor's state transitions handle relevant presentation\n // changes (presentation-resolved ↔ presentation-unresolved);\n // within 'presentation-resolved' we peek (untracked read) so\n // internal updates (segments added by sibling tasks) don't\n // re-fire the effect.\n const presentation = peek(state.presentation);\n const trackId = state[selectedKey].get();\n if (!presentation || !trackId) return;\n\n const track = findTrackToResolve(presentation, trackId);\n if (!track || isResolvedTrack(track)) return;\n\n runner.schedule(\n // NOTE: This can/maybe will be pulled into a per-use case factory (e.g. something like createResolveTrackTask(track, context, config)),\n // likely eventually passed down via config or a new \"definitions\" argument (CJP).\n new Task(\n async (signal) => {\n // `fetchResolvableText` is the behavior's failover-decorated\n // fetch: it trips the CDN on a failed fetch (network error or\n // non-OK status). A parse failure is a content issue, not a\n // CDN-availability one, so it doesn't trip.\n const text = await fetchResolvableText(track, { signal });\n const mediaTrack = parseMediaPlaylist(text, track);\n\n // Updater handles undefined inputs by returning current\n // unchanged; isResolvedPresentation narrows for the patch.\n // State-exit on resolving→unresolved fires runner.abortAll\n // before any URL change settles, and per the Fetch spec the\n // signal abort cancels in-flight body reads — so by the\n // time we reach this point the presentation we resolved\n // against is the live one.\n update(state.presentation, (current) => {\n if (!isResolvedPresentation(current)) return current;\n const patched = updateTrackInPresentation(current, mediaTrack);\n // Container is uniform within a type (an ABR ladder shares\n // its container), so a detected non-fMP4 rendition (TS,\n // raw AAC) implies every rendition of *this* type matches —\n // relabel them all from one resolved playlist instead of\n // fetching each. Scoped to this track's own type: never cross\n // audio↔video (mixed-container sources exist, e.g. muxed-TS\n // video + raw-.aac audio), which also keeps per-type\n // resolutions' writes disjoint (no race).\n return NON_FMP4_CONTAINER_MIMES.has(mediaTrack.mimeType)\n ? applyContainerMimeType(patched, mediaTrack.type, mediaTrack.mimeType)\n : patched;\n });\n },\n { id: track.id }\n )\n );\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Per-helper-per-type configs — defaults that variants spread engine config over\n// ============================================================================\n\nconst VIDEO_TRACK_RESOLUTION_CONFIG = {\n ...VIDEO_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'video', trackId),\n} as const;\n\nconst AUDIO_TRACK_RESOLUTION_CONFIG = {\n ...AUDIO_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'audio', trackId),\n} as const;\n\nconst TEXT_TRACK_RESOLUTION_CONFIG = {\n ...TEXT_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'text', trackId),\n} as const;\n\n// ============================================================================\n// Specialized exports — one per track type\n// ============================================================================\n\n/**\n * Resolve unresolved video tracks. Schedules a fetch task whenever the\n * selected video track is partially resolved, parses the manifest, and\n * writes the resolved track back into `state.presentation`.\n */\nexport const resolveVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedVideoTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Engine `config` layers over the per-type defaults (mirrors the other\n // per-type variants, see track-types.ts); `failoverFetch` reads its\n // `selectedKey` + `getCdnId` from the merged result. `fetchResolvableText`\n // is then placed AFTER the spread so the failover-decorated fetch wins —\n // unlike segments, playlists expose no overridable per-type fetch.\n const trackConfig = { ...VIDEO_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n\n/**\n * Resolve unresolved audio tracks. Same shape as `resolveVideoTrack`,\n * narrowed to audio.\n */\nexport const resolveAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedAudioTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Key order is load-bearing — see resolveVideoTrack.\n const trackConfig = { ...AUDIO_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n\n/**\n * Resolve unresolved text tracks. Same shape as `resolveVideoTrack`,\n * narrowed to text.\n */\nexport const resolveTextTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedTextTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedTextTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Key order is load-bearing — see resolveVideoTrack.\n const trackConfig = { ...TEXT_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n"],"mappings":";;;;;;;;;;;AA6DA,SAAS,qBAAiD,EACxD,OACA,QAAQ,EAAE,aAAa,oBAAoB,qBAAA,wBAAsBA,yBAIhE;CAID,MAAM,SAAS,IAAI,iBAAiB;CAWpC,MAAM,qBAAqB,eACzB,uBAAuB,MAAM,aAAa,IAAI,CAAC,IAC1C,0BACA,yBACP;CAEA,OAAO,qBAAqB;EAC1B,SAAS;EACT,eAAe,mBAAmB,IAAI;EACtC,QAAQ;GACN,2BAA2B,CAAC;GAC5B,yBAAyB;IAOvB,mBAAmB,OAAO,SAAS;IACnC,SAAS,OACD;KAMJ,MAAM,eAAe,KAAK,MAAM,YAAY;KAC5C,MAAM,UAAU,MAAM,YAAY,CAAC,IAAI;KACvC,IAAI,CAAC,gBAAgB,CAAC,SAAS;KAE/B,MAAM,QAAQ,mBAAmB,cAAc,OAAO;KACtD,IAAI,CAAC,SAAS,gBAAgB,KAAK,GAAG;KAEtC,OAAO,SAGL,IAAI,KACF,OAAO,WAAW;MAMhB,MAAM,aAAa,mBAAmB,MADnBC,sBAAoB,OAAO,EAAE,OAAO,CAAC,GACZ,KAAK;MASjD,OAAO,MAAM,eAAe,YAAY;OACtC,IAAI,CAAC,uBAAuB,OAAO,GAAG,OAAO;OAC7C,MAAM,UAAU,0BAA0B,SAAS,UAAU;OAS7D,OAAO,yBAAyB,IAAI,WAAW,QAAQ,IACnD,uBAAuB,SAAS,WAAW,MAAM,WAAW,QAAQ,IACpE;MACN,CAAC;KACH,GACA,EAAE,IAAI,MAAM,GAAG,CACjB,CACF;IACF,CACF;GACF;EACF;CACF,CAAC;AACH;AAMA,MAAM,gCAAgC;CACpC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,SAAS,OAAO;AAC5C;AAEA,MAAM,gCAAgC;CACpC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,SAAS,OAAO;AAC5C;AAEA,MAAM,+BAA+B;CACnC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,QAAQ,OAAO;AAC3C;;;;;;AAWA,MAAa,oBAAoB,eAAe;CAC9C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAMJ,MAAM,cAAc;GAAE,GAAG;GAA+B,GAAG;EAAO;EAClE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcD,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC;;;;;AAMD,MAAa,oBAAoB,eAAe;CAC9C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAEJ,MAAM,cAAc;GAAE,GAAG;GAA+B,GAAG;EAAO;EAClE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcA,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC;;;;;AAMD,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,qBAAqB;CACjD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAEJ,MAAM,cAAc;GAAE,GAAG;GAA8B,GAAG;EAAO;EACjE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcA,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC"}
|
|
1
|
+
{"version":3,"file":"resolve-track.js","names":["defaultFetchResolvableText","fetchResolvableText"],"sources":["../../../../src/playback/behaviors/resolve-track.ts"],"sourcesContent":["import { defineBehavior } from '../../core/composition/create-composition';\nimport { createMachineReactor } from '../../core/reactors/create-machine-reactor';\nimport { computed, peek, type ReadonlySignal, type Signal, update } from '../../core/signals/primitives';\nimport { when } from '../../core/signals/when';\nimport { RecurringRunner, type Reschedule, runOnce, Task } from '../../core/tasks/task';\nimport { NON_FMP4_CONTAINER_MIMES, parseMediaPlaylist } from '../../media/hls/parse-media-playlist';\nimport type { MaybeResolvedPresentation, PartiallyResolvedTrack, ResolvedTrack } from '../../media/types';\nimport { deriveStreamType, getMediaPlaylistMetadata, isResolvedPresentation, isResolvedTrack } from '../../media/types';\nimport type { GetCdnId } from '../../media/utils/cdn';\nimport { applyContainerMimeType, findTrack, updateTrackInPresentation } from '../../media/utils/tracks';\nimport { fetchResolvableText as defaultFetchResolvableText, type FetchText } from '../../network/fetch';\nimport { failoverFetch } from '../primitives/failover-fetch';\nimport type { GateFirstParse } from '../primitives/gate-first-parse';\nimport type { ReportUnsupportedTrackConditions } from '../primitives/report-track-conditions';\nimport { AUDIO_TYPE_CONFIG, TEXT_TYPE_CONFIG, VIDEO_TYPE_CONFIG } from '../primitives/track-types';\nimport { type ErrorEmitterState, emitError } from './collect-errors';\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackResolution` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => cleanup`. Each `resolveXTrack` export below calls it\n// from inside its own `defineBehavior` setup, supplying its per-type config\n// inline. The orchestration — gate on a selection, short-circuit when the\n// track is already resolved or missing, schedule the fetch+parse, and patch\n// the resolved track back into `state.presentation` — is shared.\n// ============================================================================\n\n/**\n * State shape for track resolution. Uses `MaybeResolvedPresentation` so it\n * matches the engine's slot type; resolution narrows internally.\n */\nexport interface ResolveTrackState {\n presentation?: MaybeResolvedPresentation;\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n failedCdns?: string[];\n}\n\ntype SelectedTrackKey = 'selectedVideoTrackId' | 'selectedAudioTrackId' | 'selectedTextTrackId';\n\ntype ResolveTrackStateMap<K extends SelectedTrackKey> = {\n presentation: Signal<ResolveTrackState['presentation']>;\n} & { [P in K]: ReadonlySignal<ResolveTrackState[P]> };\n\n/**\n * Sibling-owned A/V selection signals, present at runtime iff a sibling\n * behavior owns them. Deliberately not in the typed slice / `stateKeys`\n * (declaring them would force every composition to carry both selections);\n * read only to build the injected first-parse gate's selection context.\n */\ntype SiblingSelectionSignals = {\n selectedVideoTrackId?: ReadonlySignal<ResolveTrackState['selectedVideoTrackId']>;\n selectedAudioTrackId?: ReadonlySignal<ResolveTrackState['selectedAudioTrackId']>;\n};\n\ninterface TrackResolutionConfig<K extends SelectedTrackKey> {\n selectedKey: K;\n findTrackToResolve: (\n presentation: MaybeResolvedPresentation,\n trackId: string\n ) => PartiallyResolvedTrack | ResolvedTrack | undefined;\n /** Fetch a track's media-playlist text — already failover-decorated by the behavior. */\n fetchResolvableText?: FetchText;\n /** Holds a track's first parse until its placement inputs settle (live anchor); absent → parse immediately. */\n gateFirstParse?: GateFirstParse;\n /** Live re-run policy for the `RecurringRunner`; absent → resolve once (VOD). */\n reschedule?: Reschedule<ResolvedTrack>;\n /**\n * Report conditions found in the parsed playlist (see\n * `primitives/report-track-conditions`); absent → report nothing.\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n}\n\n/**\n * Engine-config slice each `resolve*` behavior reads to build its failover-\n * decorated playlist fetch.\n */\ninterface ResolveTrackConfig {\n /** CDN-id derivation for the failover trip; defaults to origin-based `getCdnId`. */\n getCdnId?: GetCdnId;\n /** First-parse placement gate (see `primitives/gate-first-parse`); absent → parse immediately. */\n gateFirstParse?: GateFirstParse;\n /** Live media-playlist re-run policy; absent → resolve once. */\n reschedule?: Reschedule<ResolvedTrack>;\n /** Playlist-derived condition reporting (see `primitives/report-track-conditions`). */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n}\n\nfunction setupTrackResolution<K extends SelectedTrackKey>({\n state,\n config: {\n selectedKey,\n findTrackToResolve,\n fetchResolvableText = defaultFetchResolvableText,\n gateFirstParse,\n reschedule,\n reportUnsupportedTrackConditions,\n },\n}: {\n // Widened with the optional `errors` slot: reporting writes through it without\n // the behavior declaring ownership, and no-ops when `collectErrors` isn't\n // composed. Same contract as `failedCdns` / `failoverFetch`.\n state: ResolveTrackStateMap<K> & ErrorEmitterState;\n config: TrackResolutionConfig<K>;\n}) {\n // Recurrence lives in the runner: with a `reschedule` (live) it re-runs the\n // task until the policy stops; `runOnce` (VOD) runs it exactly once. Single-\n // slot — a selection change re-schedules (abort-and-replace).\n const runner = new RecurringRunner<ResolvedTrack>(reschedule ?? runOnce);\n\n // Reactor states model the FSM the previous effect-based body was\n // hand-rolling. 'presentation-resolved' is entered when the\n // presentation is fully parsed (has a Ham id + selectionSets); leaving\n // it (presentation cleared or reset to an unresolved value) aborts all\n // in-flight tasks via the entry-cleanup. Most URL changes go through\n // 'presentation-unresolved' naturally (set undefined → set new partial\n // → re-parse), so the common case is covered by state-exit alone; the\n // task body's commit-time id check covers the pathological\n // resolved→resolved-without-unresolved transition.\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // `entry` runs on state entry; the function it returns is the\n // state-exit cleanup. Returning `() => runner.abortAll()` binds\n // abort-of-in-flight-resolutions to leaving 'presentation-resolved'\n // (presentation cleared/reset, or behavior destroyed) —\n // source-change cancellation expressed structurally through the\n // state machine.\n entry: () => () => runner.abortAll(),\n effects: [\n () => {\n // The reactor's state transitions handle relevant presentation\n // changes (presentation-resolved ↔ presentation-unresolved);\n // within 'presentation-resolved' we peek (untracked read) so\n // internal updates (segments added by sibling tasks, or by this\n // behavior's own reload cycles) don't re-fire the effect.\n const presentation = peek(state.presentation);\n const trackId = state[selectedKey].get();\n if (!presentation || !trackId) return;\n\n const track = findTrackToResolve(presentation, trackId);\n // Skip a complete or missing track; a resolved-but-incomplete (live)\n // window still reloads — its window may have slid past the playhead.\n if (!track || (isResolvedTrack(track) && Number.isFinite(track.duration))) return;\n\n // Abort (selection/source change) settles quietly; a genuine resolve\n // failure rejects — swallowed for now (TODO: surface to state).\n const scheduled = runner.schedule(\n // NOTE: This can/maybe will be pulled into a per-use case factory (e.g. something like createResolveTrackTask(track, context, config)),\n // likely eventually passed down via config or a new \"definitions\" argument (CJP).\n //\n // Re-runs (clones) on each reload, so the body re-reads the live\n // snapshot (via `trackId`) rather than capturing the gate-time\n // `track` — a reload carries the prior window's timeline forward.\n new Task(\n async (signal) => {\n const snapshot = peek(state.presentation);\n const current = snapshot ? findTrackToResolve(snapshot, trackId) : undefined;\n if (!current) throw new Error('resolve-track: selected track not found');\n\n // `fetchResolvableText` is the behavior's failover-decorated\n // fetch: it trips the CDN on a failed fetch (network error or\n // non-OK status). A parse failure is a content issue, not a\n // CDN-availability one, so it doesn't trip. The run-time\n // `current` supplies only the playlist URL (stable across the\n // fetch).\n const text = await fetchResolvableText(current, { signal });\n\n // Hold placement — never the fetch — until this track's\n // first-parse placement inputs settle (for live, the\n // wall-clock anchor; see `primitives/gate-first-parse`).\n // First parses only — a reload's window is already on the\n // established timeline. Aborting rejects the wait, so a\n // source change can't strand a gated task.\n if (gateFirstParse && !isResolvedTrack(current)) {\n const { selectedVideoTrackId, selectedAudioTrackId } = state as SiblingSelectionSignals;\n await when(\n () =>\n gateFirstParse(\n state.presentation.get(),\n {\n selectedVideoTrackId: selectedVideoTrackId?.get(),\n selectedAudioTrackId: selectedAudioTrackId?.get(),\n },\n trackId\n ),\n { signal }\n );\n }\n\n // Re-read `previous` after the awaits: a concurrent write\n // during them — notably the establishment reactor stamping\n // the anchor `startDate` onto this track's shell — must feed\n // the parse, not be clobbered (anchoring is establish-once;\n // parsing the pre-fetch snapshot would strand the track off\n // the anchor for good). Correctness rests on a\n // run-to-completion invariant: NOTHING may yield (await)\n // between this re-read and the write below, so no writer can\n // interleave. `parseMediaPlaylist` is synchronous — keep it\n // that way, or move the read into the updater.\n const live = peek(state.presentation);\n const previous = live ? findTrackToResolve(live, trackId) : undefined;\n if (!previous) throw new Error('resolve-track: selected track not found');\n const mediaTrack = parseMediaPlaylist(text, previous);\n\n // Report what the parse revealed about this rendition, before\n // committing it. Causes only — one unplayable rendition doesn't\n // make the source unplayable, so the verdict stays with\n // track-switching's empty-candidate branch.\n if (reportUnsupportedTrackConditions) {\n for (const condition of reportUnsupportedTrackConditions(mediaTrack as ResolvedTrack)) {\n emitError(state, condition);\n }\n }\n\n // Updater handles undefined inputs by returning current\n // unchanged; isResolvedPresentation narrows for the patch.\n // State-exit on resolving→unresolved fires runner.abortAll\n // before any URL change settles, and per the Fetch spec the\n // signal abort cancels in-flight body reads — so by the\n // time we reach this point the presentation we resolved\n // against is the live one.\n update(state.presentation, (current) => {\n if (!isResolvedPresentation(current)) return current;\n const patched = updateTrackInPresentation(current, mediaTrack);\n // Container is uniform within a type (an ABR ladder shares\n // its container), so a detected non-fMP4 rendition (TS,\n // raw AAC) implies every rendition of *this* type matches —\n // relabel them all from one resolved playlist instead of\n // fetching each. Scoped to this track's own type: never cross\n // audio↔video (mixed-container sources exist, e.g. muxed-TS\n // video + raw-.aac audio), which also keeps per-type\n // resolutions' writes disjoint (no race).\n const relabeled = NON_FMP4_CONTAINER_MIMES.has(mediaTrack.mimeType)\n ? applyContainerMimeType(patched, mediaTrack.type, mediaTrack.mimeType)\n : patched;\n // Stream nature (live vs on-demand), rewritten from whichever\n // track just parsed — every type's resolve and every live\n // reload takes this path. Idempotent in practice rather than\n // by construction: `PLAYLIST-TYPE` is a per-source constant\n // that a source's renditions agree on, so each write lands\n // the same value. Renditions that disagreed would make the\n // winner resolve-order-dependent.\n return { ...relabeled, streamType: deriveStreamType(getMediaPlaylistMetadata(mediaTrack)) };\n });\n return mediaTrack;\n },\n { id: track.id }\n )\n );\n scheduled.catch(() => {});\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Per-helper-per-type configs — defaults that variants spread engine config over\n// ============================================================================\n\nconst VIDEO_TRACK_RESOLUTION_CONFIG = {\n ...VIDEO_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'video', trackId),\n} as const;\n\nconst AUDIO_TRACK_RESOLUTION_CONFIG = {\n ...AUDIO_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'audio', trackId),\n} as const;\n\nconst TEXT_TRACK_RESOLUTION_CONFIG = {\n ...TEXT_TYPE_CONFIG,\n findTrackToResolve: (presentation: MaybeResolvedPresentation, trackId: string) =>\n findTrack(presentation, 'text', trackId),\n} as const;\n\n// ============================================================================\n// Specialized exports — one per track type\n// ============================================================================\n\n/**\n * Resolve unresolved video tracks. Schedules a fetch task whenever the\n * selected video track is partially resolved, parses the manifest, and\n * writes the resolved track back into `state.presentation`.\n */\nexport const resolveVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedVideoTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Engine `config` layers over the per-type defaults (mirrors the other\n // per-type variants, see track-types.ts); `failoverFetch` reads its\n // `selectedKey` + `getCdnId` from the merged result. `fetchResolvableText`\n // is then placed AFTER the spread so the failover-decorated fetch wins —\n // unlike segments, playlists expose no overridable per-type fetch.\n const trackConfig = { ...VIDEO_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n\n/**\n * Resolve unresolved audio tracks. Same shape as `resolveVideoTrack`,\n * narrowed to audio.\n */\nexport const resolveAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedAudioTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Key order is load-bearing — see resolveVideoTrack.\n const trackConfig = { ...AUDIO_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n\n/**\n * Resolve unresolved text tracks. Same shape as `resolveVideoTrack`,\n * narrowed to text.\n */\nexport const resolveTextTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedTextTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config = {},\n }: {\n state: ResolveTrackStateMap<'selectedTextTrackId'>;\n config?: ResolveTrackConfig;\n }) => {\n // Key order is load-bearing — see resolveVideoTrack.\n const trackConfig = { ...TEXT_TRACK_RESOLUTION_CONFIG, ...config };\n return setupTrackResolution({\n state,\n config: { ...trackConfig, fetchResolvableText: failoverFetch(defaultFetchResolvableText, state, trackConfig) },\n });\n },\n});\n"],"mappings":";;;;;;;;;;;;;AA2FA,SAAS,qBAAiD,EACxD,OACA,QAAQ,EACN,aACA,oBACA,qBAAA,wBAAsBA,qBACtB,gBACA,YACA,sCAQD;CAID,MAAM,SAAS,IAAI,gBAA+B,cAAc,OAAO;CAWvE,MAAM,qBAAqB,eACzB,uBAAuB,MAAM,aAAa,IAAI,CAAC,IAC1C,0BACA,yBACP;CAEA,OAAO,qBAAqB;EAC1B,SAAS;EACT,eAAe,mBAAmB,IAAI;EACtC,QAAQ;GACN,2BAA2B,CAAC;GAC5B,yBAAyB;IAOvB,mBAAmB,OAAO,SAAS;IACnC,SAAS,OACD;KAMJ,MAAM,eAAe,KAAK,MAAM,YAAY;KAC5C,MAAM,UAAU,MAAM,YAAY,CAAC,IAAI;KACvC,IAAI,CAAC,gBAAgB,CAAC,SAAS;KAE/B,MAAM,QAAQ,mBAAmB,cAAc,OAAO;KAGtD,IAAI,CAAC,SAAU,gBAAgB,KAAK,KAAK,OAAO,SAAS,MAAM,QAAQ,GAAI;KA2G3E,OAvGyB,SAOvB,IAAI,KACF,OAAO,WAAW;MAChB,MAAM,WAAW,KAAK,MAAM,YAAY;MACxC,MAAM,UAAU,WAAW,mBAAmB,UAAU,OAAO,IAAI,KAAA;MACnE,IAAI,CAAC,SAAS,MAAM,IAAI,MAAM,yCAAyC;MAQvE,MAAM,OAAO,MAAMC,sBAAoB,SAAS,EAAE,OAAO,CAAC;MAQ1D,IAAI,kBAAkB,CAAC,gBAAgB,OAAO,GAAG;OAC/C,MAAM,EAAE,sBAAsB,yBAAyB;OACvD,MAAM,WAEF,eACE,MAAM,aAAa,IAAI,GACvB;QACE,sBAAsB,sBAAsB,IAAI;QAChD,sBAAsB,sBAAsB,IAAI;OAClD,GACA,OACF,GACF,EAAE,OAAO,CACX;MACF;MAYA,MAAM,OAAO,KAAK,MAAM,YAAY;MACpC,MAAM,WAAW,OAAO,mBAAmB,MAAM,OAAO,IAAI,KAAA;MAC5D,IAAI,CAAC,UAAU,MAAM,IAAI,MAAM,yCAAyC;MACxE,MAAM,aAAa,mBAAmB,MAAM,QAAQ;MAMpD,IAAI,kCACF,KAAK,MAAM,aAAa,iCAAiC,UAA2B,GAClF,UAAU,OAAO,SAAS;MAW9B,OAAO,MAAM,eAAe,YAAY;OACtC,IAAI,CAAC,uBAAuB,OAAO,GAAG,OAAO;OAC7C,MAAM,UAAU,0BAA0B,SAAS,UAAU;OAmB7D,OAAO;QAAE,GAVS,yBAAyB,IAAI,WAAW,QAAQ,IAC9D,uBAAuB,SAAS,WAAW,MAAM,WAAW,QAAQ,IACpE;QAQmB,YAAY,iBAAiB,yBAAyB,UAAU,CAAC;OAAE;MAC5F,CAAC;MACD,OAAO;KACT,GACA,EAAE,IAAI,MAAM,GAAG,CACjB,CAEM,CAAC,CAAC,YAAY,CAAC,CAAC;IAC1B,CACF;GACF;EACF;CACF,CAAC;AACH;AAMA,MAAM,gCAAgC;CACpC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,SAAS,OAAO;AAC5C;AAEA,MAAM,gCAAgC;CACpC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,SAAS,OAAO;AAC5C;AAEA,MAAM,+BAA+B;CACnC,GAAG;CACH,qBAAqB,cAAyC,YAC5D,UAAU,cAAc,QAAQ,OAAO;AAC3C;;;;;;AAWA,MAAa,oBAAoB,eAAe;CAC9C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAMJ,MAAM,cAAc;GAAE,GAAG;GAA+B,GAAG;EAAO;EAClE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcD,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC;;;;;AAMD,MAAa,oBAAoB,eAAe;CAC9C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAEJ,MAAM,cAAc;GAAE,GAAG;GAA+B,GAAG;EAAO;EAClE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcA,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC;;;;;AAMD,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,qBAAqB;CACjD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,SAAS,CAAC,QAIN;EAEJ,MAAM,cAAc;GAAE,GAAG;GAA8B,GAAG;EAAO;EACjE,OAAO,qBAAqB;GAC1B;GACA,QAAQ;IAAE,GAAG;IAAa,qBAAqB,cAAcA,qBAA4B,OAAO,WAAW;GAAE;EAC/G,CAAC;CACH;AACF,CAAC"}
|
|
@@ -3,6 +3,8 @@ import { defineBehavior } from "../../core/composition/create-composition.js";
|
|
|
3
3
|
import { createMachineReactor } from "../../core/reactors/create-machine-reactor.js";
|
|
4
4
|
import { isResolvedPresentation } from "../../media/types/index.js";
|
|
5
5
|
import { getTracksByType } from "../../media/utils/tracks.js";
|
|
6
|
+
import { SVTA_NO_SUPPORTED_AUDIO_TRACK, SVTA_NO_SUPPORTED_VIDEO_TRACK } from "../../media/errors.js";
|
|
7
|
+
import { emitError } from "./collect-errors.js";
|
|
6
8
|
import { getCdnId } from "../../media/utils/cdn.js";
|
|
7
9
|
import { DEFAULT_BANDWIDTH_CONFIG, getBandwidthEstimate } from "../../network/bandwidth-estimator.js";
|
|
8
10
|
import { DEFAULT_QUALITY_CONFIG, resolutionArea } from "../../media/abr/quality-selection.js";
|
|
@@ -57,11 +59,13 @@ import { matchesPartialTrack, pickTextTrackFromTracks } from "../../media/primit
|
|
|
57
59
|
* *constraint* is the failover half — prune the cooled-down CDN, the scope falls
|
|
58
60
|
* to the next.)
|
|
59
61
|
*
|
|
60
|
-
* When the pre-pass prunes a type
|
|
61
|
-
*
|
|
62
|
-
*
|
|
63
|
-
*
|
|
64
|
-
*
|
|
62
|
+
* When the pre-pass prunes a type that *has* tracks to empty, the behavior
|
|
63
|
+
* clears the selection (so a now-unplayable pick can't linger and stall) and
|
|
64
|
+
* reports the type's `noSupportedTrackCode`. Which constraint emptied the set is
|
|
65
|
+
* deliberately not consulted — the behavior reads no constraint's state, so the
|
|
66
|
+
* chain stays composable. A type with no tracks at all is left alone; that's a
|
|
67
|
+
* legitimate source shape, not a failure. The late `createSourceBuffer` check
|
|
68
|
+
* stays as the structural backstop.
|
|
65
69
|
*
|
|
66
70
|
* Deferred: audio's preferred-language / default-track selection as standing
|
|
67
71
|
* soft-filter rules (previously the empty-slot picker, dropped in the move to
|
|
@@ -267,7 +271,7 @@ function pickResolvedTextTrack(candidates, { state, config }) {
|
|
|
267
271
|
}
|
|
268
272
|
function setupTrackSwitching(deps) {
|
|
269
273
|
const { state, config } = deps;
|
|
270
|
-
const { selectionKey, getTracks, rules, resolveSelection = selectChainHead } = config;
|
|
274
|
+
const { selectionKey, getTracks, rules, resolveSelection = selectChainHead, noSupportedTrackCode } = config;
|
|
271
275
|
const derivedStateSignal = computed(() => isResolvedPresentation(state.presentation.get()) ? "presentation-resolved" : "presentation-unresolved");
|
|
272
276
|
const candidateSet = computed(() => {
|
|
273
277
|
const presentation = state.presentation.get();
|
|
@@ -286,7 +290,10 @@ function setupTrackSwitching(deps) {
|
|
|
286
290
|
if (!tracks.length) {
|
|
287
291
|
const presentation = peek(state.presentation);
|
|
288
292
|
if (isResolvedPresentation(presentation) && getTracks(presentation).length > 0) {
|
|
289
|
-
|
|
293
|
+
if (noSupportedTrackCode !== void 0) emitError(state, {
|
|
294
|
+
code: noSupportedTrackCode,
|
|
295
|
+
data: { selectionKey }
|
|
296
|
+
});
|
|
290
297
|
state[selectionKey].set(void 0);
|
|
291
298
|
}
|
|
292
299
|
return;
|
|
@@ -327,7 +334,8 @@ const switchVideoTrack = defineBehavior({
|
|
|
327
334
|
filterByUserSelection,
|
|
328
335
|
preferActiveCdn,
|
|
329
336
|
rankByBandwidth
|
|
330
|
-
]
|
|
337
|
+
],
|
|
338
|
+
noSupportedTrackCode: SVTA_NO_SUPPORTED_VIDEO_TRACK
|
|
331
339
|
}
|
|
332
340
|
})
|
|
333
341
|
});
|
|
@@ -360,7 +368,8 @@ const switchAudioTrack = defineBehavior({
|
|
|
360
368
|
filterByUserSelection,
|
|
361
369
|
preferActiveCdn,
|
|
362
370
|
rankByBandwidth
|
|
363
|
-
]
|
|
371
|
+
],
|
|
372
|
+
noSupportedTrackCode: SVTA_NO_SUPPORTED_AUDIO_TRACK
|
|
364
373
|
}
|
|
365
374
|
})
|
|
366
375
|
});
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"track-switching.js","names":["getCdnId","defaultGetCdnId"],"sources":["../../../../src/playback/behaviors/track-switching.ts"],"sourcesContent":["/**\n * **Per-type track selection as a rule chain.** While a presentation is\n * resolved, owns that type's `selected{Video,Audio,Text}TrackId` signal: pick a\n * default, react to user intent and algorithmic ranking, and clear it on src\n * unload.\n *\n * Selection runs in two stages. First a **hard-constraints pre-pass**\n * (`applyConstraints`) prunes the unplayable from the candidate set — the\n * failed-CDN constraint (`excludeFailedCdns`, failover cooldown) and the\n * capability constraint (`excludeUnplayableTracks`, codec support). Then a small\n * ordered chain of rules (`applyRules`) picks among the survivors. Each constraint/rule reads the signals it needs at apply\n * time, so the effect subscribes to exactly what was consulted. The chain is\n * three rules, most authoritative first:\n *\n * 1. **user intent** — a soft filter on `user*TrackSelection`: narrow to the\n * partial-track match; an empty match falls through to the full set.\n * 2. **active CDN** — a soft filter on `cdnPriority` (`preferActiveCdn`):\n * narrow to the highest-priority CDN that still has tracks; an empty match\n * falls through. Shared by video and audio, so every type stays on one CDN\n * (`deriveCdnPriority` owns the list). No-op for non-redundant sources.\n * 3. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and\n * audio. Fitting tracks (within the throughput threshold) first, highest\n * bitrate first; over-throughput tracks after, least-over first. Hysteresis\n * via boosting the current track's sort weight by `upgradeMargin`.\n *\n * The composer's early-bail (one survivor → stop) is load-bearing: a user\n * selection that narrows to a single track is the pick without the ranker\n * running, so the bandwidth estimate is never read and the effect doesn't\n * re-fire on bandwidth while that choice holds.\n *\n * Lifecycle: `'presentation-unresolved'` ↔ `'presentation-resolved'`. The\n * resolved state owns the signal; its entry-returned cleanup clears it on exit\n * (canonical cleanup-binds-to-setup per `reactors.md`).\n *\n * The pick is the chain's result mapped to a slot value by `resolveSelection`\n * (default: the head, `applyRules(...)[0]`). Each variant supplies its\n * **constraints + rule chain (+ optional resolveSelection)** via config;\n * `setupTrackSwitching` owns only the lifecycle and runs what it's given. Video\n * and audio run constraints `[excludeFailedCdns, excludeUnplayableTracks]` then\n * rules `[filterByUserSelection, preferActiveCdn, rankByBandwidth]` and take the\n * head; `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack`\n * takes none. `switchTextTrack` differs — selection is *optional* (captions are\n * opt-in / off-able), so it runs `[excludeFailedCdns]` + `[preferActiveCdn]` and\n * supplies a text terminal (`pickResolvedTextTrack`) that resolves standing user\n * intent (`userTextTrackSelection`, incl. `'off'`) and may yield no selection.\n * (The active-CDN *scope* is the sticky-pick half of multi-CDN; the failed-CDN\n * *constraint* is the failover half — prune the cooled-down CDN, the scope falls\n * to the next.)\n *\n * When the pre-pass prunes a type's candidates to empty, the behavior leaves any\n * prior pick in place and makes no new pick; the late `createSourceBuffer` check\n * stays as the structural backstop for an unplayable rendition reaching the\n * pipeline. Surfacing \"nothing playable\" as observable state is deferred until a\n * consumer (error mapping) needs it.\n *\n * Deferred: audio's preferred-language / default-track selection as standing\n * soft-filter rules (previously the empty-slot picker, dropped in the move to\n * the rule chain).\n */\n\nimport { type AnySlotMap, defineBehavior } from '../../core/composition/create-composition';\nimport { createMachineReactor } from '../../core/reactors/create-machine-reactor';\nimport { computed, peek, type ReadonlySignal, type Signal } from '../../core/signals/primitives';\nimport { DEFAULT_QUALITY_CONFIG, type QualityConfig, resolutionArea } from '../../media/abr/quality-selection';\nimport {\n matchesPartialTrack,\n pickTextTrackFromTracks,\n type TextSelectionConfig,\n} from '../../media/primitives/select-tracks';\nimport {\n type AudioTrack,\n type CanPlayTrack,\n isResolvedPresentation,\n type MaybeResolvedPresentation,\n type PartiallyResolvedAudioTrack,\n type PartiallyResolvedTextTrack,\n type PartiallyResolvedVideoTrack,\n type TextTrack,\n type VideoTrack,\n} from '../../media/types';\nimport { getCdnId as defaultGetCdnId, type GetCdnId } from '../../media/utils/cdn';\nimport { getTracksByType } from '../../media/utils/tracks';\nimport type { BandwidthConfig, BandwidthState } from '../../network/bandwidth-estimator';\nimport { DEFAULT_BANDWIDTH_CONFIG, getBandwidthEstimate } from '../../network/bandwidth-estimator';\n\n// ============================================================================\n// State + Config\n// ============================================================================\n\n/**\n * The slots `setupTrackSwitching` itself owns: the `presentation` gate it reads\n * and the per-type `selected*TrackId` it writes. Rule-only inputs are\n * deliberately absent — `user*TrackSelection` and `bandwidthState` belong to\n * whoever materializes them (the embedder via `shareSignals`, the buffer-actor\n * sampler), and each rule declares the signal it consults as an optional slot\n * on its own deps map, so the behavior never assumes a rule's signal exists.\n */\nexport interface TrackSwitchingState {\n presentation?: MaybeResolvedPresentation;\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n}\n\n/**\n * Config for `switchVideoTrack` — the ABR tuning read by its ranker rule\n * (`rankByBandwidth`). `quality.safetyMargin` is the bandwidth-headroom\n * multiplier; `quality.upgradeMargin` the hysteresis ratio gating upgrades;\n * `bandwidth` tunes the estimator; `initialBandwidth` is the pre-sample\n * fallback. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15),\n * `DEFAULT_BANDWIDTH_CONFIG`, `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\nexport interface SwitchVideoTrackConfig {\n quality?: Partial<QualityConfig>;\n bandwidth?: Partial<BandwidthConfig>;\n initialBandwidth?: number;\n /** Override CDN-id derivation (shared by the CDN scope + failover constraint). */\n getCdnId?: GetCdnId;\n /**\n * Codec capability probe read by the `excludeUnplayableTracks` hard\n * constraint — drops renditions this environment can't decode before\n * selection runs. Injected (rather than imported) so the DOM-free behavior\n * never reaches a DOM API directly; the engine defaults it to the\n * `MediaSource.isTypeSupported`-backed `canPlayTrack`. Absent → no codec\n * filtering (the constraint passes everything through).\n */\n canPlayTrack?: CanPlayTrack;\n}\n\n/** Default initial-bandwidth value before bandwidth measurements arrive. */\nexport const DEFAULT_INITIAL_BANDWIDTH = 5_000_000;\n\n// ============================================================================\n// Rule chain\n// ============================================================================\n\n/**\n * Deps handed to each rule and to `applyRules`, mirroring a behavior's setup\n * deps so a rule reads from the same surfaces a behavior does. `context` is\n * optional — it's threaded through but absent on direct setup calls (and\n * unread by today's rules), so the whole deps object can pass straight through.\n */\nexport interface SelectionRuleDeps<State = unknown, Context = unknown, Config = unknown> {\n state: State;\n context?: Context;\n config: Config;\n}\n\n/**\n * A selection rule narrows or reorders the candidate list. It reads the state,\n * context, and config it needs at apply time (tightly-coupled reads), so a\n * rule's `.get()`s subscribe the running effect to exactly what it consulted.\n * Returning an empty list means \"no match\" — the composer skips it, so a soft\n * filter never narrows the set to nothing. A ranker returns the list with its\n * pick at the head.\n */\nexport type SelectionRule<T, State = unknown, Context = unknown, Config = unknown> = (\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => readonly T[];\n\n/**\n * Apply rules to a candidate list in order; the pick is the first survivor.\n * Two responsibilities the rules don't carry: a rule that returns nothing is\n * skipped (fall-through — a preference never empties the set), and once one\n * survivor remains the chain stops (early-bail — later rules, including the\n * bandwidth ranker, never run, so the effect doesn't subscribe to their\n * signals while the choice is fixed).\n *\n * @param rules - Rules to apply, most authoritative first\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed through to each rule\n * @returns The surviving candidates, pick first\n */\nexport function applyRules<T, State, Context, Config>(\n rules: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const rule of rules) {\n const remaining = rule(current, deps);\n if (remaining.length === 0) continue;\n current = remaining;\n if (current.length === 1) break;\n }\n return current;\n}\n\n/**\n * Apply hard constraints to a candidate list — the pre-pass that runs before the\n * rule chain. A constraint shares a rule's signature but its exclusion is\n * *hard*: it removes the unplayable (a codec the environment can't decode, a CDN\n * in failover cooldown) and a removed track is never attempted. Unlike\n * `applyRules`, this never skips an empty result and never early-bails — every\n * constraint always applies, and an empty survivor set is a real outcome\n * (\"nothing playable here\"), not a fall-through. Because each constraint only\n * removes, the order they run in can't change the result.\n *\n * @param constraints - Constraints to apply (pooled, order-independent)\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed to each constraint\n * @returns The playable survivors (possibly empty)\n */\nexport function applyConstraints<T, State, Context, Config>(\n constraints: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const constraint of constraints) current = constraint(current, deps);\n return current;\n}\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackSwitching` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => Reactor`. Each `switchXTrack` export below calls\n// it from inside its own `defineBehavior` setup. Its generics — `S` (selection\n// slot key), `T` (candidate track type), `C` (the concrete config the variant\n// builds) — all infer from the passed `state` + `config`, so the variants need\n// no explicit type arguments. `C extends TrackSwitchingConfig<S, T>` lets the\n// variant's richer config (rule-specific fields included) flow through the\n// helper untouched; the rules read those fields off their own config views.\n//\n// -- Design note: why narrow `SelectionKey` / `UserSelectionKey` unions ----\n// Goal we did not reach: have callers \"fully pass in\" the slot keys, with\n// the helper enforcing zero internal knowledge of which literals are valid.\n// What blocks it: indexing a mapped-type intersection by a generic key.\n// When `S extends keyof TrackSwitchingState` (or `string`), TS conservatively\n// treats `state[selectionKey]` as the union of every possible match across\n// the intersected mapped portions — including the fixed-key signal\n// (`presentation`) — and widens to their value-type union.\n// The sibling pattern hits the same constraint and answers it the same way:\n// `SelectedTrackKey` in `select-tracks.ts` is a hardcoded narrow union for\n// the same reason.\n//\n// Current pick is the narrow-union route because it matches siblings and\n// the unions read as documentation (\"these are the slots this helper\n// manages\") rather than restriction. Extending to a new track-switching\n// axis is one literal per union.\n// --------------------------------------------------------------------------\n// ============================================================================\n\n/**\n * Minimum candidate-track shape consumed by the helper and its rules: an `id`\n * (the pick), a `url` (the active-CDN scope derives the CDN from it), an\n * optional `bandwidth` (the ranker's throughput sort), and optional\n * `width`/`height` (the ranker's equal-bitrate tie-break — absent on audio, so\n * audio candidates area-compare equal). Every resolved/partially-resolved video\n * track carries them all; audio tracks omit the dimensions.\n */\ntype SwitchableTrack = {\n id: string;\n url: string;\n bandwidth?: number;\n width?: number;\n height?: number;\n // Read by the capability constraint to probe codec support. Optional on the\n // minimal shape; every resolved/partially-resolved video & audio candidate\n // carries them, and an absent `mimeType` makes a track unprobeable (kept).\n mimeType?: string;\n codecs?: string[];\n};\n\n/**\n * Map the rule chain's surviving candidates to the final selection id, or\n * `undefined` for a deliberate no-selection. Defaults to the chain head\n * (`selectChainHead`) — the always-pick contract video and audio rely on\n * (`applyRules` guarantees a non-empty result, so the head is always there). A\n * variant whose selection is legitimately optional (text: opt-in captions,\n * explicit off) supplies its own picker that may return `undefined`; the helper\n * writes that straight through to the slot, clearing it.\n */\nexport type ResolveSelection<T extends SwitchableTrack, State = unknown, Context = unknown, Config = unknown> = (\n candidates: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => string | undefined;\n\ntype SelectionKey = 'selectedVideoTrackId' | 'selectedAudioTrackId' | 'selectedTextTrackId';\ntype UserSelectionKey = 'userVideoTrackSelection' | 'userAudioTrackSelection';\n\n// Each mapped value references `P` so TS keeps the per-key dependency and\n// resolves `state[selectionKey]` to the right arm. `T` (track type) stays out\n// of the state map (it flows through `TrackSwitchingConfig` instead).\n//\n// Only the behavior's own lifecycle signals are required here: the presentation\n// gate and the selection slot it writes. Signals a *rule* reads but the\n// behavior doesn't — `user*TrackSelection` (the user-selection filter) and\n// `bandwidthState` (the bandwidth ranker) — are NOT here; each rule declares\n// the signal it needs as *optional* on its own deps and reads it defensively,\n// so the behavior never assumes a rule-only signal exists. Those slots are\n// materialized by whoever owns them: `shareSignals` for the consumer-input\n// `user*TrackSelection`, the buffer-actor sampler for `bandwidthState`.\nexport type TrackSwitchingStateMap<S extends SelectionKey> = {\n presentation: ReadonlySignal<TrackSwitchingState['presentation']>;\n} & { [P in S]: Signal<TrackSwitchingState[P]> };\n\n/**\n * Config `setupTrackSwitching` itself reads — its own wiring: which selection\n * slot to write and clear (`selectionKey`), how to enumerate candidate tracks\n * (`getTracks`), the optional **hard-constraints pre-pass** (`constraints`,\n * applied before the chain to prune the unplayable), and the **rule chain** to\n * run (`rules`), and how to map the chain's survivors to the final pick\n * (`resolveSelection`, defaulting to the chain head). Rule-/constraint-specific\n * config is deliberately absent — each declares the fields it reads as *optional*\n * on its own config view (`UserSelectionConfig`, `BandwidthRankerConfig`), so the\n * behavior never enumerates them. The variant builds the concrete config as this\n * base plus whatever its chain consults; it flows through untouched as the `C`\n * type param on `setupTrackSwitching`.\n */\ninterface TrackSwitchingConfig<S extends SelectionKey, T extends SwitchableTrack> {\n selectionKey: S;\n getTracks: (presentation: MaybeResolvedPresentation) => readonly T[];\n constraints?: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n rules: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n /**\n * Map the chain's surviving candidates to the final selection id. Optional —\n * absent means the chain head (`selectChainHead`), the always-pick path video\n * and audio use. A variant with optional selection (text) supplies one that\n * may return `undefined`.\n */\n resolveSelection?: ResolveSelection<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>;\n}\n\n/**\n * State the user-selection filter reads: the lifecycle map plus an *optional*\n * user-selection slot (keyed by `U`), holding a partial-track description to\n * match against the candidates (`Partial<T>` — `{ id }`, `{ language }`,\n * `{ height }`, …). The slot exists only when the composition provides it\n * (materialized by `shareSignals`); the filter reads it defensively and no-ops\n * when it's absent (no user override).\n */\ntype UserSelectionStateMap<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingStateMap<S> & {\n [P in U]?: ReadonlySignal<Partial<T> | undefined>;\n};\n\n/**\n * Config the user-selection filter reads: `userSelectionKey` names the state\n * slot holding the user's selection. *Optional* on the rule's view — the base\n * config doesn't carry it, so an unwired key means \"no user selection\" and the\n * filter passes through. The variants always supply it.\n */\ntype UserSelectionConfig<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingConfig<S, T> & { userSelectionKey?: U };\n\n/**\n * State the bandwidth ranker reads: the lifecycle map plus an *optional*\n * `bandwidthState`. The signal exists only when the composition includes a\n * bandwidth sampler; the ranker reads it defensively and falls back to\n * `initialBandwidth` (with a debug note) when it's absent.\n */\ntype BandwidthRankerStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n bandwidthState?: ReadonlySignal<BandwidthState | undefined>;\n};\n\n/**\n * Config the bandwidth ranker reads: the ABR tuning in `SwitchVideoTrackConfig`\n * (`quality` / `bandwidth` / `initialBandwidth`), all optional with defaults.\n */\ntype BandwidthRankerConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> &\n SwitchVideoTrackConfig;\n\n/**\n * State the active-CDN scope reads: the lifecycle map plus an *optional*\n * `cdnPriority` — the manifest-ordered CDN list (most-preferred first). The\n * signal exists only when the composition includes `deriveCdnPriority` (which\n * materializes + owns it); the scope reads it defensively and passes through\n * when it's absent (no CDN preference).\n */\ntype CdnScopeStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n cdnPriority?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * State the failed-CDN constraint reads: the lifecycle map plus an *optional*\n * `failedCdns` — the CDN ids currently in failover cooldown. The signal exists\n * only when the composition includes a failover monitor (or an external driver); the\n * constraint reads it defensively and excludes nothing when it's absent.\n */\ntype CdnConstraintStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n failedCdns?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * Config the CDN rules read: the base config plus an *optional* `getCdnId`\n * override. Both `excludeFailedCdns` and `preferActiveCdn` derive a track's CDN\n * from its URL; the override must be the *same* one `deriveCdnPriority` and the\n * failover trip use, or the keys stop matching. Optional → defaults to the\n * origin-based `getCdnId`, so the base config (without it) stays assignable.\n */\ntype CdnRuleConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> & {\n getCdnId?: GetCdnId;\n};\n\n/**\n * Config the capability constraint reads: the base config plus an *optional*\n * `canPlayTrack` codec probe. Optional → an unwired probe means \"no codec\n * filtering\" and the constraint passes everything through, so the base config\n * (without it) stays assignable. The engine defaults it to the DOM-bound\n * `canPlayTrack`.\n */\ntype CapabilityConstraintConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> & {\n canPlayTrack?: CanPlayTrack;\n};\n\ntype VideoTrackCandidate = PartiallyResolvedVideoTrack | VideoTrack;\ntype AudioTrackCandidate = PartiallyResolvedAudioTrack | AudioTrack;\ntype TextTrackCandidate = PartiallyResolvedTextTrack | TextTrack;\n\n// ----------------------------------------------------------------------------\n// Rules — defined outside the behavior closure, parameterized only by their\n// deps. Each is generic over the slot keys + track type; the variant's\n// concrete keys instantiate it where the chain is assembled.\n// ----------------------------------------------------------------------------\n\n/**\n * User intent — a soft filter. Narrows to tracks matching the partial-track\n * selection in `user*TrackSelection`; an empty match falls through (the\n * composer skips it) to the unfiltered set — e.g. a stale id from a previous\n * source.\n */\nfunction filterByUserSelection<S extends SelectionKey, U extends UserSelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<UserSelectionStateMap<S, U, T>, AnySlotMap, UserSelectionConfig<S, U, T>>\n): readonly T[] {\n const key = config.userSelectionKey;\n if (!key) return tracks;\n const filter = state[key]?.get();\n return filter ? tracks.filter((track) => matchesPartialTrack(track, filter)) : tracks;\n}\n\n/**\n * Failed-CDN constraint — a *hard* filter (constraints pre-pass), shared by\n * video and audio. Removes tracks served from a CDN currently in failover\n * cooldown (`failedCdns`, written by the failover monitor). Removed tracks are never\n * attempted; the scope then narrows to the next surviving CDN in `cdnPriority`,\n * and snaps back to the primary once it leaves cooldown.\n *\n * Passes everything through when there's no `failedCdns` signal/value. When it\n * prunes *every* track (all CDNs cooled down), the empty result is preserved\n * (per `applyConstraints`) — \"nothing playable,\" which clears the selection (no\n * pick); a later CDN recovery refills the candidate set and re-picks.\n */\nfunction excludeFailedCdns<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnConstraintStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const failed = state.failedCdns?.get();\n if (!failed?.length) return tracks;\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n const failedSet = new Set(failed);\n return tracks.filter((track) => !failedSet.has(getCdnId(track.url)));\n}\n\n/**\n * Capability constraint — a *hard* filter (constraints pre-pass), shared by\n * video and audio. Removes renditions this environment can't decode, probed via\n * the injected `canPlayTrack` (codec → `MediaSource.isTypeSupported`). Moving\n * the check here — before selection — means an unplayable variant (e.g. HEVC on\n * a browser without HEVC) is pruned upstream and never picked, instead of\n * surviving into the pipeline to fail late at `createSourceBuffer`. That late\n * throw stays as a defensive structural guarantee; with this constraint it\n * should rarely fire.\n *\n * Passes everything through when there's no `canPlayTrack` probe (a composition\n * that didn't wire it, or DOM-free tests). When it prunes *every* track (no\n * decodable rendition), the empty result is preserved (per `applyConstraints`)\n * — \"nothing playable,\" so the behavior clears the selection (no pick) and the\n * late `createSourceBuffer` check stays as the backstop.\n */\nfunction excludeUnplayableTracks<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { config }: SelectionRuleDeps<TrackSwitchingStateMap<S>, AnySlotMap, CapabilityConstraintConfig<S, T>>\n): readonly T[] {\n const canPlay = config.canPlayTrack;\n if (!canPlay) return tracks;\n return tracks.filter((track) => canPlay(track));\n}\n\n/**\n * Active-CDN scope — a soft filter, shared by video and audio. Narrows to the\n * highest-priority CDN in `cdnPriority` (owned by `deriveCdnPriority`) that\n * still has tracks, so every track type stays on one CDN. A redundant-streams\n * source lists the same renditions on multiple hosts; this keeps the pick on one\n * host rather than letting the ranker drift across them.\n *\n * \"Active\" is derived, not stored: constraints run before the rule chain, so a\n * failed CDN's tracks are already pruned by the time this runs — \"first CDN with\n * survivors\" *is* the active CDN, and it falls through to the next on failover\n * (and snaps back to the primary when it recovers). Content steering reorders\n * `cdnPriority`; this rule just honors the order.\n *\n * Soft-filter semantics: passes through when there's no `cdnPriority` signal/value\n * (no preference) or when nothing matches (`applyRules` skips an empty result).\n * Non-redundant sources have one CDN, so the narrow is a no-op.\n *\n * The CDN-id derivation defaults to origin-based `getCdnId`, overridable via the\n * `getCdnId` config — it must match the one `deriveCdnPriority` used to build\n * `cdnPriority`, or no track's CDN would ever equal an entry.\n */\nfunction preferActiveCdn<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnScopeStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const cdnPriority = state.cdnPriority?.get();\n if (!cdnPriority?.length) return tracks;\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n for (const cdn of cdnPriority) {\n const tracksUsingCdn = tracks.filter((track) => getCdnId(track.url) === cdn);\n if (tracksUsingCdn.length) return tracksUsingCdn;\n }\n return tracks;\n}\n\n/**\n * Bandwidth ranking — the terminal sort, shared by video and audio. Orders by\n * the throughput estimate: tracks within the bandwidth threshold first\n * (fitting), highest bitrate first; then over-threshold tracks, least-over\n * first. The head is the best-quality track that fits, falling back to the\n * smallest over-throughput track when nothing fits.\n *\n * Hysteresis without temporal state: the current track's effective bitrate is\n * boosted by `upgradeMargin` in the fitting sort, so a higher track only\n * outranks it once it clears `current.bitrate * upgradeMargin` (no flapping on\n * marginal bandwidth gains). Downgrades fall out for free — a current track\n * over the threshold isn't in the fitting set to be boosted, so the best fit (a\n * downgrade) wins immediately. Equal-bitrate tracks break by resolution (higher\n * `width × height` first), so an equal-bitrate ladder never picks a lower-\n * quality rendition by manifest order; audio tracks carry no dimensions, so\n * they area-compare equal and a stable sort keeps their candidate order (e.g.\n * same-bitrate language variants). Early-bail skips this rule when a prior one\n * narrowed to a single track, so the estimate is neither read nor subscribed\n * while that holds.\n */\nfunction rankByBandwidth<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<BandwidthRankerStateMap<S>, AnySlotMap, BandwidthRankerConfig<S, T>>\n): readonly T[] {\n const safetyMargin = config.quality?.safetyMargin ?? DEFAULT_QUALITY_CONFIG.safetyMargin;\n const upgradeMargin = config.quality?.upgradeMargin ?? DEFAULT_QUALITY_CONFIG.upgradeMargin;\n const initialBandwidth = config.initialBandwidth ?? DEFAULT_INITIAL_BANDWIDTH;\n const bandwidthConfig: BandwidthConfig = { ...DEFAULT_BANDWIDTH_CONFIG, ...config.bandwidth };\n if (!state.bandwidthState) {\n console.debug(\n '[track-switching] rankByBandwidth: no bandwidthState signal in composition; ranking on initialBandwidth'\n );\n }\n const threshold = getBandwidthEstimate(state.bandwidthState?.get(), initialBandwidth, bandwidthConfig) * safetyMargin;\n const currentId = state[config.selectionKey].get();\n const bitrate = (track: T) => track.bandwidth ?? 0;\n // Boost the current track's sort weight by upgradeMargin (fitting set only) so\n // an upgrade must clear current.bitrate * upgradeMargin to outrank it.\n const rank = (track: T) => (track.id === currentId ? bitrate(track) * upgradeMargin : bitrate(track));\n // Equal bitrate → prefer higher resolution (width × height), so an\n // equal-bitrate ladder doesn't pick a lower-quality rendition by manifest\n // order. Audio tracks carry no dimensions, so they area-compare equal and\n // keep candidate order (stable sort).\n const fitting = tracks\n .filter((track) => bitrate(track) <= threshold)\n .sort((a, b) => rank(b) - rank(a) || resolutionArea(b) - resolutionArea(a));\n const over = tracks\n .filter((track) => bitrate(track) > threshold)\n .sort((a, b) => bitrate(a) - bitrate(b) || resolutionArea(b) - resolutionArea(a));\n return [...fitting, ...over];\n}\n\n/**\n * Default final pick: the chain head. `applyRules` never narrows to nothing and\n * early-bails to a single survivor, so video and audio always converge to a\n * track and the head is the pick.\n */\nfunction selectChainHead<T extends SwitchableTrack>(candidates: readonly T[]): string {\n return candidates[0]!.id;\n}\n\n/**\n * State the text terminal reads: the lifecycle map plus an *optional*\n * `userTextTrackSelection` — the standing user intent. `Partial<TextTrack>` is an\n * explicit pick (language-based), `'off'` is explicit no-captions, `undefined` is\n * auto (no preference). The slot exists only when the composition materializes it\n * (`shareSignals`); the terminal reads it defensively and treats absence as auto.\n *\n * Unlike `user*TrackSelection` for video/audio, this carries the `'off'` sentinel\n * and feeds the terminal pick (not the shared `filterByUserSelection`) — text is\n * the only type whose selection is legitimately optional, so the off/auto logic\n * lives in one text-specific place rather than widening the shared filter.\n */\ntype TextSelectionStateMap = TrackSwitchingStateMap<'selectedTextTrackId'> & {\n userTextTrackSelection?: ReadonlySignal<Partial<TextTrack> | 'off' | undefined>;\n};\n\n/** Config the text terminal reads: the base config plus the opt-in default policy. */\ntype TextTerminalConfig = TrackSwitchingConfig<'selectedTextTrackId', TextTrackCandidate> & TextSelectionConfig;\n\n/**\n * Terminal pick for text — the `resolveSelection` the text variant supplies.\n * Resolves the standing `userTextTrackSelection` intent against the chain's\n * survivors (already CDN-failover-pruned and active-CDN-scoped):\n *\n * - `'off'` → no selection (clear the slot). Sticky through re-evaluation, so a\n * live refresh or failover re-run can't re-assert a default.\n * - explicit `Partial<TextTrack>` → narrow to the match (language-based). A\n * stale pick whose match is gone (e.g. the language dropped on a source\n * change) falls through to the default policy.\n * - auto (`undefined`) → the opt-in default policy (`preferredSubtitleLanguage`\n * → `DEFAULT=YES + AUTOSELECT=YES` → none), shared with `pickTextTrack`.\n *\n * Returning `undefined` is a real outcome (captions are opt-in), which is why the\n * text variant relies on `setupTrackSwitching`'s no-selection seam.\n */\nfunction pickResolvedTextTrack<T extends TextTrackCandidate>(\n candidates: readonly T[],\n { state, config }: SelectionRuleDeps<TextSelectionStateMap, AnySlotMap, TextTerminalConfig>\n): string | undefined {\n const intent = state.userTextTrackSelection?.get();\n if (intent === 'off') return undefined;\n if (intent) {\n // The stored intent is a `Partial<TextTrack>`; cast to the candidate's own\n // partial shape so the generic `matchesPartialTrack` accepts it (every field\n // it carries — language, forced — exists on the candidate too).\n const matched = candidates.filter((track) => matchesPartialTrack(track, intent as Partial<T>));\n if (matched.length) return matched[0]!.id;\n }\n return pickTextTrackFromTracks(candidates, config);\n}\n\n// `context` is the composition's context map, threaded in by each variant's\n// rest-spread and typed as the generic slot-map shape (`AnySlotMap`). It can't\n// be a typed param on the `defineBehavior` setup without widening `ContextMap`\n// to its constraint and forcing the slot required, so the variants forward it\n// untyped via the rest and it lands here — absent on direct setup calls, and\n// passed straight through to the rules (which don't read it yet).\nexport function setupTrackSwitching<\n S extends SelectionKey,\n T extends SwitchableTrack,\n C extends TrackSwitchingConfig<S, T>,\n>(deps: { state: TrackSwitchingStateMap<S>; context?: AnySlotMap; config: C }) {\n const { state, config } = deps;\n const { selectionKey, getTracks, rules, resolveSelection = selectChainHead } = config;\n\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n // The playable candidate set — the tracks the rule chain gets to pick from,\n // derived *outside* the reaction. The hard-constraints pre-pass (capability\n // probing, CDN-failover cooldown) narrows the type's tracks before the chain\n // runs. Because this is a `computed`, a constraint's own signal reads (e.g.\n // `cdnHealth`) are tracked here, so when the playable set changes — a new\n // source, or a *dynamic* constraint like a CDN entering cooldown — the effect\n // re-picks. With no constraints configured this is just the type's tracks\n // while a presentation is resolved.\n //\n // The `equals` gates notification on the *set of track ids*, not array\n // identity: a live playlist refresh swaps in a new presentation object with\n // the same variant tracks, and a constraint's inputs can churn without\n // changing which tracks survive. In both cases the playable set is unchanged,\n // so the reaction must not re-fire (the rule chain still re-runs on its own\n // inputs — bandwidth, user selection). Same intent as `equalsById`, for the\n // track list.\n const candidateSet = computed<readonly T[]>(\n () => {\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return [];\n return applyConstraints(config.constraints ?? [], getTracks(presentation), deps);\n },\n { equals: (a, b) => a.length === b.length && a.every((track) => b.some((other) => other.id === track.id)) }\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // Canonical cleanup-binds-to-setup: the selection signal's valid\n // lifespan is exactly 'presentation-resolved'. Clear fires on exit,\n // covering both src unload and behavior destroy.\n entry: () => () => state[selectionKey].set(undefined),\n effects: [\n () => {\n // Reactive read: subscribes the reaction to the candidate set, so a\n // new presentation — or a constraint pruning it — re-fires this and\n // re-picks.\n const tracks = candidateSet.get();\n\n // Empty candidate set — two shapes, told apart by whether the type\n // has any tracks at all:\n // - The type has no tracks (e.g. a video-only source's absent\n // audio): legitimate, nothing to pick or clear.\n // - The type HAS tracks but the hard-constraints pre-pass pruned\n // every one (every rendition undecodable, or every CDN in\n // failover cooldown): no playable rendition. Clear the selection\n // so a pick made earlier — e.g. under the initial mp4 label,\n // before resolve-track relabeled the type to a non-fMP4\n // container — can't linger as a now-unplayable selection and\n // silently stall the pipeline.\n // The `console.error` is a placeholder until the planned error\n // behaviors surface \"nothing playable\" as observable state.\n if (!tracks.length) {\n const presentation = peek(state.presentation);\n const hasTracksOfType = isResolvedPresentation(presentation) && getTracks(presentation).length > 0;\n if (hasTracksOfType) {\n console.error(\n `[track-switching] every ${selectionKey} candidate was filtered out by constraints; clearing selection`\n );\n state[selectionKey].set(undefined);\n }\n return;\n }\n\n // The whole deps object passes straight through to every rule in the\n // variant-supplied chain (state + config from the behavior; context\n // threaded in by the variant's rest-spread). Typed against the base\n // config — each rule re-declares the extra fields it reads as\n // optional, and the concrete `C` is assignable to the base.\n const candidates = applyRules<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>(\n rules,\n tracks,\n deps\n );\n\n // applyRules early-bails to a single survivor and never narrows to\n // nothing (a soft filter that would empty the set falls through), so\n // the pick is just the head. An empty result means a rule misbehaved\n // — applyRules is supposed to account for those cases, so surface it.\n if (!candidates.length) {\n console.error('[track-switching] applyRules returned no candidates');\n return;\n }\n // Map survivors to the final id. Defaults to the chain head; a\n // variant with optional selection (text) may resolve to `undefined`,\n // which clears the slot (e.g. explicit off, opt-in decline).\n // No change-guard needed: the slot uses default (Object.is) equality,\n // so re-setting the same value is a no-op (no notify, no re-fire).\n state[selectionKey].set(resolveSelection(candidates, deps));\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Variant: switchVideoTrack — bandwidth-driven ABR\n// ============================================================================\n\n/**\n * Manage `selectedVideoTrackId`: pick a default on src load, dynamically\n * adjust based on bandwidth, clear on src unload. Honors\n * `userVideoTrackSelection` as a partial-track constraint on candidates;\n * short-circuits ABR when the constraint narrows to a single track.\n *\n * @example\n * const reactor = switchVideoTrack.setup({ state });\n */\nexport const switchVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedVideoTrackId'>;\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedVideoTrackId',\n userSelectionKey: 'userVideoTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'video') as readonly VideoTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks],\n rules: [filterByUserSelection, preferActiveCdn, rankByBandwidth],\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchAudioTrack — bandwidth-ranked (shared ranker)\n// ============================================================================\n\n/**\n * Manage `selectedAudioTrackId`: pick a default on src load, narrow by\n * `userAudioTrackSelection` filter, re-pick on filter change, clear on\n * src unload.\n *\n * Mid-stream flush on language switch is handled by the segment-loader's\n * `planTasks` (see `playback/actors/dom/segment-loader.ts`) — not this\n * behavior. Same split as the video pipeline: slot owner writes; loader\n * orchestrates segment + flush plans.\n *\n * @example\n * const reactor = switchAudioTrack.setup({ state });\n */\nexport const switchAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedAudioTrackId'>;\n // Shares the video config shape so the engine config spreads through (CDN\n // derivation + any future cross-cutting fields).\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n // Spread engine config so cross-cutting fields (`getCdnId`, future shared\n // tuning) flow through like they do for video, then override the per-type\n // wiring. Video-only ABR tuning (`quality`/`bandwidth`/`initialBandwidth`)\n // rides along into the shared `rankByBandwidth` too; harmless since audio\n // has no `bandwidthState` to act on it and the ranker always yields a pick.\n // FOLLOW-UP: a shared config type for the genuinely cross-cutting fields\n // would keep video-only tuning out of audio entirely (CJP).\n ...config,\n selectionKey: 'selectedAudioTrackId',\n userSelectionKey: 'userAudioTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'audio') as readonly AudioTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks],\n rules: [filterByUserSelection, preferActiveCdn, rankByBandwidth],\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchTextTrack — intent-resolved, optional selection\n// ============================================================================\n\n/**\n * Config for `switchTextTrack` — the opt-in default policy\n * (`preferredSubtitleLanguage` / `includeForcedTracks` / `enableDefaultTrack`,\n * via `TextSelectionConfig`) read by the terminal when the user has no standing\n * intent, plus the `getCdnId` override shared with the CDN constraint + scope.\n */\nexport interface SwitchTextTrackConfig extends TextSelectionConfig {\n /** Override CDN-id derivation (shared by the failed-CDN constraint + active-CDN scope). */\n getCdnId?: GetCdnId;\n}\n\n/**\n * Manage `selectedTextTrackId` as the single-writer **output** of standing user\n * intent (`userTextTrackSelection`) resolved against the playable, CDN-scoped\n * text renditions: clear on src unload; re-resolve when a CDN fails or recovers.\n *\n * Unlike video/audio, the selection is *optional* — captions are opt-in and the\n * user can turn them off — so the chain skips the bandwidth ranker and the shared\n * user-selection filter, and supplies a text-specific terminal\n * (`pickResolvedTextTrack`) that may resolve to no-selection via\n * `setupTrackSwitching`'s `resolveSelection` seam. Constraints are failed-CDN only\n * (`excludeUnplayableTracks`/`canPlayTrack` is MSE-based — the wrong probe for\n * text, whose playability is SPF-parser support); the active-CDN scope co-locates\n * captions with the surviving CDN on failover.\n *\n * @example\n * const reactor = switchTextTrack.setup({ state, config: { preferredSubtitleLanguage: 'en' } });\n */\nexport const switchTextTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedTextTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedTextTrackId'>;\n config?: SwitchTextTrackConfig;\n }) =>\n // Explicit type args pin the candidate type to `TextTrackCandidate`. Video and\n // audio let it infer to the `SwitchableTrack` constraint (harmless — every\n // rule is assignable up to it), but the text terminal needs the narrower type\n // (it reads text-only fields), so it's named here rather than inferred.\n setupTrackSwitching<'selectedTextTrackId', TextTrackCandidate, TextTerminalConfig & SwitchTextTrackConfig>({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedTextTrackId',\n getTracks: (presentation) => getTracksByType(presentation, 'text') as readonly TextTrackCandidate[],\n constraints: [excludeFailedCdns],\n rules: [preferActiveCdn],\n resolveSelection: pickResolvedTextTrack,\n },\n }),\n});\n"],"mappings":"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"}
|
|
1
|
+
{"version":3,"file":"track-switching.js","names":["getCdnId","defaultGetCdnId"],"sources":["../../../../src/playback/behaviors/track-switching.ts"],"sourcesContent":["/**\n * **Per-type track selection as a rule chain.** While a presentation is\n * resolved, owns that type's `selected{Video,Audio,Text}TrackId` signal: pick a\n * default, react to user intent and algorithmic ranking, and clear it on src\n * unload.\n *\n * Selection runs in two stages. First a **hard-constraints pre-pass**\n * (`applyConstraints`) prunes the unplayable from the candidate set — the\n * failed-CDN constraint (`excludeFailedCdns`, failover cooldown) and the\n * capability constraint (`excludeUnplayableTracks`, codec support). Then a small\n * ordered chain of rules (`applyRules`) picks among the survivors. Each constraint/rule reads the signals it needs at apply\n * time, so the effect subscribes to exactly what was consulted. The chain is\n * three rules, most authoritative first:\n *\n * 1. **user intent** — a soft filter on `user*TrackSelection`: narrow to the\n * partial-track match; an empty match falls through to the full set.\n * 2. **active CDN** — a soft filter on `cdnPriority` (`preferActiveCdn`):\n * narrow to the highest-priority CDN that still has tracks; an empty match\n * falls through. Shared by video and audio, so every type stays on one CDN\n * (`deriveCdnPriority` owns the list). No-op for non-redundant sources.\n * 3. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and\n * audio. Fitting tracks (within the throughput threshold) first, highest\n * bitrate first; over-throughput tracks after, least-over first. Hysteresis\n * via boosting the current track's sort weight by `upgradeMargin`.\n *\n * The composer's early-bail (one survivor → stop) is load-bearing: a user\n * selection that narrows to a single track is the pick without the ranker\n * running, so the bandwidth estimate is never read and the effect doesn't\n * re-fire on bandwidth while that choice holds.\n *\n * Lifecycle: `'presentation-unresolved'` ↔ `'presentation-resolved'`. The\n * resolved state owns the signal; its entry-returned cleanup clears it on exit\n * (canonical cleanup-binds-to-setup per `reactors.md`).\n *\n * The pick is the chain's result mapped to a slot value by `resolveSelection`\n * (default: the head, `applyRules(...)[0]`). Each variant supplies its\n * **constraints + rule chain (+ optional resolveSelection)** via config;\n * `setupTrackSwitching` owns only the lifecycle and runs what it's given. Video\n * and audio run constraints `[excludeFailedCdns, excludeUnplayableTracks]` then\n * rules `[filterByUserSelection, preferActiveCdn, rankByBandwidth]` and take the\n * head; `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack`\n * takes none. `switchTextTrack` differs — selection is *optional* (captions are\n * opt-in / off-able), so it runs `[excludeFailedCdns]` + `[preferActiveCdn]` and\n * supplies a text terminal (`pickResolvedTextTrack`) that resolves standing user\n * intent (`userTextTrackSelection`, incl. `'off'`) and may yield no selection.\n * (The active-CDN *scope* is the sticky-pick half of multi-CDN; the failed-CDN\n * *constraint* is the failover half — prune the cooled-down CDN, the scope falls\n * to the next.)\n *\n * When the pre-pass prunes a type that *has* tracks to empty, the behavior\n * clears the selection (so a now-unplayable pick can't linger and stall) and\n * reports the type's `noSupportedTrackCode`. Which constraint emptied the set is\n * deliberately not consulted — the behavior reads no constraint's state, so the\n * chain stays composable. A type with no tracks at all is left alone; that's a\n * legitimate source shape, not a failure. The late `createSourceBuffer` check\n * stays as the structural backstop.\n *\n * Deferred: audio's preferred-language / default-track selection as standing\n * soft-filter rules (previously the empty-slot picker, dropped in the move to\n * the rule chain).\n */\n\nimport { type AnySlotMap, defineBehavior } from '../../core/composition/create-composition';\nimport { createMachineReactor } from '../../core/reactors/create-machine-reactor';\nimport { computed, peek, type ReadonlySignal, type Signal } from '../../core/signals/primitives';\nimport { DEFAULT_QUALITY_CONFIG, type QualityConfig, resolutionArea } from '../../media/abr/quality-selection';\nimport { SVTA_NO_SUPPORTED_AUDIO_TRACK, SVTA_NO_SUPPORTED_VIDEO_TRACK } from '../../media/errors';\nimport {\n matchesPartialTrack,\n pickTextTrackFromTracks,\n type TextSelectionConfig,\n} from '../../media/primitives/select-tracks';\nimport {\n type AudioTrack,\n type CanPlayTrack,\n isResolvedPresentation,\n type MaybeResolvedPresentation,\n type PartiallyResolvedAudioTrack,\n type PartiallyResolvedTextTrack,\n type PartiallyResolvedVideoTrack,\n type TextTrack,\n type VideoTrack,\n} from '../../media/types';\nimport { getCdnId as defaultGetCdnId, type GetCdnId } from '../../media/utils/cdn';\nimport { getTracksByType } from '../../media/utils/tracks';\nimport type { BandwidthConfig, BandwidthState } from '../../network/bandwidth-estimator';\nimport { DEFAULT_BANDWIDTH_CONFIG, getBandwidthEstimate } from '../../network/bandwidth-estimator';\nimport { type ErrorEmitterState, emitError } from './collect-errors';\n\n// ============================================================================\n// State + Config\n// ============================================================================\n\n/**\n * The slots `setupTrackSwitching` itself owns: the `presentation` gate it reads\n * and the per-type `selected*TrackId` it writes. Rule-only inputs are\n * deliberately absent — `user*TrackSelection` and `bandwidthState` belong to\n * whoever materializes them (the embedder via `shareSignals`, the buffer-actor\n * sampler), and each rule declares the signal it consults as an optional slot\n * on its own deps map, so the behavior never assumes a rule's signal exists.\n */\nexport interface TrackSwitchingState {\n presentation?: MaybeResolvedPresentation;\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n}\n\n/**\n * Config for `switchVideoTrack` — the ABR tuning read by its ranker rule\n * (`rankByBandwidth`). `quality.safetyMargin` is the bandwidth-headroom\n * multiplier; `quality.upgradeMargin` the hysteresis ratio gating upgrades;\n * `bandwidth` tunes the estimator; `initialBandwidth` is the pre-sample\n * fallback. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15),\n * `DEFAULT_BANDWIDTH_CONFIG`, `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\nexport interface SwitchVideoTrackConfig {\n quality?: Partial<QualityConfig>;\n bandwidth?: Partial<BandwidthConfig>;\n initialBandwidth?: number;\n /** Override CDN-id derivation (shared by the CDN scope + failover constraint). */\n getCdnId?: GetCdnId;\n /**\n * Codec capability probe read by the `excludeUnplayableTracks` hard\n * constraint — drops renditions this environment can't decode before\n * selection runs. Injected (rather than imported) so the DOM-free behavior\n * never reaches a DOM API directly; the engine defaults it to the\n * `MediaSource.isTypeSupported`-backed `canPlayTrack`. Absent → no codec\n * filtering (the constraint passes everything through).\n */\n canPlayTrack?: CanPlayTrack;\n}\n\n/** Default initial-bandwidth value before bandwidth measurements arrive. */\nexport const DEFAULT_INITIAL_BANDWIDTH = 5_000_000;\n\n// ============================================================================\n// Rule chain\n// ============================================================================\n\n/**\n * Deps handed to each rule and to `applyRules`, mirroring a behavior's setup\n * deps so a rule reads from the same surfaces a behavior does. `context` is\n * optional — it's threaded through but absent on direct setup calls (and\n * unread by today's rules), so the whole deps object can pass straight through.\n */\nexport interface SelectionRuleDeps<State = unknown, Context = unknown, Config = unknown> {\n state: State;\n context?: Context;\n config: Config;\n}\n\n/**\n * A selection rule narrows or reorders the candidate list. It reads the state,\n * context, and config it needs at apply time (tightly-coupled reads), so a\n * rule's `.get()`s subscribe the running effect to exactly what it consulted.\n * Returning an empty list means \"no match\" — the composer skips it, so a soft\n * filter never narrows the set to nothing. A ranker returns the list with its\n * pick at the head.\n */\nexport type SelectionRule<T, State = unknown, Context = unknown, Config = unknown> = (\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => readonly T[];\n\n/**\n * Apply rules to a candidate list in order; the pick is the first survivor.\n * Two responsibilities the rules don't carry: a rule that returns nothing is\n * skipped (fall-through — a preference never empties the set), and once one\n * survivor remains the chain stops (early-bail — later rules, including the\n * bandwidth ranker, never run, so the effect doesn't subscribe to their\n * signals while the choice is fixed).\n *\n * @param rules - Rules to apply, most authoritative first\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed through to each rule\n * @returns The surviving candidates, pick first\n */\nexport function applyRules<T, State, Context, Config>(\n rules: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const rule of rules) {\n const remaining = rule(current, deps);\n if (remaining.length === 0) continue;\n current = remaining;\n if (current.length === 1) break;\n }\n return current;\n}\n\n/**\n * Apply hard constraints to a candidate list — the pre-pass that runs before the\n * rule chain. A constraint shares a rule's signature but its exclusion is\n * *hard*: it removes the unplayable (a codec the environment can't decode, a CDN\n * in failover cooldown) and a removed track is never attempted. Unlike\n * `applyRules`, this never skips an empty result and never early-bails — every\n * constraint always applies, and an empty survivor set is a real outcome\n * (\"nothing playable here\"), not a fall-through. Because each constraint only\n * removes, the order they run in can't change the result.\n *\n * @param constraints - Constraints to apply (pooled, order-independent)\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed to each constraint\n * @returns The playable survivors (possibly empty)\n */\nexport function applyConstraints<T, State, Context, Config>(\n constraints: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const constraint of constraints) current = constraint(current, deps);\n return current;\n}\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackSwitching` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => Reactor`. Each `switchXTrack` export below calls\n// it from inside its own `defineBehavior` setup. Its generics — `S` (selection\n// slot key), `T` (candidate track type), `C` (the concrete config the variant\n// builds) — all infer from the passed `state` + `config`, so the variants need\n// no explicit type arguments. `C extends TrackSwitchingConfig<S, T>` lets the\n// variant's richer config (rule-specific fields included) flow through the\n// helper untouched; the rules read those fields off their own config views.\n//\n// -- Design note: why narrow `SelectionKey` / `UserSelectionKey` unions ----\n// Goal we did not reach: have callers \"fully pass in\" the slot keys, with\n// the helper enforcing zero internal knowledge of which literals are valid.\n// What blocks it: indexing a mapped-type intersection by a generic key.\n// When `S extends keyof TrackSwitchingState` (or `string`), TS conservatively\n// treats `state[selectionKey]` as the union of every possible match across\n// the intersected mapped portions — including the fixed-key signal\n// (`presentation`) — and widens to their value-type union.\n// The sibling pattern hits the same constraint and answers it the same way:\n// `SelectedTrackKey` in `select-tracks.ts` is a hardcoded narrow union for\n// the same reason.\n//\n// Current pick is the narrow-union route because it matches siblings and\n// the unions read as documentation (\"these are the slots this helper\n// manages\") rather than restriction. Extending to a new track-switching\n// axis is one literal per union.\n// --------------------------------------------------------------------------\n// ============================================================================\n\n/**\n * Minimum candidate-track shape consumed by the helper and its rules: an `id`\n * (the pick), a `url` (the active-CDN scope derives the CDN from it), an\n * optional `bandwidth` (the ranker's throughput sort), and optional\n * `width`/`height` (the ranker's equal-bitrate tie-break — absent on audio, so\n * audio candidates area-compare equal). Every resolved/partially-resolved video\n * track carries them all; audio tracks omit the dimensions.\n */\ntype SwitchableTrack = {\n id: string;\n url: string;\n bandwidth?: number;\n width?: number;\n height?: number;\n // Read by the capability constraint to probe codec support. Optional on the\n // minimal shape; every resolved/partially-resolved video & audio candidate\n // carries them, and an absent `mimeType` makes a track unprobeable (kept).\n mimeType?: string;\n codecs?: string[];\n};\n\n/**\n * Map the rule chain's surviving candidates to the final selection id, or\n * `undefined` for a deliberate no-selection. Defaults to the chain head\n * (`selectChainHead`) — the always-pick contract video and audio rely on\n * (`applyRules` guarantees a non-empty result, so the head is always there). A\n * variant whose selection is legitimately optional (text: opt-in captions,\n * explicit off) supplies its own picker that may return `undefined`; the helper\n * writes that straight through to the slot, clearing it.\n */\nexport type ResolveSelection<T extends SwitchableTrack, State = unknown, Context = unknown, Config = unknown> = (\n candidates: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => string | undefined;\n\ntype SelectionKey = 'selectedVideoTrackId' | 'selectedAudioTrackId' | 'selectedTextTrackId';\ntype UserSelectionKey = 'userVideoTrackSelection' | 'userAudioTrackSelection';\n\n// Each mapped value references `P` so TS keeps the per-key dependency and\n// resolves `state[selectionKey]` to the right arm. `T` (track type) stays out\n// of the state map (it flows through `TrackSwitchingConfig` instead).\n//\n// Only the behavior's own lifecycle signals are required here: the presentation\n// gate and the selection slot it writes. Signals a *rule* reads but the\n// behavior doesn't — `user*TrackSelection` (the user-selection filter) and\n// `bandwidthState` (the bandwidth ranker) — are NOT here; each rule declares\n// the signal it needs as *optional* on its own deps and reads it defensively,\n// so the behavior never assumes a rule-only signal exists. Those slots are\n// materialized by whoever owns them: `shareSignals` for the consumer-input\n// `user*TrackSelection`, the buffer-actor sampler for `bandwidthState`.\nexport type TrackSwitchingStateMap<S extends SelectionKey> = {\n presentation: ReadonlySignal<TrackSwitchingState['presentation']>;\n} & { [P in S]: Signal<TrackSwitchingState[P]> };\n\n/**\n * The lifecycle map plus the *optional* `errors` slot reporters append to. Owned\n * by `collectErrors`; optional so a composition without it still type-checks and\n * emission no-ops. The behavior reads no constraint's state — see\n * `noSupportedTrackCode`.\n */\ntype TrackSwitchingReporterStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & ErrorEmitterState;\n\n/**\n * Config `setupTrackSwitching` itself reads — its own wiring: which selection\n * slot to write and clear (`selectionKey`), how to enumerate candidate tracks\n * (`getTracks`), the optional **hard-constraints pre-pass** (`constraints`,\n * applied before the chain to prune the unplayable), and the **rule chain** to\n * run (`rules`), and how to map the chain's survivors to the final pick\n * (`resolveSelection`, defaulting to the chain head). Rule-/constraint-specific\n * config is deliberately absent — each declares the fields it reads as *optional*\n * on its own config view (`UserSelectionConfig`, `BandwidthRankerConfig`), so the\n * behavior never enumerates them. The variant builds the concrete config as this\n * base plus whatever its chain consults; it flows through untouched as the `C`\n * type param on `setupTrackSwitching`.\n */\ninterface TrackSwitchingConfig<S extends SelectionKey, T extends SwitchableTrack> {\n selectionKey: S;\n getTracks: (presentation: MaybeResolvedPresentation) => readonly T[];\n constraints?: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n rules: readonly SelectionRule<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>[];\n /**\n * Map the chain's surviving candidates to the final selection id. Optional —\n * absent means the chain head (`selectChainHead`), the always-pick path video\n * and audio use. A variant with optional selection (text) supplies one that\n * may return `undefined`.\n */\n resolveSelection?: ResolveSelection<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>;\n /**\n * SVTA code to report when this type *has* tracks but the constraints pruned\n * every one. Per-variant because the condition isn't universally an error:\n * video and audio supply {@link SVTA_NO_SUPPORTED_VIDEO_TRACK} /\n * {@link SVTA_NO_SUPPORTED_AUDIO_TRACK}, while text supplies none — an\n * unavailable subtitle track is a legitimate outcome, not a playback failure.\n * Absent → the selection still clears, nothing is reported.\n */\n noSupportedTrackCode?: number;\n}\n\n/**\n * State the user-selection filter reads: the lifecycle map plus an *optional*\n * user-selection slot (keyed by `U`), holding a partial-track description to\n * match against the candidates (`Partial<T>` — `{ id }`, `{ language }`,\n * `{ height }`, …). The slot exists only when the composition provides it\n * (materialized by `shareSignals`); the filter reads it defensively and no-ops\n * when it's absent (no user override).\n */\ntype UserSelectionStateMap<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingStateMap<S> & {\n [P in U]?: ReadonlySignal<Partial<T> | undefined>;\n};\n\n/**\n * Config the user-selection filter reads: `userSelectionKey` names the state\n * slot holding the user's selection. *Optional* on the rule's view — the base\n * config doesn't carry it, so an unwired key means \"no user selection\" and the\n * filter passes through. The variants always supply it.\n */\ntype UserSelectionConfig<\n S extends SelectionKey,\n U extends UserSelectionKey,\n T extends SwitchableTrack,\n> = TrackSwitchingConfig<S, T> & { userSelectionKey?: U };\n\n/**\n * State the bandwidth ranker reads: the lifecycle map plus an *optional*\n * `bandwidthState`. The signal exists only when the composition includes a\n * bandwidth sampler; the ranker reads it defensively and falls back to\n * `initialBandwidth` (with a debug note) when it's absent.\n */\ntype BandwidthRankerStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n bandwidthState?: ReadonlySignal<BandwidthState | undefined>;\n};\n\n/**\n * Config the bandwidth ranker reads: the ABR tuning in `SwitchVideoTrackConfig`\n * (`quality` / `bandwidth` / `initialBandwidth`), all optional with defaults.\n */\ntype BandwidthRankerConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> &\n SwitchVideoTrackConfig;\n\n/**\n * State the active-CDN scope reads: the lifecycle map plus an *optional*\n * `cdnPriority` — the manifest-ordered CDN list (most-preferred first). The\n * signal exists only when the composition includes `deriveCdnPriority` (which\n * materializes + owns it); the scope reads it defensively and passes through\n * when it's absent (no CDN preference).\n */\ntype CdnScopeStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n cdnPriority?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * State the failed-CDN constraint reads: the lifecycle map plus an *optional*\n * `failedCdns` — the CDN ids currently in failover cooldown. The signal exists\n * only when the composition includes a failover monitor (or an external driver); the\n * constraint reads it defensively and excludes nothing when it's absent.\n */\ntype CdnConstraintStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n failedCdns?: ReadonlySignal<string[] | undefined>;\n};\n\n/**\n * Config the CDN rules read: the base config plus an *optional* `getCdnId`\n * override. Both `excludeFailedCdns` and `preferActiveCdn` derive a track's CDN\n * from its URL; the override must be the *same* one `deriveCdnPriority` and the\n * failover trip use, or the keys stop matching. Optional → defaults to the\n * origin-based `getCdnId`, so the base config (without it) stays assignable.\n */\ntype CdnRuleConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> & {\n getCdnId?: GetCdnId;\n};\n\n/**\n * Config the capability constraint reads: the base config plus an *optional*\n * `canPlayTrack` codec probe. Optional → an unwired probe means \"no codec\n * filtering\" and the constraint passes everything through, so the base config\n * (without it) stays assignable. The engine defaults it to the DOM-bound\n * `canPlayTrack`.\n */\ntype CapabilityConstraintConfig<S extends SelectionKey, T extends SwitchableTrack> = TrackSwitchingConfig<S, T> & {\n canPlayTrack?: CanPlayTrack;\n};\n\ntype VideoTrackCandidate = PartiallyResolvedVideoTrack | VideoTrack;\ntype AudioTrackCandidate = PartiallyResolvedAudioTrack | AudioTrack;\ntype TextTrackCandidate = PartiallyResolvedTextTrack | TextTrack;\n\n// ----------------------------------------------------------------------------\n// Rules — defined outside the behavior closure, parameterized only by their\n// deps. Each is generic over the slot keys + track type; the variant's\n// concrete keys instantiate it where the chain is assembled.\n// ----------------------------------------------------------------------------\n\n/**\n * User intent — a soft filter. Narrows to tracks matching the partial-track\n * selection in `user*TrackSelection`; an empty match falls through (the\n * composer skips it) to the unfiltered set — e.g. a stale id from a previous\n * source.\n */\nfunction filterByUserSelection<S extends SelectionKey, U extends UserSelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<UserSelectionStateMap<S, U, T>, AnySlotMap, UserSelectionConfig<S, U, T>>\n): readonly T[] {\n const key = config.userSelectionKey;\n if (!key) return tracks;\n const filter = state[key]?.get();\n return filter ? tracks.filter((track) => matchesPartialTrack(track, filter)) : tracks;\n}\n\n/**\n * Failed-CDN constraint — a *hard* filter (constraints pre-pass), shared by\n * video and audio. Removes tracks served from a CDN currently in failover\n * cooldown (`failedCdns`, written by the failover monitor). Removed tracks are never\n * attempted; the scope then narrows to the next surviving CDN in `cdnPriority`,\n * and snaps back to the primary once it leaves cooldown.\n *\n * Passes everything through when there's no `failedCdns` signal/value. When it\n * prunes *every* track (all CDNs cooled down), the empty result is preserved\n * (per `applyConstraints`) — \"nothing playable,\" which clears the selection (no\n * pick); a later CDN recovery refills the candidate set and re-picks.\n */\nfunction excludeFailedCdns<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnConstraintStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const failed = state.failedCdns?.get();\n if (!failed?.length) return tracks;\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n const failedSet = new Set(failed);\n return tracks.filter((track) => !failedSet.has(getCdnId(track.url)));\n}\n\n/**\n * Capability constraint — a *hard* filter (constraints pre-pass), shared by\n * video and audio. Removes renditions this environment can't decode, probed via\n * the injected `canPlayTrack` (codec → `MediaSource.isTypeSupported`). Moving\n * the check here — before selection — means an unplayable variant (e.g. HEVC on\n * a browser without HEVC) is pruned upstream and never picked, instead of\n * surviving into the pipeline to fail late at `createSourceBuffer`. That late\n * throw stays as a defensive structural guarantee; with this constraint it\n * should rarely fire.\n *\n * Passes everything through when there's no `canPlayTrack` probe (a composition\n * that didn't wire it, or DOM-free tests). When it prunes *every* track (no\n * decodable rendition), the empty result is preserved (per `applyConstraints`)\n * — \"nothing playable,\" so the behavior clears the selection (no pick) and the\n * late `createSourceBuffer` check stays as the backstop.\n */\nfunction excludeUnplayableTracks<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { config }: SelectionRuleDeps<TrackSwitchingStateMap<S>, AnySlotMap, CapabilityConstraintConfig<S, T>>\n): readonly T[] {\n const canPlay = config.canPlayTrack;\n if (!canPlay) return tracks;\n return tracks.filter((track) => canPlay(track));\n}\n\n/**\n * Active-CDN scope — a soft filter, shared by video and audio. Narrows to the\n * highest-priority CDN in `cdnPriority` (owned by `deriveCdnPriority`) that\n * still has tracks, so every track type stays on one CDN. A redundant-streams\n * source lists the same renditions on multiple hosts; this keeps the pick on one\n * host rather than letting the ranker drift across them.\n *\n * \"Active\" is derived, not stored: constraints run before the rule chain, so a\n * failed CDN's tracks are already pruned by the time this runs — \"first CDN with\n * survivors\" *is* the active CDN, and it falls through to the next on failover\n * (and snaps back to the primary when it recovers). Content steering reorders\n * `cdnPriority`; this rule just honors the order.\n *\n * Soft-filter semantics: passes through when there's no `cdnPriority` signal/value\n * (no preference) or when nothing matches (`applyRules` skips an empty result).\n * Non-redundant sources have one CDN, so the narrow is a no-op.\n *\n * The CDN-id derivation defaults to origin-based `getCdnId`, overridable via the\n * `getCdnId` config — it must match the one `deriveCdnPriority` used to build\n * `cdnPriority`, or no track's CDN would ever equal an entry.\n */\nfunction preferActiveCdn<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<CdnScopeStateMap<S>, AnySlotMap, CdnRuleConfig<S, T>>\n): readonly T[] {\n const cdnPriority = state.cdnPriority?.get();\n if (!cdnPriority?.length) return tracks;\n const getCdnId = config.getCdnId ?? defaultGetCdnId;\n for (const cdn of cdnPriority) {\n const tracksUsingCdn = tracks.filter((track) => getCdnId(track.url) === cdn);\n if (tracksUsingCdn.length) return tracksUsingCdn;\n }\n return tracks;\n}\n\n/**\n * Bandwidth ranking — the terminal sort, shared by video and audio. Orders by\n * the throughput estimate: tracks within the bandwidth threshold first\n * (fitting), highest bitrate first; then over-threshold tracks, least-over\n * first. The head is the best-quality track that fits, falling back to the\n * smallest over-throughput track when nothing fits.\n *\n * Hysteresis without temporal state: the current track's effective bitrate is\n * boosted by `upgradeMargin` in the fitting sort, so a higher track only\n * outranks it once it clears `current.bitrate * upgradeMargin` (no flapping on\n * marginal bandwidth gains). Downgrades fall out for free — a current track\n * over the threshold isn't in the fitting set to be boosted, so the best fit (a\n * downgrade) wins immediately. Equal-bitrate tracks break by resolution (higher\n * `width × height` first), so an equal-bitrate ladder never picks a lower-\n * quality rendition by manifest order; audio tracks carry no dimensions, so\n * they area-compare equal and a stable sort keeps their candidate order (e.g.\n * same-bitrate language variants). Early-bail skips this rule when a prior one\n * narrowed to a single track, so the estimate is neither read nor subscribed\n * while that holds.\n */\nfunction rankByBandwidth<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state, config }: SelectionRuleDeps<BandwidthRankerStateMap<S>, AnySlotMap, BandwidthRankerConfig<S, T>>\n): readonly T[] {\n const safetyMargin = config.quality?.safetyMargin ?? DEFAULT_QUALITY_CONFIG.safetyMargin;\n const upgradeMargin = config.quality?.upgradeMargin ?? DEFAULT_QUALITY_CONFIG.upgradeMargin;\n const initialBandwidth = config.initialBandwidth ?? DEFAULT_INITIAL_BANDWIDTH;\n const bandwidthConfig: BandwidthConfig = { ...DEFAULT_BANDWIDTH_CONFIG, ...config.bandwidth };\n if (!state.bandwidthState) {\n console.debug(\n '[track-switching] rankByBandwidth: no bandwidthState signal in composition; ranking on initialBandwidth'\n );\n }\n const threshold = getBandwidthEstimate(state.bandwidthState?.get(), initialBandwidth, bandwidthConfig) * safetyMargin;\n const currentId = state[config.selectionKey].get();\n const bitrate = (track: T) => track.bandwidth ?? 0;\n // Boost the current track's sort weight by upgradeMargin (fitting set only) so\n // an upgrade must clear current.bitrate * upgradeMargin to outrank it.\n const rank = (track: T) => (track.id === currentId ? bitrate(track) * upgradeMargin : bitrate(track));\n // Equal bitrate → prefer higher resolution (width × height), so an\n // equal-bitrate ladder doesn't pick a lower-quality rendition by manifest\n // order. Audio tracks carry no dimensions, so they area-compare equal and\n // keep candidate order (stable sort).\n const fitting = tracks\n .filter((track) => bitrate(track) <= threshold)\n .sort((a, b) => rank(b) - rank(a) || resolutionArea(b) - resolutionArea(a));\n const over = tracks\n .filter((track) => bitrate(track) > threshold)\n .sort((a, b) => bitrate(a) - bitrate(b) || resolutionArea(b) - resolutionArea(a));\n return [...fitting, ...over];\n}\n\n/**\n * Default final pick: the chain head. `applyRules` never narrows to nothing and\n * early-bails to a single survivor, so video and audio always converge to a\n * track and the head is the pick.\n */\nfunction selectChainHead<T extends SwitchableTrack>(candidates: readonly T[]): string {\n return candidates[0]!.id;\n}\n\n/**\n * State the text terminal reads: the lifecycle map plus an *optional*\n * `userTextTrackSelection` — the standing user intent. `Partial<TextTrack>` is an\n * explicit pick (language-based), `'off'` is explicit no-captions, `undefined` is\n * auto (no preference). The slot exists only when the composition materializes it\n * (`shareSignals`); the terminal reads it defensively and treats absence as auto.\n *\n * Unlike `user*TrackSelection` for video/audio, this carries the `'off'` sentinel\n * and feeds the terminal pick (not the shared `filterByUserSelection`) — text is\n * the only type whose selection is legitimately optional, so the off/auto logic\n * lives in one text-specific place rather than widening the shared filter.\n */\ntype TextSelectionStateMap = TrackSwitchingStateMap<'selectedTextTrackId'> & {\n userTextTrackSelection?: ReadonlySignal<Partial<TextTrack> | 'off' | undefined>;\n};\n\n/** Config the text terminal reads: the base config plus the opt-in default policy. */\ntype TextTerminalConfig = TrackSwitchingConfig<'selectedTextTrackId', TextTrackCandidate> & TextSelectionConfig;\n\n/**\n * Terminal pick for text — the `resolveSelection` the text variant supplies.\n * Resolves the standing `userTextTrackSelection` intent against the chain's\n * survivors (already CDN-failover-pruned and active-CDN-scoped):\n *\n * - `'off'` → no selection (clear the slot). Sticky through re-evaluation, so a\n * live refresh or failover re-run can't re-assert a default.\n * - explicit `Partial<TextTrack>` → narrow to the match (language-based). A\n * stale pick whose match is gone (e.g. the language dropped on a source\n * change) falls through to the default policy.\n * - auto (`undefined`) → the opt-in default policy (`preferredSubtitleLanguage`\n * → `DEFAULT=YES + AUTOSELECT=YES` → none), shared with `pickTextTrack`.\n *\n * Returning `undefined` is a real outcome (captions are opt-in), which is why the\n * text variant relies on `setupTrackSwitching`'s no-selection seam.\n */\nfunction pickResolvedTextTrack<T extends TextTrackCandidate>(\n candidates: readonly T[],\n { state, config }: SelectionRuleDeps<TextSelectionStateMap, AnySlotMap, TextTerminalConfig>\n): string | undefined {\n const intent = state.userTextTrackSelection?.get();\n if (intent === 'off') return undefined;\n if (intent) {\n // The stored intent is a `Partial<TextTrack>`; cast to the candidate's own\n // partial shape so the generic `matchesPartialTrack` accepts it (every field\n // it carries — language, forced — exists on the candidate too).\n const matched = candidates.filter((track) => matchesPartialTrack(track, intent as Partial<T>));\n if (matched.length) return matched[0]!.id;\n }\n return pickTextTrackFromTracks(candidates, config);\n}\n\n// `context` is the composition's context map, threaded in by each variant's\n// rest-spread and typed as the generic slot-map shape (`AnySlotMap`). It can't\n// be a typed param on the `defineBehavior` setup without widening `ContextMap`\n// to its constraint and forcing the slot required, so the variants forward it\n// untyped via the rest and it lands here — absent on direct setup calls, and\n// passed straight through to the rules (which don't read it yet).\nexport function setupTrackSwitching<\n S extends SelectionKey,\n T extends SwitchableTrack,\n C extends TrackSwitchingConfig<S, T>,\n>(deps: { state: TrackSwitchingReporterStateMap<S>; context?: AnySlotMap; config: C }) {\n const { state, config } = deps;\n const { selectionKey, getTracks, rules, resolveSelection = selectChainHead, noSupportedTrackCode } = config;\n\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n // The playable candidate set — the tracks the rule chain gets to pick from,\n // derived *outside* the reaction. The hard-constraints pre-pass (capability\n // probing, CDN-failover cooldown) narrows the type's tracks before the chain\n // runs. Because this is a `computed`, a constraint's own signal reads (e.g.\n // `cdnHealth`) are tracked here, so when the playable set changes — a new\n // source, or a *dynamic* constraint like a CDN entering cooldown — the effect\n // re-picks. With no constraints configured this is just the type's tracks\n // while a presentation is resolved.\n //\n // The `equals` gates notification on the *set of track ids*, not array\n // identity: a live playlist refresh swaps in a new presentation object with\n // the same variant tracks, and a constraint's inputs can churn without\n // changing which tracks survive. In both cases the playable set is unchanged,\n // so the reaction must not re-fire (the rule chain still re-runs on its own\n // inputs — bandwidth, user selection). Same intent as `equalsById`, for the\n // track list.\n const candidateSet = computed<readonly T[]>(\n () => {\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return [];\n return applyConstraints(config.constraints ?? [], getTracks(presentation), deps);\n },\n { equals: (a, b) => a.length === b.length && a.every((track) => b.some((other) => other.id === track.id)) }\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // Canonical cleanup-binds-to-setup: the selection signal's valid\n // lifespan is exactly 'presentation-resolved'. Clear fires on exit,\n // covering both src unload and behavior destroy.\n entry: () => () => state[selectionKey].set(undefined),\n effects: [\n () => {\n // Reactive read: subscribes the reaction to the candidate set, so a\n // new presentation — or a constraint pruning it — re-fires this and\n // re-picks.\n const tracks = candidateSet.get();\n\n // Empty candidate set — two shapes, told apart by whether the type\n // has any tracks at all:\n // - The type has no tracks (e.g. a video-only source's absent\n // audio): legitimate, nothing to pick or clear.\n // - The type HAS tracks but the hard-constraints pre-pass pruned\n // every one (every rendition undecodable, or every CDN in\n // failover cooldown): no playable rendition. Clear the selection\n // so a pick made earlier — e.g. under the initial mp4 label,\n // before resolve-track relabeled the type to a non-fMP4\n // container — can't linger as a now-unplayable selection and\n // silently stall the pipeline.\n if (!tracks.length) {\n const presentation = peek(state.presentation);\n const hasTracksOfType = isResolvedPresentation(presentation) && getTracks(presentation).length > 0;\n if (hasTracksOfType) {\n // Reported generically: *why* the set emptied is the constraints'\n // business, not this behavior's, so no constraint's state is read\n // here and no cause is distinguished. Whatever the reason, a type\n // that has renditions but none selectable can't play — a codec\n // this environment can't decode, or every CDN failed, which is\n // itself fatal-or-nearly so. Finer causes (container vs codec)\n // would need `CanPlayTrack` to report a reason; see\n // `internal/design/spf/features/errors.md`.\n if (noSupportedTrackCode !== undefined) {\n emitError(state, { code: noSupportedTrackCode, data: { selectionKey } });\n }\n state[selectionKey].set(undefined);\n }\n return;\n }\n\n // The whole deps object passes straight through to every rule in the\n // variant-supplied chain (state + config from the behavior; context\n // threaded in by the variant's rest-spread). Typed against the base\n // config — each rule re-declares the extra fields it reads as\n // optional, and the concrete `C` is assignable to the base.\n const candidates = applyRules<T, TrackSwitchingStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>(\n rules,\n tracks,\n deps\n );\n\n // applyRules early-bails to a single survivor and never narrows to\n // nothing (a soft filter that would empty the set falls through), so\n // the pick is just the head. An empty result means a rule misbehaved\n // — applyRules is supposed to account for those cases, so surface it.\n if (!candidates.length) {\n console.error('[track-switching] applyRules returned no candidates');\n return;\n }\n // Map survivors to the final id. Defaults to the chain head; a\n // variant with optional selection (text) may resolve to `undefined`,\n // which clears the slot (e.g. explicit off, opt-in decline).\n // No change-guard needed: the slot uses default (Object.is) equality,\n // so re-setting the same value is a no-op (no notify, no re-fire).\n state[selectionKey].set(resolveSelection(candidates, deps));\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Variant: switchVideoTrack — bandwidth-driven ABR\n// ============================================================================\n\n/**\n * Manage `selectedVideoTrackId`: pick a default on src load, dynamically\n * adjust based on bandwidth, clear on src unload. Honors\n * `userVideoTrackSelection` as a partial-track constraint on candidates;\n * short-circuits ABR when the constraint narrows to a single track.\n *\n * @example\n * const reactor = switchVideoTrack.setup({ state });\n */\nexport const switchVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedVideoTrackId'>;\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedVideoTrackId',\n userSelectionKey: 'userVideoTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'video') as readonly VideoTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks],\n rules: [filterByUserSelection, preferActiveCdn, rankByBandwidth],\n noSupportedTrackCode: SVTA_NO_SUPPORTED_VIDEO_TRACK,\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchAudioTrack — bandwidth-ranked (shared ranker)\n// ============================================================================\n\n/**\n * Manage `selectedAudioTrackId`: pick a default on src load, narrow by\n * `userAudioTrackSelection` filter, re-pick on filter change, clear on\n * src unload.\n *\n * Mid-stream flush on language switch is handled by the segment-loader's\n * `planTasks` (see `playback/actors/dom/segment-loader.ts`) — not this\n * behavior. Same split as the video pipeline: slot owner writes; loader\n * orchestrates segment + flush plans.\n *\n * @example\n * const reactor = switchAudioTrack.setup({ state });\n */\nexport const switchAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedAudioTrackId'>;\n // Shares the video config shape so the engine config spreads through (CDN\n // derivation + any future cross-cutting fields).\n config?: SwitchVideoTrackConfig;\n }) =>\n setupTrackSwitching({\n ...otherProps,\n state,\n config: {\n // Spread engine config so cross-cutting fields (`getCdnId`, future shared\n // tuning) flow through like they do for video, then override the per-type\n // wiring. Video-only ABR tuning (`quality`/`bandwidth`/`initialBandwidth`)\n // rides along into the shared `rankByBandwidth` too; harmless since audio\n // has no `bandwidthState` to act on it and the ranker always yields a pick.\n // FOLLOW-UP: a shared config type for the genuinely cross-cutting fields\n // would keep video-only tuning out of audio entirely (CJP).\n ...config,\n selectionKey: 'selectedAudioTrackId',\n userSelectionKey: 'userAudioTrackSelection',\n getTracks: (presentation) => getTracksByType(presentation, 'audio') as readonly AudioTrackCandidate[],\n constraints: [excludeFailedCdns, excludeUnplayableTracks],\n rules: [filterByUserSelection, preferActiveCdn, rankByBandwidth],\n noSupportedTrackCode: SVTA_NO_SUPPORTED_AUDIO_TRACK,\n },\n }),\n});\n\n// ============================================================================\n// Variant: switchTextTrack — intent-resolved, optional selection\n// ============================================================================\n\n/**\n * Config for `switchTextTrack` — the opt-in default policy\n * (`preferredSubtitleLanguage` / `includeForcedTracks` / `enableDefaultTrack`,\n * via `TextSelectionConfig`) read by the terminal when the user has no standing\n * intent, plus the `getCdnId` override shared with the CDN constraint + scope.\n */\nexport interface SwitchTextTrackConfig extends TextSelectionConfig {\n /** Override CDN-id derivation (shared by the failed-CDN constraint + active-CDN scope). */\n getCdnId?: GetCdnId;\n}\n\n/**\n * Manage `selectedTextTrackId` as the single-writer **output** of standing user\n * intent (`userTextTrackSelection`) resolved against the playable, CDN-scoped\n * text renditions: clear on src unload; re-resolve when a CDN fails or recovers.\n *\n * Unlike video/audio, the selection is *optional* — captions are opt-in and the\n * user can turn them off — so the chain skips the bandwidth ranker and the shared\n * user-selection filter, and supplies a text-specific terminal\n * (`pickResolvedTextTrack`) that may resolve to no-selection via\n * `setupTrackSwitching`'s `resolveSelection` seam. Constraints are failed-CDN only\n * (`excludeUnplayableTracks`/`canPlayTrack` is MSE-based — the wrong probe for\n * text, whose playability is SPF-parser support); the active-CDN scope co-locates\n * captions with the surviving CDN on failover.\n *\n * @example\n * const reactor = switchTextTrack.setup({ state, config: { preferredSubtitleLanguage: 'en' } });\n */\nexport const switchTextTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedTextTrackId'],\n contextKeys: [],\n setup: ({\n state,\n config,\n ...otherProps\n }: {\n state: TrackSwitchingStateMap<'selectedTextTrackId'>;\n config?: SwitchTextTrackConfig;\n }) =>\n // Explicit type args pin the candidate type to `TextTrackCandidate`. Video and\n // audio let it infer to the `SwitchableTrack` constraint (harmless — every\n // rule is assignable up to it), but the text terminal needs the narrower type\n // (it reads text-only fields), so it's named here rather than inferred.\n setupTrackSwitching<'selectedTextTrackId', TextTrackCandidate, TextTerminalConfig & SwitchTextTrackConfig>({\n ...otherProps,\n state,\n config: {\n ...config,\n selectionKey: 'selectedTextTrackId',\n getTracks: (presentation) => getTracksByType(presentation, 'text') as readonly TextTrackCandidate[],\n constraints: [excludeFailedCdns],\n rules: [preferActiveCdn],\n resolveSelection: pickResolvedTextTrack,\n },\n }),\n});\n"],"mappings":"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"}
|
|
@@ -9,6 +9,7 @@ import { canPlayTrack } from "../../../media/dom/capabilities.js";
|
|
|
9
9
|
import { parseMultivariantPlaylist } from "../../../media/hls/parse-multivariant.js";
|
|
10
10
|
import { getResolvedSelectedTrackDuration } from "../../../media/utils/track-selection.js";
|
|
11
11
|
import { calculatePresentationDuration } from "../../behaviors/calculate-presentation-duration.js";
|
|
12
|
+
import { collectErrors } from "../../behaviors/collect-errors.js";
|
|
12
13
|
import { deriveCdnPriority } from "../../behaviors/derive-cdn-priority.js";
|
|
13
14
|
import { setupAirPlay } from "../../behaviors/dom/airplay.js";
|
|
14
15
|
import { applyStartPosition } from "../../behaviors/dom/apply-start-position.js";
|
|
@@ -23,12 +24,13 @@ import { setupFailoverMonitor } from "../../behaviors/setup-failover-monitor.js"
|
|
|
23
24
|
import { syncPreload } from "../../behaviors/sync-preload.js";
|
|
24
25
|
import { switchAudioTrack } from "../../behaviors/track-switching.js";
|
|
25
26
|
import { relocationPipelinesFor } from "../../primitives/relocation-pipelines.js";
|
|
27
|
+
import { reportUnsupportedTrackConditions } from "../../primitives/report-track-conditions.js";
|
|
26
28
|
//#region src/playback/engines/hls/engine-audio-only.ts
|
|
27
29
|
const shareSignals = makeShareSignals(["userAudioTrackSelection", "disableRemotePlayback"]);
|
|
28
30
|
/**
|
|
29
31
|
* Create an audio-only HLS playback engine.
|
|
30
32
|
*
|
|
31
|
-
* Subtractive composition variant of `
|
|
33
|
+
* Subtractive composition variant of `createHlsVideoEngine`: omits
|
|
32
34
|
* video-side behaviors (`resolveVideoTrack`, `switchVideoTrack`,
|
|
33
35
|
* `setupVideoBufferActors`, `loadVideoSegments`) and text-track behaviors
|
|
34
36
|
* (`switchTextTrack`, `resolveTextTrack`, `syncTextTracks`,
|
|
@@ -43,8 +45,8 @@ const shareSignals = makeShareSignals(["userAudioTrackSelection", "disableRemote
|
|
|
43
45
|
*
|
|
44
46
|
* @example
|
|
45
47
|
* ```ts
|
|
46
|
-
* let signals:
|
|
47
|
-
* const engine =
|
|
48
|
+
* let signals: HlsAudioEngineSignals;
|
|
49
|
+
* const engine = createHlsAudioEngine({
|
|
48
50
|
* preferredAudioLanguage: 'en',
|
|
49
51
|
* onSignalsReady: (refs) => {
|
|
50
52
|
* signals = refs;
|
|
@@ -55,13 +57,14 @@ const shareSignals = makeShareSignals(["userAudioTrackSelection", "disableRemote
|
|
|
55
57
|
* signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });
|
|
56
58
|
* ```
|
|
57
59
|
*/
|
|
58
|
-
function
|
|
60
|
+
function createHlsAudioEngine(config = {}) {
|
|
59
61
|
const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;
|
|
60
62
|
const finalConfig = {
|
|
61
63
|
...config,
|
|
62
64
|
deriveStartMediaTime,
|
|
63
65
|
attachMediaSource: attachMediaSourceAsSourceElement,
|
|
64
66
|
canPlayTrack: config.canPlayTrack ?? canPlayTrack,
|
|
67
|
+
reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,
|
|
65
68
|
resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,
|
|
66
69
|
parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,
|
|
67
70
|
audioMessagePipelines: relocationPipelinesFor("audio", deriveStartMediaTime)
|
|
@@ -72,6 +75,7 @@ function createHlsAudioOnlyEngine(config = {}) {
|
|
|
72
75
|
resolvePresentation,
|
|
73
76
|
deriveCdnPriority,
|
|
74
77
|
setupFailoverMonitor,
|
|
78
|
+
collectErrors,
|
|
75
79
|
switchAudioTrack,
|
|
76
80
|
resolveAudioTrack,
|
|
77
81
|
calculatePresentationDuration,
|
|
@@ -89,6 +93,6 @@ function createHlsAudioOnlyEngine(config = {}) {
|
|
|
89
93
|
], { config: finalConfig });
|
|
90
94
|
}
|
|
91
95
|
//#endregion
|
|
92
|
-
export {
|
|
96
|
+
export { createHlsAudioEngine };
|
|
93
97
|
|
|
94
98
|
//# sourceMappingURL=engine-audio-only.js.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine-audio-only.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine-audio-only.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 { 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 { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport type { AudioTrack, CanPlayTrack, MaybeResolvedPresentation, MediaContainerData } from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\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 } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { setupAudioBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\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// `audioMessagePipelines` finalConfig entry, the `mediaContainerData` state slot,\n// and the `deriveStartMediaTime` config field to drop relocation from audio-only.\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 } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack } from '../../behaviors/track-switching';\nimport { relocationPipelinesFor } from '../../primitives/relocation-pipelines';\n\n// ============================================================================\n// Audio-Only HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the audio-only HLS playback engine.\n *\n * Subset of `SimpleHlsEngineState` covering only the slots written and read\n * by audio-side behaviors. Video and text-track slots are absent —\n * subtractive composition removes the behaviors that declare them.\n */\nexport interface SimpleHlsAudioOnlyEngineState {\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedAudioTrackId?: string;\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 /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection` in the default engine. Partial-track\n * shape — `{ language: 'es' }`, `{ id: 'audio-en' }`, etc.\n * `selectAudioTrack` reads this and re-picks when it changes.\n * Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * The CDNs the source is served from, in manifest priority order (mirrors\n * HLS content steering's `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`,\n * read by `track-switching`'s `preferActiveCdn` scope. Only meaningful for\n * redundant-stream sources; a single-CDN source has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids currently in failover cooldown — read by `track-switching`'s\n * `excludeFailedCdns` constraint, which prunes their tracks so the active-CDN\n * scope falls to the next CDN. Empty / absent 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 `loadAudioSegments`\n * (parks in `'dormant'`) and by `setupMediaSource` (a pending rebuild\n * waits). See `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 media\n * element's own `disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the audio-only HLS playback engine.\n *\n * Subset of `SimpleHlsEngineContext` covering only the platform objects and\n * actor refs managed by audio-side behaviors.\n */\nexport interface SimpleHlsAudioOnlyEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n audioBufferActor?: SourceBufferActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n}\n\nexport type SimpleHlsAudioOnlyEngineSignals = {\n state: StateSignals<SimpleHlsAudioOnlyEngineState>;\n context: ContextSignals<SimpleHlsAudioOnlyEngineContext>;\n};\n\n/**\n * Configuration for the audio-only HLS playback engine.\n *\n * Subset of `SimpleHlsEngineConfig` — video-quality, bandwidth-estimator,\n * and text-track config fields are omitted (no behavior consumes them).\n */\nexport interface SimpleHlsAudioOnlyEngineConfig\n extends ShareSignalsConfig<SimpleHlsAudioOnlyEngineState, SimpleHlsAudioOnlyEngineContext> {\n preferredAudioLanguage?: string;\n /**\n * Codec capability probe read by `track-switching`'s `excludeUnplayableTracks`\n * constraint. Defaults to the `MediaSource.isTypeSupported`-backed\n * `canPlayTrack`; override to force-exclude a codec. Mirrors the default\n * engine — without it, capability probing (and TS / raw-AAC detection) would\n * be inert for audio-only playback.\n */\n canPlayTrack?: CanPlayTrack;\n resolveDuration?: PresentationDurationResolver;\n parsePresentation?: ParsePresentation;\n forwardBuffer?: Partial<ForwardBufferConfig>;\n backBuffer?: Partial<BackBufferConfig>;\n /** Multi-CDN failover monitor tuning. Defaults: `DEFAULT_FAILOVER_MONITOR_CONFIG`. */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * Derive a CDN grouping key from a track URL (used by `cdnPriority`, the\n * failover trip, and the track-switching CDN rules — one function read by all).\n * Defaults to the URL origin; override to key on e.g. Mux's `cdn=` param.\n */\n getCdnId?: GetCdnId;\n /** Non-zero-PTS relocation (spike): the reduce seam (tier knob); defaults to per-track own. */\n deriveStartMediaTime?: DeriveStartMediaTime;\n}\n\n// ============================================================================\n// Audio-Only HLS Playback Engine\n// ============================================================================\n\n// Materializes input slots no composed behavior produces — `userAudioTrackSelection`\n// (switchAudioTrack only reads it) and `disableRemotePlayback` (setupAirPlay only\n// reads it) — in addition to forwarding refs. `failedCdns` is owned by\n// `setupFailoverMonitor`, so it's already materialized and reachable on the\n// `onSignalsReady` refs without being listed here.\nconst shareSignals = makeShareSignals<SimpleHlsAudioOnlyEngineState, SimpleHlsAudioOnlyEngineContext>([\n 'userAudioTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an audio-only HLS playback engine.\n *\n * Subtractive composition variant of `createSimpleHlsEngine`: omits\n * video-side behaviors (`resolveVideoTrack`, `switchVideoTrack`,\n * `setupVideoBufferActors`, `loadVideoSegments`) and text-track behaviors\n * (`switchTextTrack`, `resolveTextTrack`, `syncTextTracks`,\n * `setupTextTrackActors`, `loadTextTrackSegments`). The remaining audio\n * pipeline composes unchanged.\n *\n * Handles both truly audio-only HLS sources (no video stream-inf) and\n * mixed-AV HLS sources where the audio rendition is selected and video /\n * subtitle renditions are ignored at composition time. The variant decision\n * is encoded by adapter choice; this engine does not branch on source\n * shape.\n *\n * @example\n * ```ts\n * let signals: SimpleHlsAudioOnlyEngineSignals;\n * const engine = createHlsAudioOnlyEngine({\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(audioEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n * ```\n */\nexport function createHlsAudioOnlyEngine(\n config: SimpleHlsAudioOnlyEngineConfig = {}\n): Composition<SimpleHlsAudioOnlyEngineState, SimpleHlsAudioOnlyEngineContext> {\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. The helper's\n // `video/mp4` source type is inert here — resource selection probes it\n // with `canPlayType`, which answers `'maybe'` on an audio element too.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n // Non-zero-PTS relocation (spike): pair the audio loader with the relocation steps\n // `establishStartMediaTime` derives from; same `deriveStartMediaTime` seam. Remove\n // with the reactor.\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`; switchAudioTrack's preferActiveCdn scope reads it. No-op\n // for single-CDN sources.\n //\n // With a single track type there's no cross-type coherence to enforce and\n // the first pick is the primary CDN regardless, so composition order is\n // not load-bearing here today. It earns its place for forward-consistency\n // with the default engine and for future failover / steering, where the\n // active CDN changes dynamically (and selection stays reactive either way).\n deriveCdnPriority,\n\n // CDN failover cooldown: watches `failedCdns` (tripped directly by audio\n // track resolution on a failed media-playlist fetch) and removes each CDN\n // once its cooldown lapses.\n setupFailoverMonitor,\n\n // Audio track selection — slot owner with filter reactivity.\n // Mid-stream flush on language switch is handled in segment-loader's\n // planTasks, not here.\n switchAudioTrack,\n\n // Resolve selected tracks — audio only.\n resolveAudioTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Single audio buffer; no video buffer to coordinate with,\n // so the Firefox `mozHasAudio` registration ordering is moot here.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // Non-zero-PTS relocation (spike): establishes per-track startMediaTime;\n // MUST precede setupAudioBufferActors. Remove this line + the import + the\n // finalConfig/state entries to drop relocation. (Selection is optional in the\n // reactor, so it works with only audio in scope.)\n establishStartMediaTime,\n\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere). Audio-only sources\n // AirPlay to audio receivers (HomePod, AirPlay speakers) through the same\n // native-HLS fallback `<source>`; `webkitCurrentPlaybackTargetIsWireless`\n // and the picker are HTMLMediaElement-level, so an `<audio>` host is\n // AirPlay-capable on the same terms as a `<video>` one.\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\n // Segment loading — audio only.\n loadAudioSegments,\n\n // End of stream coordination. `endOfStream` iterates buffer actors via\n // `[videoBufferActor, audioBufferActor].filter(Boolean)` and reads\n // `mediaSource.sourceBuffers` aggregately — composes unchanged with\n // only audio in scope.\n endOfStream,\n // Force native `ended` if Chrome freezes the playhead short of the buffered end\n // after `endOfStream`. Inert for a clean-ending single-track source.\n recoverEndStall,\n\n // Adapter signal callback.\n shareSignals,\n ],\n {\n config: finalConfig,\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA+KA,MAAM,eAAe,iBAAiF,CACpG,2BACA,uBACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCD,SAAgB,yBACd,SAAyC,CAAC,GACmC;CAC7E,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAMA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAI/C,uBAAuB,uBAAuB,SAAS,oBAAoB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAWA;EAKA;EAKA;EAGA;EAGA;EAIA;EACA;EAMA;EAEA;EAOA;EAGA;EAGA;EAGA;EAMA;EAGA;EAGA;CACF,GACA,EACE,QAAQ,YACV,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"engine-audio-only.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine-audio-only.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 { 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 type { SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport type { AudioTrack, CanPlayTrack, MaybeResolvedPresentation, MediaContainerData } from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\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 } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { setupAudioBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\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// `audioMessagePipelines` finalConfig entry, the `mediaContainerData` state slot,\n// and the `deriveStartMediaTime` config field to drop relocation from audio-only.\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 } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack } from '../../behaviors/track-switching';\nimport { relocationPipelinesFor } from '../../primitives/relocation-pipelines';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\n\n// ============================================================================\n// Audio-Only HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the audio-only HLS playback engine.\n *\n * Subset of `HlsVideoEngineState` covering only the slots written and read\n * by audio-side behaviors. Video and text-track slots are absent —\n * subtractive composition removes the behaviors that declare them.\n */\nexport interface HlsAudioEngineState {\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedAudioTrackId?: string;\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 /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection` in the default engine. Partial-track\n * shape — `{ language: 'es' }`, `{ id: 'audio-en' }`, etc.\n * `selectAudioTrack` reads this and re-picks when it changes.\n * Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * The CDNs the source is served from, in manifest priority order (mirrors\n * HLS content steering's `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`,\n * read by `track-switching`'s `preferActiveCdn` scope. Only meaningful for\n * redundant-stream sources; a single-CDN source has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids currently in failover cooldown — read by `track-switching`'s\n * `excludeFailedCdns` constraint, which prunes their tracks so the active-CDN\n * scope falls to the next CDN. Empty / absent means all CDNs are eligible.\n */\n failedCdns?: string[];\n /**\n * Conditions reported during playback, in order — appended by whichever\n * behavior detects one, owned and cleared per source by `collectErrors`.\n * Severity is decided above the engine. Audio-only makes an all-audio-pruned\n * source unrecoverable: there's no video fallback to fall back to.\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 `loadAudioSegments`\n * (parks in `'dormant'`) and by `setupMediaSource` (a pending rebuild\n * waits). See `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 media\n * element's own `disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the audio-only HLS playback engine.\n *\n * Subset of `HlsVideoEngineContext` covering only the platform objects and\n * actor refs managed by audio-side behaviors.\n */\nexport interface HlsAudioEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n audioBufferActor?: SourceBufferActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n}\n\nexport type HlsAudioEngineSignals = {\n state: StateSignals<HlsAudioEngineState>;\n context: ContextSignals<HlsAudioEngineContext>;\n};\n\n/**\n * Configuration for the audio-only HLS playback engine.\n *\n * Subset of `HlsVideoEngineConfig` — video-quality, bandwidth-estimator,\n * and text-track config fields are omitted (no behavior consumes them).\n */\nexport interface HlsAudioEngineConfig extends ShareSignalsConfig<HlsAudioEngineState, HlsAudioEngineContext> {\n preferredAudioLanguage?: string;\n /**\n * Codec capability probe read by `track-switching`'s `excludeUnplayableTracks`\n * constraint. Defaults to the `MediaSource.isTypeSupported`-backed\n * `canPlayTrack`; override to force-exclude a codec. Mirrors the default\n * engine — without it, capability probing (and TS / raw-AAC detection) would\n * be inert for audio-only playback.\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 resolveDuration?: PresentationDurationResolver;\n parsePresentation?: ParsePresentation;\n forwardBuffer?: Partial<ForwardBufferConfig>;\n backBuffer?: Partial<BackBufferConfig>;\n /** Multi-CDN failover monitor tuning. Defaults: `DEFAULT_FAILOVER_MONITOR_CONFIG`. */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * Derive a CDN grouping key from a track URL (used by `cdnPriority`, the\n * failover trip, and the track-switching CDN rules — one function read by all).\n * Defaults to the URL origin; override to key on e.g. Mux's `cdn=` param.\n */\n getCdnId?: GetCdnId;\n /** Non-zero-PTS relocation (spike): the reduce seam (tier knob); defaults to per-track own. */\n deriveStartMediaTime?: DeriveStartMediaTime;\n}\n\n// ============================================================================\n// Audio-Only HLS Playback Engine\n// ============================================================================\n\n// Materializes input slots no composed behavior produces — `userAudioTrackSelection`\n// (switchAudioTrack only reads it) and `disableRemotePlayback` (setupAirPlay only\n// reads it) — in addition to forwarding refs. `failedCdns` is owned by\n// `setupFailoverMonitor`, so it's already materialized and reachable on the\n// `onSignalsReady` refs without being listed here.\nconst shareSignals = makeShareSignals<HlsAudioEngineState, HlsAudioEngineContext>([\n 'userAudioTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an audio-only HLS playback engine.\n *\n * Subtractive composition variant of `createHlsVideoEngine`: omits\n * video-side behaviors (`resolveVideoTrack`, `switchVideoTrack`,\n * `setupVideoBufferActors`, `loadVideoSegments`) and text-track behaviors\n * (`switchTextTrack`, `resolveTextTrack`, `syncTextTracks`,\n * `setupTextTrackActors`, `loadTextTrackSegments`). The remaining audio\n * pipeline composes unchanged.\n *\n * Handles both truly audio-only HLS sources (no video stream-inf) and\n * mixed-AV HLS sources where the audio rendition is selected and video /\n * subtitle renditions are ignored at composition time. The variant decision\n * is encoded by adapter choice; this engine does not branch on source\n * shape.\n *\n * @example\n * ```ts\n * let signals: HlsAudioEngineSignals;\n * const engine = createHlsAudioEngine({\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(audioEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n * ```\n */\nexport function createHlsAudioEngine(\n config: HlsAudioEngineConfig = {}\n): Composition<HlsAudioEngineState, HlsAudioEngineContext> {\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. The helper's\n // `video/mp4` source type is inert here — resource selection probes it\n // with `canPlayType`, which answers `'maybe'` on an audio element too.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n // Non-zero-PTS relocation (spike): pair the audio loader with the relocation steps\n // `establishStartMediaTime` derives from; same `deriveStartMediaTime` seam. Remove\n // with the reactor.\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`; switchAudioTrack's preferActiveCdn scope reads it. No-op\n // for single-CDN sources.\n //\n // With a single track type there's no cross-type coherence to enforce and\n // the first pick is the primary CDN regardless, so composition order is\n // not load-bearing here today. It earns its place for forward-consistency\n // with the default engine and for future failover / steering, where the\n // active CDN changes dynamically (and selection stays reactive either way).\n deriveCdnPriority,\n\n // CDN failover cooldown: watches `failedCdns` (tripped directly by audio\n // track resolution on a failed media-playlist fetch) and removes each CDN\n // once its cooldown lapses.\n setupFailoverMonitor,\n\n // Owns `errors` and its per-source lifecycle; reporters append into it.\n collectErrors,\n\n // Audio track selection — slot owner with filter reactivity.\n // Mid-stream flush on language switch is handled in segment-loader's\n // planTasks, not here.\n switchAudioTrack,\n\n // Resolve selected tracks — audio only.\n resolveAudioTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Single audio buffer; no video buffer to coordinate with,\n // so the Firefox `mozHasAudio` registration ordering is moot here.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // Non-zero-PTS relocation (spike): establishes per-track startMediaTime;\n // MUST precede setupAudioBufferActors. Remove this line + the import + the\n // finalConfig/state entries to drop relocation. (Selection is optional in the\n // reactor, so it works with only audio in scope.)\n establishStartMediaTime,\n\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere). Audio-only sources\n // AirPlay to audio receivers (HomePod, AirPlay speakers) through the same\n // native-HLS fallback `<source>`; `webkitCurrentPlaybackTargetIsWireless`\n // and the picker are HTMLMediaElement-level, so an `<audio>` host is\n // AirPlay-capable on the same terms as a `<video>` one.\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\n // Segment loading — audio only.\n loadAudioSegments,\n\n // End of stream coordination. `endOfStream` iterates buffer actors via\n // `[videoBufferActor, audioBufferActor].filter(Boolean)` and reads\n // `mediaSource.sourceBuffers` aggregately — composes unchanged with\n // only audio in scope.\n endOfStream,\n // Force native `ended` if Chrome freezes the playhead short of the buffered end\n // after `endOfStream`. Inert for a clean-ending single-track source.\n recoverEndStall,\n\n // Adapter signal callback.\n shareSignals,\n ],\n {\n config: finalConfig,\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAmMA,MAAM,eAAe,iBAA6D,CAChF,2BACA,uBACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCD,SAAgB,qBACd,SAA+B,CAAC,GACyB;CACzD,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAMA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;EAC7E,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAI/C,uBAAuB,uBAAuB,SAAS,oBAAoB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAWA;EAKA;EAGA;EAKA;EAGA;EAGA;EAIA;EACA;EAMA;EAEA;EAOA;EAGA;EAGA;EAGA;EAMA;EAGA;EAGA;CACF,GACA,EACE,QAAQ,YACV,CACF;AACF"}
|
|
@@ -13,7 +13,7 @@ import { resolvePresentation } from "../../behaviors/resolve-presentation.js";
|
|
|
13
13
|
import { resolveVideoTrack } from "../../behaviors/resolve-track.js";
|
|
14
14
|
import { pickHighestResolutionVideoTrack } from "../../../media/primitives/select-tracks.js";
|
|
15
15
|
import { selectVideoTrack } from "../../behaviors/select-tracks.js";
|
|
16
|
-
//#region src/playback/engines/background-video
|
|
16
|
+
//#region src/playback/engines/hls/engine-background-video.ts
|
|
17
17
|
const shareSignals = makeShareSignals();
|
|
18
18
|
/**
|
|
19
19
|
* Create a background-video playback engine.
|
|
@@ -28,7 +28,7 @@ const shareSignals = makeShareSignals();
|
|
|
28
28
|
* surfaces that should start loading the moment a src is set.
|
|
29
29
|
*
|
|
30
30
|
* Native `loop` / `muted` / `autoplay` are adapter concerns and live on
|
|
31
|
-
* `
|
|
31
|
+
* `HlsBackgroundVideoMediaElement` rather than the engine.
|
|
32
32
|
*
|
|
33
33
|
* @example
|
|
34
34
|
* ```ts
|
|
@@ -72,4 +72,4 @@ function createBackgroundVideoEngine(config = {}) {
|
|
|
72
72
|
//#endregion
|
|
73
73
|
export { createBackgroundVideoEngine };
|
|
74
74
|
|
|
75
|
-
//# sourceMappingURL=engine.js.map
|
|
75
|
+
//# sourceMappingURL=engine-background-video.js.map
|