@videojs/spf 10.0.0-beta.29 → 10.0.0-beta.30
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/media/dom/screen.js +7 -24
- package/dist/default/media/dom/screen.js.map +1 -1
- package/dist/default/media/primitives/resolution.js +29 -0
- package/dist/default/media/primitives/resolution.js.map +1 -0
- package/dist/default/media/primitives/select-tracks.js +17 -1
- package/dist/default/media/primitives/select-tracks.js.map +1 -1
- package/dist/default/playback/adapters/hls-background-video/adapter.js +3 -3
- package/dist/default/playback/adapters/hls-background-video/adapter.js.map +1 -1
- package/dist/default/playback/behaviors/collect-errors.js +8 -8
- package/dist/default/playback/behaviors/collect-errors.js.map +1 -1
- package/dist/default/playback/behaviors/dom/track-player-resolution.js +57 -0
- package/dist/default/playback/behaviors/dom/track-player-resolution.js.map +1 -0
- package/dist/default/playback/behaviors/select-tracks.js.map +1 -1
- package/dist/default/playback/behaviors/track-switching.js +48 -6
- package/dist/default/playback/behaviors/track-switching.js.map +1 -1
- package/dist/default/playback/engines/hls/engine-background-video.js +1 -1
- package/dist/default/playback/engines/hls/engine-background-video.js.map +1 -1
- package/dist/default/playback/engines/hls/engine.js +2 -0
- package/dist/default/playback/engines/hls/engine.js.map +1 -1
- package/dist/default/playback/primitives/selection-rules.js +4 -3
- package/dist/default/playback/primitives/selection-rules.js.map +1 -1
- package/dist/dev/media/dom/screen.d.ts +2 -21
- package/dist/dev/media/dom/screen.d.ts.map +1 -1
- package/dist/dev/media/dom/screen.js +7 -24
- package/dist/dev/media/dom/screen.js.map +1 -1
- package/dist/dev/media/primitives/resolution.d.ts +24 -0
- package/dist/dev/media/primitives/resolution.d.ts.map +1 -0
- package/dist/dev/media/primitives/resolution.js +29 -0
- package/dist/dev/media/primitives/resolution.js.map +1 -0
- package/dist/dev/media/primitives/select-tracks.js +17 -1
- package/dist/dev/media/primitives/select-tracks.js.map +1 -1
- package/dist/dev/playback/adapters/hls-background-video/adapter.js +3 -3
- package/dist/dev/playback/adapters/hls-background-video/adapter.js.map +1 -1
- package/dist/dev/playback/behaviors/collect-errors.js +8 -8
- package/dist/dev/playback/behaviors/collect-errors.js.map +1 -1
- package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts +8 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts.map +1 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.js +57 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.js.map +1 -0
- package/dist/dev/playback/behaviors/select-tracks.d.ts.map +1 -1
- package/dist/dev/playback/behaviors/select-tracks.js.map +1 -1
- package/dist/dev/playback/behaviors/track-switching.js +48 -6
- package/dist/dev/playback/behaviors/track-switching.js.map +1 -1
- package/dist/dev/playback/engines/hls/engine-background-video.d.ts +3 -3
- package/dist/dev/playback/engines/hls/engine-background-video.js +1 -1
- package/dist/dev/playback/engines/hls/engine-background-video.js.map +1 -1
- package/dist/dev/playback/engines/hls/engine.d.ts +19 -0
- package/dist/dev/playback/engines/hls/engine.d.ts.map +1 -1
- package/dist/dev/playback/engines/hls/engine.js +2 -0
- package/dist/dev/playback/engines/hls/engine.js.map +1 -1
- package/dist/dev/playback/primitives/selection-rules.d.ts.map +1 -1
- package/dist/dev/playback/primitives/selection-rules.js +4 -3
- package/dist/dev/playback/primitives/selection-rules.js.map +1 -1
- package/package.json +3 -3
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"track-player-resolution.js","names":[],"sources":["../../../../../src/playback/behaviors/dom/track-player-resolution.ts"],"sourcesContent":["/**\n * Mirror the player element's rendered pixel dimensions into reactive state, so\n * a rendition cap can narrow candidates to what the element can actually show\n * without reading the DOM at pick time — which would make the picker impure, and\n * would never re-pick when the element resized.\n *\n * The player-element half of the caps in\n * `internal/design/spf/features/rendition-selection-caps.md`, and the tighter\n * half: a small embed on a large display is capped by its own box rather than by\n * the screen behind it (`trackScreenResolution`).\n *\n * Reported as a width and a height in device pixels — the same units, and for the\n * same reason, as `media/dom/screen`'s reading: the cap compares against real\n * track dimensions, and a `\"720p\"`-style tier only describes a track once you\n * assume its aspect ratio.\n *\n * `undefined` where there is nothing to measure — no element attached, or one\n * that isn't being rendered (detached, `display: none`, not yet laid out) — which\n * is the value the cap reads as \"don't cap\".\n */\n\nimport { type ElementSize, observeElementSize, observeRenderedSize } from '@videojs/utils/dom';\nimport { shallowEqual } from '@videojs/utils/object';\nimport { defineBehavior } from '../../../core/composition/create-composition';\nimport { effect } from '../../../core/signals/effect';\nimport type { ReadonlySignal, Signal } from '../../../core/signals/primitives';\nimport { type Resolution, scaleResolution } from '../../../media/primitives/resolution';\n\n/** A player element's rendered pixel dimensions. */\nexport type PlayerResolution = Resolution;\n\nexport interface PlayerResolutionState {\n playerResolution?: PlayerResolution;\n}\n\nexport interface PlayerResolutionContext {\n mediaElement?: HTMLMediaElement | undefined;\n}\n\nexport interface TrackPlayerResolutionConfig {\n /**\n * Whether to cap renditions to the player's rendered size at all. `false`\n * measures nothing, which leaves `state.playerResolution` unset and the cap\n * inert. Defaults to `true`.\n *\n * Named for the policy rather than the measurement because it is the public\n * switch for the feature — the same one hls.js spells `capLevelToPlayerSize`\n * and the Mux Video element spells `cap-rendition-to-player-size`.\n */\n capRenditionToPlayerSize?: boolean;\n /**\n * Whether the reading is scaled into device pixels. Defaults to `true` — see\n * `ScreenResolutionOptions.useDevicePixelRatio` in `media/dom/screen.ts`,\n * including its note on page zoom being folded into the ratio outside WebKit.\n */\n useDevicePixelRatio?: boolean;\n}\n\nfunction trackPlayerResolutionSetup({\n state,\n context,\n config = {},\n}: {\n state: { playerResolution: Signal<PlayerResolutionState['playerResolution']> };\n context: { mediaElement: ReadonlySignal<PlayerResolutionContext['mediaElement']> };\n config?: TrackPlayerResolutionConfig;\n}): () => void {\n const { capRenditionToPlayerSize = true, useDevicePixelRatio = true } = config;\n\n return effect(() => {\n const mediaElement = context.mediaElement.get();\n // Clear before (re-)observing so the previous element's measurement can't\n // stand while the new one's first observation is in flight.\n let current: PlayerResolution | undefined;\n state.playerResolution.set(current);\n if (!capRenditionToPlayerSize || !mediaElement) return;\n\n // Compared rather than written straight through, since the slot holds an\n // object and would otherwise notify on identity alone: a resize that rounds\n // to the same device pixels is not a change worth re-running selection for.\n // Same reason `watchScreenResolution` compares its readings.\n const write = (size: ElementSize & { scale?: number }) => {\n const next = scaleResolution(size, size.scale);\n if (shallowEqual(current, next)) return;\n\n current = next;\n state.playerResolution.set(next);\n };\n\n return useDevicePixelRatio ? observeRenderedSize(mediaElement, write) : observeElementSize(mediaElement, write);\n });\n}\n\n/**\n * Track the player element's rendered resolution in `state.playerResolution`.\n *\n * @example\n * const cleanup = trackPlayerResolution.setup({ state, context });\n */\nexport const trackPlayerResolution = defineBehavior({\n stateKeys: ['playerResolution'],\n contextKeys: ['mediaElement'],\n setup: trackPlayerResolutionSetup,\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;AA0DA,SAAS,2BAA2B,EAClC,OACA,SACA,SAAS,CAAC,KAKG;CACb,MAAM,EAAE,2BAA2B,MAAM,sBAAsB,SAAS;CAExE,OAAO,aAAa;EAClB,MAAM,eAAe,QAAQ,aAAa,IAAI;EAG9C,IAAI;EACJ,MAAM,iBAAiB,IAAI,OAAO;EAClC,IAAI,CAAC,4BAA4B,CAAC,cAAc;EAMhD,MAAM,SAAS,SAA2C;GACxD,MAAM,OAAO,gBAAgB,MAAM,KAAK,KAAK;GAC7C,IAAI,aAAa,SAAS,IAAI,GAAG;GAEjC,UAAU;GACV,MAAM,iBAAiB,IAAI,IAAI;EACjC;EAEA,OAAO,sBAAsB,oBAAoB,cAAc,KAAK,IAAI,mBAAmB,cAAc,KAAK;CAChH,CAAC;AACH;;;;;;;AAQA,MAAa,wBAAwB,eAAe;CAClD,WAAW,CAAC,kBAAkB;CAC9B,aAAa,CAAC,cAAc;CAC5B,OAAO;AACT,CAAC"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-tracks.d.ts","names":[],"sources":["../../../../src/playback/behaviors/select-tracks.ts"],"mappings":";;;;;
|
|
1
|
+
{"version":3,"file":"select-tracks.d.ts","names":[],"sources":["../../../../src/playback/behaviors/select-tracks.ts"],"mappings":";;;;;KA8FY,gBAAgB,UAAU,cAAc,mCAAmC;;KAGlF;EAAoB;;;;;;;;;;;;;;;;cA+JZ,yBAAyB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;cAyCzB,qBAAqB;;;;;;UAgBjB,+BAA+B;EAC9C,uBAAuB,gBAAgB;EACvC,iBAAiB,gBAAgB"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"select-tracks.js","names":[],"sources":["../../../../src/playback/behaviors/select-tracks.ts"],"sourcesContent":["/**\n * **Default audio/video track selection on src load / unselect on src unload.**\n * When a presentation is resolved, sets `selectedVideoTrackId` /\n * `selectedAudioTrackId` from a per-type default rule chain if no selection\n * already exists. When the presentation is unset/reset (transitions back to unresolved),\n * clears the selection so a stale id from the previous source doesn't persist.\n *\n * Lifecycle-driven: the pick fires once per transition, and nothing re-picks —\n * that is what separates these from the `switch*` variants. External writes (user\n * picks, ABR, programmatic filter-driven re-picks) are left alone, including a\n * write naming a track the manifest never offered.\n *\n * The one thing policed between transitions is a pick the *constraints* turn\n * against: a rendition's container and encryption are only known once its media\n * playlist resolves, which is after the pick was made, so a selection that becomes\n * unplayable is dropped. Dropped, never moved — re-picking is exactly the behavior\n * `switchVideoTrack` exists to provide. Dropping reports nothing on its own, since\n * whatever made the pick unplayable already reported its own, more specific cause.\n *\n * Selection runs the same rule model `switchVideoTrack` does — a hard\n * `constraints` pre-pass, then an ordered `rules` chain, with the pick as the\n * head (see `internal/design/spf/track-switching-model.md`). What differs is\n * reactivity, not the rules: this evaluates the chain once on resolve and pins\n * the result, where `switchVideoTrack` re-evaluates inside an effect so its rules\n * subscribe to bandwidth and user selection. A rule written for one therefore\n * composes into the other unchanged.\n *\n * Both are config-driven, each per-type export wiring a sensible default: audio's\n * three-tier language policy, and for video the *empty* chain — with nothing\n * narrowing or reordering, the head is the first candidate. The behavior's\n * `config` is forwarded to the rules, so options like `preferredAudioLanguage`\n * reach them without an intermediate layer.\n *\n * Note a rule can only pick among real candidates, where the picker it replaced\n * could return any id at all. An id absent from the manifest was never\n * selectable, so that narrowing is the point rather than a limitation.\n *\n * Compose `selectVideoTrack` for the simple \"pick a default video track\"\n * behavior, or `switchVideoTrack` (`./track-switching.ts`) for the\n * ABR-driven variant. Compose `selectAudioTrack` for the simple default\n * pick, or `switchAudioTrack` (`./track-switching.ts`) for the\n * filter-reactive + mid-stream-flush slot-owner variant — when audio-abr\n * lands, `switchAudioTrack` extends into `switchAudioQuality`. Compose\n * only one per type — they're alternatives, not stackable (each writes\n * the same `selected*TrackId` slot). The simple variants tree-shake out\n * the heavier machinery (bandwidth estimator, quality selection, flush\n * orchestration).\n *\n * Text selection has no simple variant here — it's owned by `switchTextTrack`\n * (`./track-switching.ts`), which resolves standing `userTextTrackSelection`\n * intent against the constrained, CDN-scoped renditions.\n */\n\nimport { 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 {\n type AudioSelectionConfig,\n byDescendingResolution,\n pickAudioTrackFromTracks,\n type TrackSelectionState,\n tracksUnderPixelArea,\n} from '../../media/primitives/select-tracks';\nimport { isResolvedPresentation, type TrackType } from '../../media/types';\nimport { getTracksByType } from '../../media/utils/tracks';\nimport {\n applyConstraints,\n applyRules,\n type CapabilityConstraintConfig,\n excludeUnplayableTracks,\n type SelectionRule,\n sameCandidateSet,\n} from '../primitives/selection-rules';\nimport { AUDIO_TYPE_CONFIG, VIDEO_TYPE_CONFIG } from '../primitives/track-types';\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackSelection` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => Reactor`. Each `selectXTrack` export below calls\n// it from inside its own `defineBehavior` setup, supplying its per-type\n// `selectedKey`, track type, default rule chain, and forwarded config. The lifecycle\n// — pick on entering 'presentation-resolved' if not already selected; clear\n// on entering 'presentation-unresolved' — is shared.\n// ============================================================================\n\ntype SelectedTrackKey = 'selectedVideoTrackId' | 'selectedAudioTrackId';\n\ntype SelectStateMap<K extends SelectedTrackKey> = {\n presentation: ReadonlySignal<TrackSelectionState['presentation']>;\n} & { [P in K]: Signal<TrackSelectionState[P]> };\n\n/** A selection rule over this behavior's candidate tracks. */\nexport type SelectTrackRule<Config> = SelectionRule<SelectableTrack, unknown, unknown, Config | undefined>;\n\n/** What a rule here needs off a candidate: the id it may become the pick by. */\ntype SelectableTrack = { id: string };\n\ninterface TrackSelectionSetupConfig<K extends SelectedTrackKey, RuleConfig> {\n selectedKey: K;\n trackType: TrackType;\n constraints: readonly SelectTrackRule<RuleConfig>[];\n rules: readonly SelectTrackRule<RuleConfig>[];\n ruleConfig?: RuleConfig;\n}\n\nfunction setupTrackSelection<K extends SelectedTrackKey, RuleConfig>({\n state,\n config: { selectedKey, trackType, constraints, rules, ruleConfig },\n}: {\n state: SelectStateMap<K>;\n config: TrackSelectionSetupConfig<K, RuleConfig>;\n}) {\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n const deps = { state, config: ruleConfig };\n\n // The playable candidate set — the type's tracks after the hard-constraints\n // pre-pass. A `computed` so it re-evaluates when its inputs change, which is what\n // lets a *pinned* selection still notice it has gone unplayable: `resolve-track`\n // relabels the whole type's container from the first resolved media playlist,\n // long after `entry` made its pick under the fMP4 default.\n //\n // The `equals` gates notification on the set of track ids rather than array\n // identity, matching `setupTrackSwitching`'s. Segment appends and live reloads\n // both swap in a new presentation object carrying the same variants; without\n // this the effect below would re-run on every one of them.\n const candidateSet = computed(\n () => {\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return [];\n return applyConstraints(constraints, getTracksByType(presentation, trackType), deps);\n },\n { equals: sameCandidateSet }\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // Entry: pick a default on entering presentation-resolved if none\n // is set. External writes (user picks, ABR) that already populated\n // the slot are left alone.\n //\n // The returned cleanup runs on state exit — which fires on src\n // unload (presentation-resolved → presentation-unresolved) AND on\n // behavior destroy (presentation-resolved → destroying →\n // destroyed). Putting the clear here rather than as\n // presentation-unresolved.entry is more cohesive (operation +\n // cleanup co-located) and correctly covers destroy (destroy\n // doesn't pass through presentation-unresolved).\n entry: () => {\n if (!state[selectedKey].get()) {\n // `state.presentation.get()` is non-null inside this entry —\n // the reactor's `'presentation-resolved'` gate is exactly\n // `isResolvedPresentation(state.presentation.get())`, which\n // requires a truthy Presentation.\n //\n // Constraints prune the unplayable, then the chain narrows and ranks;\n // the pick is the head. An empty `rules` chain therefore selects the\n // first candidate, which falls out of the model rather than needing a\n // first-track code path of its own.\n const survivors = applyRules(rules, peek(candidateSet), deps);\n const id = survivors[0]?.id;\n if (id) state[selectedKey].set(id);\n }\n return () => state[selectedKey].set(undefined);\n },\n effects: [\n // Selection is `entry`'s alone — this only ever *de*selects. Keeping the\n // pick out of a reaction is what makes this the pinned variant rather\n // than a worse-spelled `switchVideoTrack`: nothing here re-ranks or moves\n // the pin. It has to be a reaction all the same, because what it watches\n // for is learned late — container and encryption come from a rendition's\n // media playlist, which resolves after the pick was made.\n //\n // Deliberately does *not* report why. Whatever made the pick unplayable\n // reported its own cause as the playlist resolved (1004 container, 4008\n // encryption, via `reportUnsupportedTrackConditions`), which is both more\n // specific than a verdict and already logged. The one condition no cause\n // covers is nothing being playable at all — no rendition resolved, so\n // none reported — which is why that alone emits here. See\n // `internal/design/spf/features/errors.md`.\n () => {\n // Untracked: writing the slot below must not re-enter this reaction.\n const selectedId = peek(state[selectedKey]);\n if (!selectedId) return;\n if (candidateSet.get().some((track) => track.id === selectedId)) return;\n\n // Only a pick the source actually offers is this behavior's to drop. An\n // id absent from the manifest was never selectable, and external writes\n // are left alone — see this module's header.\n const presentation = peek(state.presentation);\n if (\n isResolvedPresentation(presentation) &&\n getTracksByType(presentation, trackType).some((track) => track.id === selectedId)\n ) {\n state[selectedKey].set(undefined);\n }\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Default rules\n//\n// Each variant resolves its chain as `config?.rules ?? <default>`. The whole\n// behavior config is forwarded as the rules' `config`, so a policy rule reads\n// its own options (`preferredAudioLanguage`) directly off it.\n//\n// Video's default is the *empty* chain: with no rule narrowing or reordering the\n// candidates, the head is the first track — a consequence of the model rather than\n// a first-track code path of its own.\n// ============================================================================\n\n/** Default video chain: none. The first candidate is the pick. */\nconst DEFAULT_VIDEO_RULES: readonly SelectTrackRule<SelectVideoTrackConfig>[] = [];\n\n/**\n * Default audio chain: the three-tier policy (`preferredAudioLanguage` →\n * `DEFAULT=YES` → first) as a single narrowing rule. Returning `[]` when nothing\n * is picked lets `applyRules` fall through to the unnarrowed candidates, so the\n * head stays the first track — the same last tier the policy itself ends on.\n */\nconst preferAudioPolicy: SelectTrackRule<SelectAudioTrackConfig> = (tracks, { config }) => {\n const id = pickAudioTrackFromTracks(tracks as readonly { id: string }[], config);\n const pick = tracks.find((track) => track.id === id);\n return pick ? [pick] : [];\n};\n\nconst DEFAULT_AUDIO_RULES: readonly SelectTrackRule<SelectAudioTrackConfig>[] = [preferAudioPolicy];\n\n/**\n * Order the candidates by resolution, largest first, with bandwidth breaking ties\n * between renditions of identical dimensions. The background-video default — that\n * variant pins one rendition for the session, and absent a cap the largest is the\n * head.\n *\n * A ranker, so it reorders rather than narrowing: the chain's pick is the head of\n * what it returns, which means ranking never has to collapse to one track. Belongs\n * last in a chain — a sort only reorders what survived the filters ahead of it, and\n * leaving it last is what lets `applyRules` early-bail before it runs.\n *\n * Exported because it is a *rule*, not a variant's private policy: the same one\n * composes into `switchVideoTrack`'s chain when a ranker is wanted there.\n */\nexport const preferHighestResolution: SelectTrackRule<unknown> = (tracks) => [...tracks].sort(byDescendingResolution);\n\n/**\n * What {@link screenResolutionCap} reads off the composition state.\n *\n * Structurally compatible with `media/dom/screen`'s `ScreenResolution` rather than\n * importing it: this module sits outside the DOM layer (project references enforce\n * that), and a rule comparing pixel areas needs two numbers, not a screen.\n */\ntype ScreenResolutionRuleState = {\n screenResolution?: ReadonlySignal<{ readonly width: number; readonly height: number } | undefined>;\n};\n\n/**\n * Narrow to the renditions that fit the screen, by pixel area — the screen-size\n * cap from `internal/design/spf/features/rendition-selection-caps.md`, as a scope\n * (soft filter) rather than a constraint: an over-cap rendition is wasteful, not\n * unplayable, so nothing here may make a source unplayable.\n *\n * Narrows only — it neither orders the survivors nor resolves the case where none\n * survive, because `applyRules` owns both. So it needs a ranker behind it to pick\n * within the cap: `[screenResolutionCap, preferHighestResolution]` yields the\n * largest rendition that fits. Composed *last*, the pick would instead be whichever\n * fitting rendition the manifest happened to list first.\n *\n * Reading `state.screenResolution` through its signal is what subscribes a\n * re-evaluating chain (`switchVideoTrack`) to screen changes; `selectVideoTrack`\n * pins the first answer instead, by design.\n *\n * Compares areas rather than matching a `\"1080p\"`-style tier because a tier only\n * describes a rendition once you assume its aspect ratio — the assumption that\n * mis-measures an anamorphic ladder. See `media/dom/screen.ts`.\n *\n * Three ways the cap ends up not applying, all of them fall-through:\n *\n * - **No `screenResolution` signal at all**, because the composition omits\n * `trackScreenResolution`. So composing the cap without its signal source is\n * inert rather than broken.\n * - **A `screenResolution` of `undefined`**, meaning no screen to read. \"Unknown\"\n * has to mean \"don't cap\": treating it as an area of zero would pin every source\n * to its smallest rendition on exactly the environments we know least about.\n * - **No rendition fits**, on a screen smaller than the whole ladder. `applyRules`\n * skips the empty result and the chain proceeds unnarrowed, so the ranker behind\n * the cap decides — for `preferHighestResolution`, the largest rendition. A floor\n * is the fix if that ever matters (`rendition-selection-caps.md` carries one), not\n * a special case here.\n */\nexport const screenResolutionCap: SelectTrackRule<unknown> = (tracks, { state }) => {\n const screenResolution = (state as ScreenResolutionRuleState | undefined)?.screenResolution?.get();\n if (!screenResolution) return [];\n\n return tracksUnderPixelArea(tracks, screenResolution.width * screenResolution.height);\n};\n\n// ============================================================================\n// Specialized exports — one per track type\n// ============================================================================\n\n/**\n * Config for `selectVideoTrack`. Pass `rules` to replace the selection chain, or\n * `constraints` to replace the capability pre-pass; otherwise the chain is empty\n * and the first playable candidate is the pick.\n */\nexport interface SelectVideoTrackConfig extends CapabilityConstraintConfig {\n constraints?: readonly SelectTrackRule<SelectVideoTrackConfig>[];\n rules?: readonly SelectTrackRule<SelectVideoTrackConfig>[];\n}\n\n/**\n * Default video constraints: the capability pre-pass alone. No\n * `excludeFailedCdns` — this variant's compositions run no failover monitor, so\n * `failedCdns` has no writer and the constraint would always pass through.\n */\nconst DEFAULT_VIDEO_CONSTRAINTS: readonly SelectTrackRule<SelectVideoTrackConfig>[] = [excludeUnplayableTracks];\n\n/**\n * Select a video track when a presentation loads. Clears the selection on\n * src unload.\n *\n * This is the simple, non-ABR counterpart to `switchVideoTrack` — compose\n * one or the other, not both (both write `selectedVideoTrackId`). Composing\n * `selectVideoTrack` alone tree-shakes out the ABR code path\n * (bandwidth-estimator, quality-selection); use it for sources without\n * meaningful quality variants, test setups, or players that intentionally\n * pin a quality.\n *\n * @example\n * const reactor = selectVideoTrack.setup({ state });\n */\nexport const selectVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({ state, config }: { state: SelectStateMap<'selectedVideoTrackId'>; config?: SelectVideoTrackConfig }) =>\n setupTrackSelection({\n state,\n config: {\n selectedKey: VIDEO_TYPE_CONFIG.selectedKey,\n trackType: 'video',\n constraints: config?.constraints ?? DEFAULT_VIDEO_CONSTRAINTS,\n rules: config?.rules ?? DEFAULT_VIDEO_RULES,\n ruleConfig: config,\n },\n }),\n});\n\n/**\n * Config for `selectAudioTrack`. Pass `rules` to replace the selection chain, or\n * `constraints` to prune candidates before it runs; otherwise the default\n * three-tier policy applies (`preferredAudioLanguage` → `DEFAULT=YES` → first).\n */\nexport interface SelectAudioTrackConfig extends AudioSelectionConfig {\n constraints?: readonly SelectTrackRule<SelectAudioTrackConfig>[];\n rules?: readonly SelectTrackRule<SelectAudioTrackConfig>[];\n}\n\n/**\n * Select an audio track when a presentation loads. Clears the selection\n * on src unload.\n *\n * This is the simple, lifecycle-only counterpart to `switchAudioTrack`\n * (in `./track-switching.ts`) — compose one or the other, not both\n * (both write `selectedAudioTrackId`). `switchAudioTrack` adds\n * filter-reactivity (`userAudioTrackSelection`) and mid-stream-flush\n * orchestration; `selectAudioTrack` covers the default-on-load case\n * without those. Use this variant for test setups, audio-only flows\n * that don't expose language switching, or composition variants that\n * intentionally pin a track.\n *\n * @example\n * const reactor = selectAudioTrack.setup({ state });\n *\n * @example\n * // Language preference, honored by the default audio policy rule\n * const reactor = selectAudioTrack.setup({\n * state,\n * config: { preferredAudioLanguage: 'en' },\n * });\n */\nexport const selectAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({ state, config }: { state: SelectStateMap<'selectedAudioTrackId'>; config?: SelectAudioTrackConfig }) =>\n setupTrackSelection({\n state,\n config: {\n selectedKey: AUDIO_TYPE_CONFIG.selectedKey,\n trackType: 'audio',\n constraints: config?.constraints ?? [],\n rules: config?.rules ?? DEFAULT_AUDIO_RULES,\n ruleConfig: config,\n },\n }),\n});\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA0GA,SAAS,oBAA4D,EACnE,OACA,QAAQ,EAAE,aAAa,WAAW,aAAa,OAAO,gBAIrD;CACD,MAAM,qBAAqB,eACzB,uBAAuB,MAAM,aAAa,IAAI,CAAC,IAC1C,0BACA,yBACP;CAEA,MAAM,OAAO;EAAE;EAAO,QAAQ;CAAW;CAYzC,MAAM,eAAe,eACb;EACJ,MAAM,eA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sB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA+CpH,MAAa,uBAAiD,QAAQ,EAAE,YAAY;CAClF,MAAM,mBAAoB,OAAiD,kBAAkB,IAAI;CACjG,IAAI,CAAC,kBAAkB,OAAO,CAAC;CAE/B,OAAO,qBAAqB,QAAQ,iBAAiB,QAAQ,iBAAiB,MAAM;AACtF;;;;;;AAqBA,MAAM,4BAAgF,CAAC,uBAAuB;;;;;;;;;;;;;;;AAgB9G,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EAAE,OAAO,aACf,oBAAoB;EAClB;EACA,QAAQ;GACN,aAAa,kBAAkB;GAC/B,WAAW;GACX,aAAa,QAAQ,eAAe;GACpC,OAAO,QAAQ,SAAS;GACxB,YAAY;EACd;CACF,CAAC;AACL,CAAC;AAmC+B,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EAAE,OAAO,aACf,oBAAoB;EAClB;EACA,QAAQ;GACN,aAAa,kBAAkB;GAC/B,WAAW;GACX,aAAa,QAAQ,eAAe,CAAC;GACrC,OAAO,QAAQ,SAAS;GACxB,YAAY;EACd;CACF,CAAC;AACL,CAAC"}
|
|
1
|
+
{"version":3,"file":"select-tracks.js","names":[],"sources":["../../../../src/playback/behaviors/select-tracks.ts"],"sourcesContent":["/**\n * **Default audio/video track selection on src load / unselect on src unload.**\n * When a presentation is resolved, sets `selectedVideoTrackId` /\n * `selectedAudioTrackId` from a per-type default rule chain if no selection\n * already exists. When the presentation is unset/reset (transitions back to unresolved),\n * clears the selection so a stale id from the previous source doesn't persist.\n *\n * Lifecycle-driven: the pick fires once per transition, and nothing re-picks —\n * that is what separates these from the `switch*` variants. External writes (user\n * picks, ABR, programmatic filter-driven re-picks) are left alone, including a\n * write naming a track the manifest never offered.\n *\n * The one thing policed between transitions is a pick the *constraints* turn\n * against: a rendition's container and encryption are only known once its media\n * playlist resolves, which is after the pick was made, so a selection that becomes\n * unplayable is dropped. Dropped, never moved — re-picking is exactly the behavior\n * `switchVideoTrack` exists to provide. Dropping reports nothing on its own, since\n * whatever made the pick unplayable already reported its own, more specific cause.\n *\n * Selection runs the same rule model `switchVideoTrack` does — a hard\n * `constraints` pre-pass, then an ordered `rules` chain, with the pick as the\n * head (see `internal/design/spf/track-switching-model.md`). What differs is\n * reactivity, not the rules: this evaluates the chain once on resolve and pins\n * the result, where `switchVideoTrack` re-evaluates inside an effect so its rules\n * subscribe to bandwidth and user selection. A rule written for one therefore\n * composes into the other unchanged.\n *\n * Both are config-driven, each per-type export wiring a sensible default: audio's\n * three-tier language policy, and for video the *empty* chain — with nothing\n * narrowing or reordering, the head is the first candidate. The behavior's\n * `config` is forwarded to the rules, so options like `preferredAudioLanguage`\n * reach them without an intermediate layer.\n *\n * Note a rule can only pick among real candidates, where the picker it replaced\n * could return any id at all. An id absent from the manifest was never\n * selectable, so that narrowing is the point rather than a limitation.\n *\n * Compose `selectVideoTrack` for the simple \"pick a default video track\"\n * behavior, or `switchVideoTrack` (`./track-switching.ts`) for the\n * ABR-driven variant. Compose `selectAudioTrack` for the simple default\n * pick, or `switchAudioTrack` (`./track-switching.ts`) for the\n * filter-reactive + mid-stream-flush slot-owner variant — when audio-abr\n * lands, `switchAudioTrack` extends into `switchAudioQuality`. Compose\n * only one per type — they're alternatives, not stackable (each writes\n * the same `selected*TrackId` slot). The simple variants tree-shake out\n * the heavier machinery (bandwidth estimator, quality selection, flush\n * orchestration).\n *\n * Text selection has no simple variant here — it's owned by `switchTextTrack`\n * (`./track-switching.ts`), which resolves standing `userTextTrackSelection`\n * intent against the constrained, CDN-scoped renditions.\n */\n\nimport { 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 type { Resolution } from '../../media/primitives/resolution';\nimport {\n type AudioSelectionConfig,\n byDescendingResolution,\n pickAudioTrackFromTracks,\n type TrackSelectionState,\n tracksUnderPixelArea,\n} from '../../media/primitives/select-tracks';\nimport { isResolvedPresentation, type TrackType } from '../../media/types';\nimport { getTracksByType } from '../../media/utils/tracks';\nimport {\n applyConstraints,\n applyRules,\n type CapabilityConstraintConfig,\n excludeUnplayableTracks,\n type SelectionRule,\n sameCandidateSet,\n} from '../primitives/selection-rules';\nimport { AUDIO_TYPE_CONFIG, VIDEO_TYPE_CONFIG } from '../primitives/track-types';\n\n// ============================================================================\n// Specialization helper\n//\n// `setupTrackSelection` has the same shape as a Behavior `setup` function:\n// `({ state, config }) => Reactor`. Each `selectXTrack` export below calls\n// it from inside its own `defineBehavior` setup, supplying its per-type\n// `selectedKey`, track type, default rule chain, and forwarded config. The lifecycle\n// — pick on entering 'presentation-resolved' if not already selected; clear\n// on entering 'presentation-unresolved' — is shared.\n// ============================================================================\n\ntype SelectedTrackKey = 'selectedVideoTrackId' | 'selectedAudioTrackId';\n\ntype SelectStateMap<K extends SelectedTrackKey> = {\n presentation: ReadonlySignal<TrackSelectionState['presentation']>;\n} & { [P in K]: Signal<TrackSelectionState[P]> };\n\n/** A selection rule over this behavior's candidate tracks. */\nexport type SelectTrackRule<Config> = SelectionRule<SelectableTrack, unknown, unknown, Config | undefined>;\n\n/** What a rule here needs off a candidate: the id it may become the pick by. */\ntype SelectableTrack = { id: string };\n\ninterface TrackSelectionSetupConfig<K extends SelectedTrackKey, RuleConfig> {\n selectedKey: K;\n trackType: TrackType;\n constraints: readonly SelectTrackRule<RuleConfig>[];\n rules: readonly SelectTrackRule<RuleConfig>[];\n ruleConfig?: RuleConfig;\n}\n\nfunction setupTrackSelection<K extends SelectedTrackKey, RuleConfig>({\n state,\n config: { selectedKey, trackType, constraints, rules, ruleConfig },\n}: {\n state: SelectStateMap<K>;\n config: TrackSelectionSetupConfig<K, RuleConfig>;\n}) {\n const derivedStateSignal = computed(() =>\n isResolvedPresentation(state.presentation.get())\n ? ('presentation-resolved' as const)\n : ('presentation-unresolved' as const)\n );\n\n const deps = { state, config: ruleConfig };\n\n // The playable candidate set — the type's tracks after the hard-constraints\n // pre-pass. A `computed` so it re-evaluates when its inputs change, which is what\n // lets a *pinned* selection still notice it has gone unplayable: `resolve-track`\n // relabels the whole type's container from the first resolved media playlist,\n // long after `entry` made its pick under the fMP4 default.\n //\n // The `equals` gates notification on the set of track ids rather than array\n // identity, matching `setupTrackSwitching`'s. Segment appends and live reloads\n // both swap in a new presentation object carrying the same variants; without\n // this the effect below would re-run on every one of them.\n const candidateSet = computed(\n () => {\n const presentation = state.presentation.get();\n if (!isResolvedPresentation(presentation)) return [];\n return applyConstraints(constraints, getTracksByType(presentation, trackType), deps);\n },\n { equals: sameCandidateSet }\n );\n\n return createMachineReactor({\n initial: 'presentation-unresolved',\n monitor: () => derivedStateSignal.get(),\n states: {\n 'presentation-unresolved': {},\n 'presentation-resolved': {\n // Entry: pick a default on entering presentation-resolved if none\n // is set. External writes (user picks, ABR) that already populated\n // the slot are left alone.\n //\n // The returned cleanup runs on state exit — which fires on src\n // unload (presentation-resolved → presentation-unresolved) AND on\n // behavior destroy (presentation-resolved → destroying →\n // destroyed). Putting the clear here rather than as\n // presentation-unresolved.entry is more cohesive (operation +\n // cleanup co-located) and correctly covers destroy (destroy\n // doesn't pass through presentation-unresolved).\n entry: () => {\n if (!state[selectedKey].get()) {\n // `state.presentation.get()` is non-null inside this entry —\n // the reactor's `'presentation-resolved'` gate is exactly\n // `isResolvedPresentation(state.presentation.get())`, which\n // requires a truthy Presentation.\n //\n // Constraints prune the unplayable, then the chain narrows and ranks;\n // the pick is the head. An empty `rules` chain therefore selects the\n // first candidate, which falls out of the model rather than needing a\n // first-track code path of its own.\n const survivors = applyRules(rules, peek(candidateSet), deps);\n const id = survivors[0]?.id;\n if (id) state[selectedKey].set(id);\n }\n return () => state[selectedKey].set(undefined);\n },\n effects: [\n // Selection is `entry`'s alone — this only ever *de*selects. Keeping the\n // pick out of a reaction is what makes this the pinned variant rather\n // than a worse-spelled `switchVideoTrack`: nothing here re-ranks or moves\n // the pin. It has to be a reaction all the same, because what it watches\n // for is learned late — container and encryption come from a rendition's\n // media playlist, which resolves after the pick was made.\n //\n // Deliberately does *not* report why. Whatever made the pick unplayable\n // reported its own cause as the playlist resolved (1004 container, 4008\n // encryption, via `reportUnsupportedTrackConditions`), which is both more\n // specific than a verdict and already logged. The one condition no cause\n // covers is nothing being playable at all — no rendition resolved, so\n // none reported — which is why that alone emits here. See\n // `internal/design/spf/features/errors.md`.\n () => {\n // Untracked: writing the slot below must not re-enter this reaction.\n const selectedId = peek(state[selectedKey]);\n if (!selectedId) return;\n if (candidateSet.get().some((track) => track.id === selectedId)) return;\n\n // Only a pick the source actually offers is this behavior's to drop. An\n // id absent from the manifest was never selectable, and external writes\n // are left alone — see this module's header.\n const presentation = peek(state.presentation);\n if (\n isResolvedPresentation(presentation) &&\n getTracksByType(presentation, trackType).some((track) => track.id === selectedId)\n ) {\n state[selectedKey].set(undefined);\n }\n },\n ],\n },\n },\n });\n}\n\n// ============================================================================\n// Default rules\n//\n// Each variant resolves its chain as `config?.rules ?? <default>`. The whole\n// behavior config is forwarded as the rules' `config`, so a policy rule reads\n// its own options (`preferredAudioLanguage`) directly off it.\n//\n// Video's default is the *empty* chain: with no rule narrowing or reordering the\n// candidates, the head is the first track — a consequence of the model rather than\n// a first-track code path of its own.\n// ============================================================================\n\n/** Default video chain: none. The first candidate is the pick. */\nconst DEFAULT_VIDEO_RULES: readonly SelectTrackRule<SelectVideoTrackConfig>[] = [];\n\n/**\n * Default audio chain: the three-tier policy (`preferredAudioLanguage` →\n * `DEFAULT=YES` → first) as a single narrowing rule. Returning `[]` when nothing\n * is picked lets `applyRules` fall through to the unnarrowed candidates, so the\n * head stays the first track — the same last tier the policy itself ends on.\n */\nconst preferAudioPolicy: SelectTrackRule<SelectAudioTrackConfig> = (tracks, { config }) => {\n const id = pickAudioTrackFromTracks(tracks as readonly { id: string }[], config);\n const pick = tracks.find((track) => track.id === id);\n return pick ? [pick] : [];\n};\n\nconst DEFAULT_AUDIO_RULES: readonly SelectTrackRule<SelectAudioTrackConfig>[] = [preferAudioPolicy];\n\n/**\n * Order the candidates by resolution, largest first, with bandwidth breaking ties\n * between renditions of identical dimensions. The background-video default — that\n * variant pins one rendition for the session, and absent a cap the largest is the\n * head.\n *\n * A ranker, so it reorders rather than narrowing: the chain's pick is the head of\n * what it returns, which means ranking never has to collapse to one track. Belongs\n * last in a chain — a sort only reorders what survived the filters ahead of it, and\n * leaving it last is what lets `applyRules` early-bail before it runs.\n *\n * Exported because it is a *rule*, not a variant's private policy: the same one\n * composes into `switchVideoTrack`'s chain when a ranker is wanted there.\n */\nexport const preferHighestResolution: SelectTrackRule<unknown> = (tracks) => [...tracks].sort(byDescendingResolution);\n\n/** What {@link screenResolutionCap} reads off the composition state. */\ntype ScreenResolutionRuleState = {\n screenResolution?: ReadonlySignal<Resolution | undefined>;\n};\n\n/**\n * Narrow to the renditions that fit the screen, by pixel area — the screen-size\n * cap from `internal/design/spf/features/rendition-selection-caps.md`, as a scope\n * (soft filter) rather than a constraint: an over-cap rendition is wasteful, not\n * unplayable, so nothing here may make a source unplayable.\n *\n * Narrows only — it neither orders the survivors nor resolves the case where none\n * survive, because `applyRules` owns both. So it needs a ranker behind it to pick\n * within the cap: `[screenResolutionCap, preferHighestResolution]` yields the\n * largest rendition that fits. Composed *last*, the pick would instead be whichever\n * fitting rendition the manifest happened to list first.\n *\n * Reading `state.screenResolution` through its signal is what subscribes a\n * re-evaluating chain (`switchVideoTrack`) to screen changes; `selectVideoTrack`\n * pins the first answer instead, by design.\n *\n * Compares areas rather than matching a `\"1080p\"`-style tier because a tier only\n * describes a rendition once you assume its aspect ratio — the assumption that\n * mis-measures an anamorphic ladder. See `media/dom/screen.ts`.\n *\n * Three ways the cap ends up not applying, all of them fall-through:\n *\n * - **No `screenResolution` signal at all**, because the composition omits\n * `trackScreenResolution`. So composing the cap without its signal source is\n * inert rather than broken.\n * - **A `screenResolution` of `undefined`**, meaning no screen to read. \"Unknown\"\n * has to mean \"don't cap\": treating it as an area of zero would pin every source\n * to its smallest rendition on exactly the environments we know least about.\n * - **No rendition fits**, on a screen smaller than the whole ladder. `applyRules`\n * skips the empty result and the chain proceeds unnarrowed, so the ranker behind\n * the cap decides — for `preferHighestResolution`, the largest rendition. A floor\n * is the fix if that ever matters (`rendition-selection-caps.md` carries one), not\n * a special case here.\n */\nexport const screenResolutionCap: SelectTrackRule<unknown> = (tracks, { state }) => {\n const screenResolution = (state as ScreenResolutionRuleState | undefined)?.screenResolution?.get();\n if (!screenResolution) return [];\n\n return tracksUnderPixelArea(tracks, screenResolution.width * screenResolution.height);\n};\n\n// ============================================================================\n// Specialized exports — one per track type\n// ============================================================================\n\n/**\n * Config for `selectVideoTrack`. Pass `rules` to replace the selection chain, or\n * `constraints` to replace the capability pre-pass; otherwise the chain is empty\n * and the first playable candidate is the pick.\n */\nexport interface SelectVideoTrackConfig extends CapabilityConstraintConfig {\n constraints?: readonly SelectTrackRule<SelectVideoTrackConfig>[];\n rules?: readonly SelectTrackRule<SelectVideoTrackConfig>[];\n}\n\n/**\n * Default video constraints: the capability pre-pass alone. No\n * `excludeFailedCdns` — this variant's compositions run no failover monitor, so\n * `failedCdns` has no writer and the constraint would always pass through.\n */\nconst DEFAULT_VIDEO_CONSTRAINTS: readonly SelectTrackRule<SelectVideoTrackConfig>[] = [excludeUnplayableTracks];\n\n/**\n * Select a video track when a presentation loads. Clears the selection on\n * src unload.\n *\n * This is the simple, non-ABR counterpart to `switchVideoTrack` — compose\n * one or the other, not both (both write `selectedVideoTrackId`). Composing\n * `selectVideoTrack` alone tree-shakes out the ABR code path\n * (bandwidth-estimator, quality-selection); use it for sources without\n * meaningful quality variants, test setups, or players that intentionally\n * pin a quality.\n *\n * @example\n * const reactor = selectVideoTrack.setup({ state });\n */\nexport const selectVideoTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedVideoTrackId'],\n contextKeys: [],\n setup: ({ state, config }: { state: SelectStateMap<'selectedVideoTrackId'>; config?: SelectVideoTrackConfig }) =>\n setupTrackSelection({\n state,\n config: {\n selectedKey: VIDEO_TYPE_CONFIG.selectedKey,\n trackType: 'video',\n constraints: config?.constraints ?? DEFAULT_VIDEO_CONSTRAINTS,\n rules: config?.rules ?? DEFAULT_VIDEO_RULES,\n ruleConfig: config,\n },\n }),\n});\n\n/**\n * Config for `selectAudioTrack`. Pass `rules` to replace the selection chain, or\n * `constraints` to prune candidates before it runs; otherwise the default\n * three-tier policy applies (`preferredAudioLanguage` → `DEFAULT=YES` → first).\n */\nexport interface SelectAudioTrackConfig extends AudioSelectionConfig {\n constraints?: readonly SelectTrackRule<SelectAudioTrackConfig>[];\n rules?: readonly SelectTrackRule<SelectAudioTrackConfig>[];\n}\n\n/**\n * Select an audio track when a presentation loads. Clears the selection\n * on src unload.\n *\n * This is the simple, lifecycle-only counterpart to `switchAudioTrack`\n * (in `./track-switching.ts`) — compose one or the other, not both\n * (both write `selectedAudioTrackId`). `switchAudioTrack` adds\n * filter-reactivity (`userAudioTrackSelection`) and mid-stream-flush\n * orchestration; `selectAudioTrack` covers the default-on-load case\n * without those. Use this variant for test setups, audio-only flows\n * that don't expose language switching, or composition variants that\n * intentionally pin a track.\n *\n * @example\n * const reactor = selectAudioTrack.setup({ state });\n *\n * @example\n * // Language preference, honored by the default audio policy rule\n * const reactor = selectAudioTrack.setup({\n * state,\n * config: { preferredAudioLanguage: 'en' },\n * });\n */\nexport const selectAudioTrack = defineBehavior({\n stateKeys: ['presentation', 'selectedAudioTrackId'],\n contextKeys: [],\n setup: ({ state, config }: { state: SelectStateMap<'selectedAudioTrackId'>; config?: SelectAudioTrackConfig }) =>\n setupTrackSelection({\n state,\n config: {\n selectedKey: AUDIO_TYPE_CONFIG.selectedKey,\n trackType: 'audio',\n constraints: config?.constraints ?? [],\n rules: config?.rules ?? DEFAULT_AUDIO_RULES,\n ruleConfig: config,\n },\n }),\n});\n"],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C;;;;;;;AAQjF,MAAM,qBAA8D,QAAQ,EAAE,aAAa;CACzF,MAAM,KAAK,yBAAyB,QAAqC,MAAM;CAC/E,MAAM,OAAO,OAAO,MAAM,UAAU,MAAM,OAAO,EAAE;CACnD,OAAO,OAAO,CAAC,IAAI,IAAI,CAAC;AAC1B;AAEA,MAAM,sBAA0E,CAAC,iBAAiB;;;;;;;;;;;;;;;AAgBlG,MAAa,2BAAqD,WAAW,CAAC,GAAG,MAAM,CAAC,CAAC,KAAK,sBAAsB;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAyCpH,MAAa,uBAAiD,QAAQ,EAAE,YAAY;CAClF,MAAM,mBAAoB,OAAiD,kBAAkB,IAAI;CACjG,IAAI,CAAC,kBAAkB,OAAO,CAAC;CAE/B,OAAO,qBAAqB,QAAQ,iBAAiB,QAAQ,iBAAiB,MAAM;AACtF;;;;;;AAqBA,MAAM,4BAAgF,CAAC,uBAAuB;;;;;;;;;;;;;;;AAgB9G,MAAa,mBAAmB,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EAAE,OAAO,aACf,oBAAoB;EAClB;EACA,QAAQ;GACN,aAAa,kBAAkB;GAC/B,WAAW;GACX,aAAa,QAAQ,eAAe;GACpC,OAAO,QAAQ,SAAS;GACxB,YAAY;EACd;CACF,CAAC;AACL,CAAC;AAmC+B,eAAe;CAC7C,WAAW,CAAC,gBAAgB,sBAAsB;CAClD,aAAa,CAAC;CACd,QAAQ,EAAE,OAAO,aACf,oBAAoB;EAClB;EACA,QAAQ;GACN,aAAa,kBAAkB;GAC/B,WAAW;GACX,aAAa,QAAQ,eAAe,CAAC;GACrC,OAAO,QAAQ,SAAS;GACxB,YAAY;EACd;CACF,CAAC;AACL,CAAC"}
|
|
@@ -4,7 +4,7 @@ import { createMachineReactor } from "../../core/reactors/create-machine-reactor
|
|
|
4
4
|
import { isResolvedPresentation } from "../../media/types/index.js";
|
|
5
5
|
import { getTracksByType } from "../../media/utils/tracks.js";
|
|
6
6
|
import { SVTA_NO_SUPPORTED_AUDIO_TRACK, SVTA_NO_SUPPORTED_VIDEO_TRACK } from "../../media/errors.js";
|
|
7
|
-
import { matchesPartialTrack, pickTextTrackFromTracks } from "../../media/primitives/select-tracks.js";
|
|
7
|
+
import { matchesPartialTrack, pickTextTrackFromTracks, smallestCoveringPixelArea, tracksUnderPixelArea } from "../../media/primitives/select-tracks.js";
|
|
8
8
|
import { applyConstraints, applyRules, excludeUnplayableTracks, sameCandidateSet } from "../primitives/selection-rules.js";
|
|
9
9
|
import { emitError } from "./collect-errors.js";
|
|
10
10
|
import { getCdnId } from "../../media/utils/cdn.js";
|
|
@@ -22,8 +22,8 @@ import { DEFAULT_QUALITY_CONFIG, resolutionArea } from "../../media/abr/quality-
|
|
|
22
22
|
* failed-CDN constraint (`excludeFailedCdns`, failover cooldown) and the
|
|
23
23
|
* capability constraint (`excludeUnplayableTracks`, codec support). Then a small
|
|
24
24
|
* ordered chain of rules (`applyRules`) picks among the survivors. Each constraint/rule reads the signals it needs at apply
|
|
25
|
-
* time, so the effect subscribes to exactly what was consulted. The chain
|
|
26
|
-
*
|
|
25
|
+
* time, so the effect subscribes to exactly what was consulted. The chain runs
|
|
26
|
+
* most authoritative first:
|
|
27
27
|
*
|
|
28
28
|
* 1. **user intent** — a soft filter on `user*TrackSelection`: narrow to the
|
|
29
29
|
* partial-track match; an empty match falls through to the full set.
|
|
@@ -31,7 +31,12 @@ import { DEFAULT_QUALITY_CONFIG, resolutionArea } from "../../media/abr/quality-
|
|
|
31
31
|
* narrow to the highest-priority CDN that still has tracks; an empty match
|
|
32
32
|
* falls through. Shared by video and audio, so every type stays on one CDN
|
|
33
33
|
* (`deriveCdnPriority` owns the list). No-op for non-redundant sources.
|
|
34
|
-
* 3. **
|
|
34
|
+
* 3. **player resolution** — a soft filter on `playerResolution`
|
|
35
|
+
* (`playerResolutionCap`, video only): narrow to the smallest rendition
|
|
36
|
+
* tier covering the player element, plus everything below it. No-op
|
|
37
|
+
* without a measurement. Ahead of the ranker but behind the CDN scope, so
|
|
38
|
+
* the cap chooses *within* a host rather than between hosts.
|
|
39
|
+
* 4. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and
|
|
35
40
|
* audio. Fitting tracks (within the throughput threshold) first, highest
|
|
36
41
|
* bitrate first; over-throughput tracks after, least-over first. Hysteresis
|
|
37
42
|
* via boosting the current track's sort weight by `upgradeMargin`.
|
|
@@ -51,8 +56,9 @@ import { DEFAULT_QUALITY_CONFIG, resolutionArea } from "../../media/abr/quality-
|
|
|
51
56
|
* `setupTrackSwitching` owns only the lifecycle and runs what it's given. Video
|
|
52
57
|
* and audio run constraints `[excludeFailedCdns, excludeUnplayableTracks]` then
|
|
53
58
|
* rules `[filterByUserSelection, preferActiveCdn, rankByBandwidth]` and take the
|
|
54
|
-
* head; `
|
|
55
|
-
*
|
|
59
|
+
* head; video inserts `playerResolutionCap` after the active-CDN scope, and
|
|
60
|
+
* `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack` takes
|
|
61
|
+
* none. `switchTextTrack` differs — selection is *optional* (captions are
|
|
56
62
|
* opt-in / off-able), so it runs `[excludeFailedCdns]` + `[preferActiveCdn]` and
|
|
57
63
|
* supplies a text terminal (`pickResolvedTextTrack`) that resolves standing user
|
|
58
64
|
* intent (`userTextTrackSelection`, incl. `'off'`) and may yield no selection.
|
|
@@ -87,6 +93,41 @@ function filterByUserSelection(tracks, { state, config }) {
|
|
|
87
93
|
return filter ? tracks.filter((track) => matchesPartialTrack(track, filter)) : tracks;
|
|
88
94
|
}
|
|
89
95
|
/**
|
|
96
|
+
* Player-resolution cap — a soft filter, video only. Narrows to the renditions
|
|
97
|
+
* worth delivering at the player element's rendered size, so a small embed
|
|
98
|
+
* doesn't pull segments nobody can perceive. The tighter sibling of
|
|
99
|
+
* `screenResolutionCap`: the element's box, not the screen behind it.
|
|
100
|
+
*
|
|
101
|
+
* The cap is the *smallest tier that still covers the player*, and everything at
|
|
102
|
+
* or below it survives — not "everything at or below the player's area," which
|
|
103
|
+
* under-serves a player falling between two tiers. Take an 800×450 player
|
|
104
|
+
* against a 360p/720p/1080p ladder: only 360p is below it, so capping at the
|
|
105
|
+
* player's area would hold an 800-px-wide box to a 640-px-wide picture. The
|
|
106
|
+
* honest answer is the tier above, 720p, with 360p left in for the ranker.
|
|
107
|
+
* `smallestCoveringPixelArea` picks that cap; `tracksUnderPixelArea` — the same
|
|
108
|
+
* filter `screenResolutionCap` narrows with — applies it.
|
|
109
|
+
*
|
|
110
|
+
* Renditions declaring no width or height compare as area `0` and are never capped
|
|
111
|
+
* out — they can't be judged against the player, and dropping them could strand
|
|
112
|
+
* a source whose renditions all omit it.
|
|
113
|
+
*
|
|
114
|
+
* Runs *after* `preferActiveCdn`, so it narrows within the host already chosen.
|
|
115
|
+
* Ahead of it, a cap that pruned every rendition of the preferred CDN would leave
|
|
116
|
+
* the scope to fall to the next one with survivors — a size preference silently
|
|
117
|
+
* moving playback to another host. Redundant streams normally mirror the same
|
|
118
|
+
* ladder, which makes that a nonstandard-but-legal mismatch across CDNs rather
|
|
119
|
+
* than an everyday case; the ordering costs nothing either way.
|
|
120
|
+
*
|
|
121
|
+
* Reading `state.playerResolution` through its signal is what subscribes the
|
|
122
|
+
* chain to resizes; `undefined` — no signal composed, or nothing to measure —
|
|
123
|
+
* means "don't cap" rather than a cap of zero, so the chain proceeds unnarrowed.
|
|
124
|
+
*/
|
|
125
|
+
function playerResolutionCap(tracks, { state }) {
|
|
126
|
+
const playerResolution = state.playerResolution?.get();
|
|
127
|
+
if (!playerResolution) return tracks;
|
|
128
|
+
return tracksUnderPixelArea(tracks, smallestCoveringPixelArea(tracks, playerResolution.width * playerResolution.height));
|
|
129
|
+
}
|
|
130
|
+
/**
|
|
90
131
|
* Failed-CDN constraint — a *hard* filter (constraints pre-pass), shared by
|
|
91
132
|
* video and audio. Removes tracks served from a CDN currently in failover
|
|
92
133
|
* cooldown (`failedCdns`, written by the failover monitor). Removed tracks are never
|
|
@@ -270,6 +311,7 @@ const switchVideoTrack = defineBehavior({
|
|
|
270
311
|
rules: [
|
|
271
312
|
filterByUserSelection,
|
|
272
313
|
preferActiveCdn,
|
|
314
|
+
playerResolutionCap,
|
|
273
315
|
rankByBandwidth
|
|
274
316
|
],
|
|
275
317
|
noSupportedTrackCode: SVTA_NO_SUPPORTED_VIDEO_TRACK
|
|
@@ -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 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 { SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nimport { applyConstraints, applyRules, excludeUnplayableTracks, sameCandidateSet } from '../primitives/selection-rules';\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// Re-exported so a consumer typing against this module's rules doesn't need a\n// second import; the definitions live in `../primitives/selection-rules` so the\n// simple `selectVideoTrack` variant can share them without pulling the ABR path\n// in with them. See that module's note.\nexport type { SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nexport { applyConstraints, applyRules, excludeUnplayableTracks } from '../primitives/selection-rules';\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\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 * 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), via `pickTextTrackFromTracks`.\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: sameCandidateSet }\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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwIA,MAAa,4BAA4B;;;;;;;AA2OzC,SAAS,sBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,MAAM,OAAO;CACnB,IAAI,CAAC,KAAK,OAAO;CACjB,M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QN,GAAG;GACH,cAAc;GACd,kBAAkB;GAClB,YAAY,iBAAiB,gBAAgB,cAAc,OAAO;GAClE,aAAa,CAAC,mBAAmB,uBAAuB;GACxD,OAAO;IAAC;IAAuB;IAAiB;GAAe;GAC/D,sBAAsB;EACxB;CACF,CAAC;AACL,CAAC;;;;;;;;;;;;;;;;;;AAkCD,MAAa,kBAAkB,eAAe;CAC5C,WAAW,CAAC,gBAAgB,qBAAqB;CACjD,aAAa,CAAC;CACd,QAAQ,EACN,OACA,QACA,GAAG,iBASH,oBAA2G;EACzG,GAAG;EACH;EACA,QAAQ;GACN,GAAG;GACH,cAAc;GACd,YAAY,iBAAiB,gBAAgB,cAAc,MAAM;GACjE,aAAa,CAAC,iBAAiB;GAC/B,OAAO,CAAC,eAAe;GACvB,kBAAkB;EACpB;CACF,CAAC;AACL,CAAC"}
|
|
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 runs\n * 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. **player resolution** — a soft filter on `playerResolution`\n * (`playerResolutionCap`, video only): narrow to the smallest rendition\n * tier covering the player element, plus everything below it. No-op\n * without a measurement. Ahead of the ranker but behind the CDN scope, so\n * the cap chooses *within* a host rather than between hosts.\n * 4. **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; video inserts `playerResolutionCap` after the active-CDN scope, and\n * `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack` takes\n * 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 type { Resolution } from '../../media/primitives/resolution';\nimport {\n matchesPartialTrack,\n pickTextTrackFromTracks,\n smallestCoveringPixelArea,\n type TextSelectionConfig,\n tracksUnderPixelArea,\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 { SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nimport { applyConstraints, applyRules, excludeUnplayableTracks, sameCandidateSet } from '../primitives/selection-rules';\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// Re-exported so a consumer typing against this module's rules doesn't need a\n// second import; the definitions live in `../primitives/selection-rules` so the\n// simple `selectVideoTrack` variant can share them without pulling the ABR path\n// in with them. See that module's note.\nexport type { SelectionRule, SelectionRuleDeps } from '../primitives/selection-rules';\nexport { applyConstraints, applyRules, excludeUnplayableTracks } from '../primitives/selection-rules';\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 player-resolution cap reads: TrackSwitchingStateMap plus the\n * *optional* player measurement, manifested by `trackPlayerResolution`.\n */\ntype PlayerResolutionCapStateMap<S extends SelectionKey> = TrackSwitchingStateMap<S> & {\n playerResolution?: ReadonlySignal<Resolution | undefined>;\n};\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\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 * Player-resolution cap — a soft filter, video only. Narrows to the renditions\n * worth delivering at the player element's rendered size, so a small embed\n * doesn't pull segments nobody can perceive. The tighter sibling of\n * `screenResolutionCap`: the element's box, not the screen behind it.\n *\n * The cap is the *smallest tier that still covers the player*, and everything at\n * or below it survives — not \"everything at or below the player's area,\" which\n * under-serves a player falling between two tiers. Take an 800×450 player\n * against a 360p/720p/1080p ladder: only 360p is below it, so capping at the\n * player's area would hold an 800-px-wide box to a 640-px-wide picture. The\n * honest answer is the tier above, 720p, with 360p left in for the ranker.\n * `smallestCoveringPixelArea` picks that cap; `tracksUnderPixelArea` — the same\n * filter `screenResolutionCap` narrows with — applies it.\n *\n * Renditions declaring no width or height compare as area `0` and are never capped\n * out — they can't be judged against the player, and dropping them could strand\n * a source whose renditions all omit it.\n *\n * Runs *after* `preferActiveCdn`, so it narrows within the host already chosen.\n * Ahead of it, a cap that pruned every rendition of the preferred CDN would leave\n * the scope to fall to the next one with survivors — a size preference silently\n * moving playback to another host. Redundant streams normally mirror the same\n * ladder, which makes that a nonstandard-but-legal mismatch across CDNs rather\n * than an everyday case; the ordering costs nothing either way.\n *\n * Reading `state.playerResolution` through its signal is what subscribes the\n * chain to resizes; `undefined` — no signal composed, or nothing to measure —\n * means \"don't cap\" rather than a cap of zero, so the chain proceeds unnarrowed.\n */\nfunction playerResolutionCap<S extends SelectionKey, T extends SwitchableTrack>(\n tracks: readonly T[],\n { state }: SelectionRuleDeps<PlayerResolutionCapStateMap<S>, AnySlotMap, TrackSwitchingConfig<S, T>>\n): readonly T[] {\n const playerResolution = state.playerResolution?.get();\n if (!playerResolution) return tracks;\n\n // A player larger than every rendition has no covering tier, so the cap is\n // `undefined` and the filter's unbounded default narrows nothing.\n const cap = smallestCoveringPixelArea(tracks, playerResolution.width * playerResolution.height);\n\n return tracksUnderPixelArea(tracks, cap);\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 * 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), via `pickTextTrackFromTracks`.\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: sameCandidateSet }\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, playerResolutionCap, 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":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAiJA,MAAa,4BAA4B;;;;;;;AAmPzC,SAAS,sBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,MAAM,OAAO;CACnB,IAAI,CAAC,KAAK,OAAO;CACjB,MAAM,SAAS,MAAM,IAAI,EAAE,IAAI;CAC/B,OAAO,SAAS,OAAO,QAAQ,UAAU,oBAAoB,OAAO,MAAM,CAAC,IAAI;AACjF;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAgCA,SAAS,oBACP,QACA,EAAE,SACY;CACd,MAAM,mBAAmB,MAAM,kBAAkB,IAAI;CACrD,IAAI,CAAC,kBAAkB,OAAO;CAM9B,OAAO,qBAAqB,QAFhB,0BAA0B,QAAQ,iBAAiB,QAAQ,iBAAiB,MAElD,CAAC;AACzC;;;;;;;;;;;;;AAcA,SAAS,kBACP,QACA,EAAE,OAAO,UACK;CACd,MAAM,SAAS,MAAM,YAAY,IAAI;CACrC,IAAI,CAAC,QAAQ,QAAQ,OAAO;CAC5B,MAAMA,aAAW,OAAO,YAAYC;CACpC,MAAM,YAAY,IAAI,IAAI,MAAM;CAChC,OAAO,OAAO,QAAQ,UAAU,CAAC,UAAU,IAAID,WAAS,MAAM,GAAG,CAAC,CAAC;AACrE;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c;GACd,YAAY,iBAAiB,gBAAgB,cAAc,MAAM;GACjE,aAAa,CAAC,iBAAiB;GAC/B,OAAO,CAAC,eAAe;GACvB,kBAAkB;EACpB;CACF,CAAC;AACL,CAAC"}
|
|
@@ -76,9 +76,9 @@ type BackgroundVideoEngineSignals = {
|
|
|
76
76
|
interface BackgroundVideoEngineConfig extends ShareSignalsConfig<BackgroundVideoEngineState, BackgroundVideoEngineContext> {
|
|
77
77
|
/**
|
|
78
78
|
* Hard-constraint pre-pass handed to `selectVideoTrack`. Defaults to
|
|
79
|
-
* `[reportAbsentTrackType(2011)
|
|
80
|
-
*
|
|
81
|
-
*
|
|
79
|
+
* `[excludeUnplayableTracks, reportAbsentTrackType(2011)]` — prune the renditions
|
|
80
|
+
* this environment can't decode, then report 2011 if nothing is left (this engine
|
|
81
|
+
* composes only video, so a source with none playable can never play).
|
|
82
82
|
*/
|
|
83
83
|
constraints?: SelectVideoTrackConfig['constraints'];
|
|
84
84
|
/**
|
|
@@ -60,7 +60,7 @@ const shareSignals = makeShareSignals();
|
|
|
60
60
|
function createBackgroundVideoEngine(config = {}) {
|
|
61
61
|
const finalConfig = {
|
|
62
62
|
...config,
|
|
63
|
-
constraints: config.constraints ?? [reportAbsentTrackType(2011)
|
|
63
|
+
constraints: config.constraints ?? [excludeUnplayableTracks, reportAbsentTrackType(2011)],
|
|
64
64
|
rules: config.rules ?? [screenResolutionCap, preferHighestResolution],
|
|
65
65
|
parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,
|
|
66
66
|
resolveDuration: getResolvedSelectedTrackDuration,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine-background-video.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine-background-video.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport type { ScreenResolution } from '../../../media/dom/screen';\nimport { SVTA_NO_SUPPORTED_VIDEO_TRACK, type SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport type { CanPlayTrack, MaybeResolvedPresentation } from '../../../media/types';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport { calculatePresentationDuration } from '../../behaviors/calculate-presentation-duration';\nimport { collectErrors, reportAbsentTrackType } from '../../behaviors/collect-errors';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackScreenResolution } from '../../behaviors/dom/track-screen-resolution';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveVideoTrack } from '../../behaviors/resolve-track';\nimport {\n preferHighestResolution,\n type SelectVideoTrackConfig,\n screenResolutionCap,\n selectVideoTrack,\n} from '../../behaviors/select-tracks';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\nimport { excludeUnplayableTracks } from '../../primitives/selection-rules';\n\n// ============================================================================\n// Background-video engine state & context\n// ============================================================================\n\n/**\n * State shape for the background-video playback engine.\n *\n * Mostly narrower than `HlsVideoEngineState`: audio/text track slots are absent\n * because their selection/resolution behaviors are subtracted. `bandwidthState`\n * is present because `setupVideoBufferActors` declares it and `loadVideoSegments`\n * samples into it (wasted work in this variant — a Phase 3 alt-impl will skip\n * sampling).\n *\n * `screenResolution` is the one slot this variant has and the HLS video engine\n * doesn't, because the screen-size cap is being built here first. It generalizes\n * — the cap is a selection rule both engines can compose — so expect the slot to\n * appear there too rather than staying variant-specific.\n */\nexport interface BackgroundVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n loadActivated?: boolean;\n /**\n * The screen's pixel dimensions, or `undefined` where there is none to read.\n * Written by `trackScreenResolution`, read by the `screenResolutionCap`\n * selection rule — which treats `undefined` as \"don't cap\".\n */\n screenResolution?: ScreenResolution;\n /**\n * Conditions reported while this source is loaded — the per-rendition causes\n * `resolveVideoTrack` reports and the verdict `selectVideoTrack` reports when\n * the constraints prune every rendition. Owned and cleared per source by\n * `collectErrors`; the adapter derives which are fatal.\n */\n errors?: SvtaError[];\n}\n\n/**\n * Context shape for the background-video engine.\n */\nexport interface BackgroundVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type BackgroundVideoEngineSignals = {\n state: StateSignals<BackgroundVideoEngineState>;\n context: ContextSignals<BackgroundVideoEngineContext>;\n};\n\n/**\n * Configuration for the background-video engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read. Compared to\n * `HlsVideoEngineConfig`, audio/text/ABR/bandwidth/quality knobs are\n * dropped: the variant subtracts the behaviors that read them.\n */\nexport interface BackgroundVideoEngineConfig\n extends ShareSignalsConfig<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n /**\n * Hard-constraint pre-pass handed to `selectVideoTrack`. Defaults to\n * `[reportAbsentTrackType(2011), excludeUnplayableTracks]` — report a source\n * offering no video at all (this engine composes only video, so it can never\n * play one), then prune the renditions this environment can't decode.\n */\n constraints?: SelectVideoTrackConfig['constraints'];\n /**\n * Selection-rule chain handed to `selectVideoTrack`. Defaults to\n * `[screenResolutionCap, preferHighestResolution]` — narrows to the renditions\n * that fit the screen, takes the largest of those, and pins it for the session.\n *\n * The cap sits ahead of the ranker because a scope that narrows first wins over\n * one applied later; pass `[preferHighestResolution]` alone to opt out and always\n * pin the largest rendition on offer.\n */\n rules?: readonly NonNullable<SelectVideoTrackConfig['rules']>[number][];\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Whether `state.screenResolution` is reported in device pixels. Read by\n * `trackScreenResolution`; defaults to `true`.\n */\n useDevicePixelRatio?: boolean;\n /**\n * Codec/container capability probe read by `selectVideoTrack`'s constraint\n * pre-pass. Defaults to the DOM `canPlayTrack`; override to force-exclude a\n * codec.\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Per-rendition condition reporting, called by `resolveVideoTrack` once a\n * media playlist parses. Defaults to\n * {@link reportUnsupportedTrackConditions}, which reports non-fMP4 containers\n * (1004) and encryption (4008).\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n}\n\n// ============================================================================\n// Background-video playback engine\n// ============================================================================\n\nconst shareSignals = makeShareSignals<BackgroundVideoEngineState, BackgroundVideoEngineContext>();\n\n/**\n * Create a background-video playback engine.\n *\n * Subtractive composition over the HLS engine baseline:\n * audio-side, text-side, ABR-driven, preload-monitoring, and play/seek\n * load-trigger behaviors are removed. `selectVideoTrack` (with a\n * highest-resolution rule by default) replaces `switchVideoQuality`, pinning\n * a single rendition for the session. The initial state seeds\n * `loadActivated: true` so the composition behaves as if preload has\n * already been activated — appropriate for ambient / hero / GIF-replacement\n * surfaces that should start loading the moment a src is set.\n *\n * Error reporting is *not* subtracted: `collectErrors` owns the sequence,\n * `resolveVideoTrack` reports per-rendition causes, and `selectVideoTrack`\n * reports the video verdict when nothing survives its constraints. Without them\n * every unplayable source here is a silent stall — an unsupported container,\n * encryption this engine can't decrypt, and an undecodable codec all leave\n * `HTMLMediaElement.error` null on both Chromium and WebKit.\n *\n * Native `loop` / `muted` / `autoplay` are adapter concerns and live on\n * `HlsBackgroundVideoMediaElement` rather than the engine.\n *\n * @example\n * ```ts\n * let signals: BackgroundVideoEngineSignals;\n * const engine = createBackgroundVideoEngine({\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * await engine.destroy();\n * ```\n */\nexport function createBackgroundVideoEngine(\n config: BackgroundVideoEngineConfig = {}\n): Composition<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n const finalConfig = {\n ...config,\n constraints: config.constraints ?? [reportAbsentTrackType(SVTA_NO_SUPPORTED_VIDEO_TRACK), excludeUnplayableTracks],\n rules: config.rules ?? [screenResolutionCap, preferHighestResolution],\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n resolveDuration: getResolvedSelectedTrackDuration,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n };\n\n return createComposition(\n [\n resolvePresentation,\n // Presentation duration\n calculatePresentationDuration,\n\n // Owns `errors` and its per-source lifecycle; reporters append into it.\n collectErrors,\n\n // Track selection - pinned single-rendition pick on presentation resolve,\n // unpinned again if the constraint pre-pass later prunes every rendition\n // (which is how a container relabel reaches a pick already made).\n selectVideoTrack,\n // Resolve selected video track (fetch its media playlist)\n resolveVideoTrack,\n // Segment loading — video-only.\n loadVideoSegments,\n\n // MSE setup — video-only.\n setupMediaSource,\n updateMediaSourceDuration,\n setupVideoBufferActors,\n\n // Playback tracking\n trackCurrentTime,\n\n // Environment tracking — the signal source for a screen-size rendition\n // cap. Independent of the presentation, so it sits outside the\n // resolve/select/load sequence above.\n trackScreenResolution,\n\n // End of stream coordination\n endOfStream,\n\n // Behavior whose sole purpose is to expose signal refs via a callback\n // (e.g. to an adapter). Listed last so initial signal setup has run\n // before the callback fires.\n shareSignals,\n ],\n {\n config: finalConfig,\n initialState: {\n // Note: Set to true until we add preload configuration\n loadActivated: true,\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6JA,MAAM,eAAe,iBAA2E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuChG,SAAgB,4BACd,SAAsC,CAAC,GACgC;CACvE,MAAM,cAAc;EAClB,GAAG;EACH,aAAa,OAAO,eAAe,CAAC,sBAAA,IAAmD,GAAG,uBAAuB;EACjH,OAAO,OAAO,SAAS,CAAC,qBAAqB,uBAAuB;EACpE,mBAAmB,OAAO,qBAAqB;EAC/C,iBAAiB;EACjB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;CAC/E;CAEA,OAAO,kBACL;EACE;EAEA;EAGA;EAKA;EAEA;EAEA;EAGA;EACA;EACA;EAGA;EAKA;EAGA;EAKA;CACF,GACA;EACE,QAAQ;EACR,cAAc,EAEZ,eAAe,KACjB;CACF,CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"engine-background-video.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine-background-video.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport type { ScreenResolution } from '../../../media/dom/screen';\nimport { SVTA_NO_SUPPORTED_VIDEO_TRACK, type SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport type { CanPlayTrack, MaybeResolvedPresentation } from '../../../media/types';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport { calculatePresentationDuration } from '../../behaviors/calculate-presentation-duration';\nimport { collectErrors, reportAbsentTrackType } from '../../behaviors/collect-errors';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackScreenResolution } from '../../behaviors/dom/track-screen-resolution';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveVideoTrack } from '../../behaviors/resolve-track';\nimport {\n preferHighestResolution,\n type SelectVideoTrackConfig,\n screenResolutionCap,\n selectVideoTrack,\n} from '../../behaviors/select-tracks';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\nimport { excludeUnplayableTracks } from '../../primitives/selection-rules';\n\n// ============================================================================\n// Background-video engine state & context\n// ============================================================================\n\n/**\n * State shape for the background-video playback engine.\n *\n * Mostly narrower than `HlsVideoEngineState`: audio/text track slots are absent\n * because their selection/resolution behaviors are subtracted. `bandwidthState`\n * is present because `setupVideoBufferActors` declares it and `loadVideoSegments`\n * samples into it (wasted work in this variant — a Phase 3 alt-impl will skip\n * sampling).\n *\n * `screenResolution` is the one slot this variant has and the HLS video engine\n * doesn't, because the screen-size cap is being built here first. It generalizes\n * — the cap is a selection rule both engines can compose — so expect the slot to\n * appear there too rather than staying variant-specific.\n */\nexport interface BackgroundVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n loadActivated?: boolean;\n /**\n * The screen's pixel dimensions, or `undefined` where there is none to read.\n * Written by `trackScreenResolution`, read by the `screenResolutionCap`\n * selection rule — which treats `undefined` as \"don't cap\".\n */\n screenResolution?: ScreenResolution;\n /**\n * Conditions reported while this source is loaded — the per-rendition causes\n * `resolveVideoTrack` reports and the verdict `selectVideoTrack` reports when\n * the constraints prune every rendition. Owned and cleared per source by\n * `collectErrors`; the adapter derives which are fatal.\n */\n errors?: SvtaError[];\n}\n\n/**\n * Context shape for the background-video engine.\n */\nexport interface BackgroundVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type BackgroundVideoEngineSignals = {\n state: StateSignals<BackgroundVideoEngineState>;\n context: ContextSignals<BackgroundVideoEngineContext>;\n};\n\n/**\n * Configuration for the background-video engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read. Compared to\n * `HlsVideoEngineConfig`, audio/text/ABR/bandwidth/quality knobs are\n * dropped: the variant subtracts the behaviors that read them.\n */\nexport interface BackgroundVideoEngineConfig\n extends ShareSignalsConfig<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n /**\n * Hard-constraint pre-pass handed to `selectVideoTrack`. Defaults to\n * `[excludeUnplayableTracks, reportAbsentTrackType(2011)]` — prune the renditions\n * this environment can't decode, then report 2011 if nothing is left (this engine\n * composes only video, so a source with none playable can never play).\n */\n constraints?: SelectVideoTrackConfig['constraints'];\n /**\n * Selection-rule chain handed to `selectVideoTrack`. Defaults to\n * `[screenResolutionCap, preferHighestResolution]` — narrows to the renditions\n * that fit the screen, takes the largest of those, and pins it for the session.\n *\n * The cap sits ahead of the ranker because a scope that narrows first wins over\n * one applied later; pass `[preferHighestResolution]` alone to opt out and always\n * pin the largest rendition on offer.\n */\n rules?: readonly NonNullable<SelectVideoTrackConfig['rules']>[number][];\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Whether `state.screenResolution` is reported in device pixels. Read by\n * `trackScreenResolution`; defaults to `true`.\n */\n useDevicePixelRatio?: boolean;\n /**\n * Codec/container capability probe read by `selectVideoTrack`'s constraint\n * pre-pass. Defaults to the DOM `canPlayTrack`; override to force-exclude a\n * codec.\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Per-rendition condition reporting, called by `resolveVideoTrack` once a\n * media playlist parses. Defaults to\n * {@link reportUnsupportedTrackConditions}, which reports non-fMP4 containers\n * (1004) and encryption (4008).\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n}\n\n// ============================================================================\n// Background-video playback engine\n// ============================================================================\n\nconst shareSignals = makeShareSignals<BackgroundVideoEngineState, BackgroundVideoEngineContext>();\n\n/**\n * Create a background-video playback engine.\n *\n * Subtractive composition over the HLS engine baseline:\n * audio-side, text-side, ABR-driven, preload-monitoring, and play/seek\n * load-trigger behaviors are removed. `selectVideoTrack` (with a\n * highest-resolution rule by default) replaces `switchVideoQuality`, pinning\n * a single rendition for the session. The initial state seeds\n * `loadActivated: true` so the composition behaves as if preload has\n * already been activated — appropriate for ambient / hero / GIF-replacement\n * surfaces that should start loading the moment a src is set.\n *\n * Error reporting is *not* subtracted: `collectErrors` owns the sequence,\n * `resolveVideoTrack` reports per-rendition causes, and `selectVideoTrack`\n * reports the video verdict when nothing survives its constraints. Without them\n * every unplayable source here is a silent stall — an unsupported container,\n * encryption this engine can't decrypt, and an undecodable codec all leave\n * `HTMLMediaElement.error` null on both Chromium and WebKit.\n *\n * Native `loop` / `muted` / `autoplay` are adapter concerns and live on\n * `HlsBackgroundVideoMediaElement` rather than the engine.\n *\n * @example\n * ```ts\n * let signals: BackgroundVideoEngineSignals;\n * const engine = createBackgroundVideoEngine({\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * await engine.destroy();\n * ```\n */\nexport function createBackgroundVideoEngine(\n config: BackgroundVideoEngineConfig = {}\n): Composition<BackgroundVideoEngineState, BackgroundVideoEngineContext> {\n const finalConfig = {\n ...config,\n constraints: config.constraints ?? [excludeUnplayableTracks, reportAbsentTrackType(SVTA_NO_SUPPORTED_VIDEO_TRACK)],\n rules: config.rules ?? [screenResolutionCap, preferHighestResolution],\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n resolveDuration: getResolvedSelectedTrackDuration,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n };\n\n return createComposition(\n [\n resolvePresentation,\n // Presentation duration\n calculatePresentationDuration,\n\n // Owns `errors` and its per-source lifecycle; reporters append into it.\n collectErrors,\n\n // Track selection - pinned single-rendition pick on presentation resolve,\n // unpinned again if the constraint pre-pass later prunes every rendition\n // (which is how a container relabel reaches a pick already made).\n selectVideoTrack,\n // Resolve selected video track (fetch its media playlist)\n resolveVideoTrack,\n // Segment loading — video-only.\n loadVideoSegments,\n\n // MSE setup — video-only.\n setupMediaSource,\n updateMediaSourceDuration,\n setupVideoBufferActors,\n\n // Playback tracking\n trackCurrentTime,\n\n // Environment tracking — the signal source for a screen-size rendition\n // cap. Independent of the presentation, so it sits outside the\n // resolve/select/load sequence above.\n trackScreenResolution,\n\n // End of stream coordination\n endOfStream,\n\n // Behavior whose sole purpose is to expose signal refs via a callback\n // (e.g. to an adapter). Listed last so initial signal setup has run\n // before the callback fires.\n shareSignals,\n ],\n {\n config: finalConfig,\n initialState: {\n // Note: Set to true until we add preload configuration\n loadActivated: true,\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AA6JA,MAAM,eAAe,iBAA2E;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAuChG,SAAgB,4BACd,SAAsC,CAAC,GACgC;CACvE,MAAM,cAAc;EAClB,GAAG;EACH,aAAa,OAAO,eAAe,CAAC,yBAAyB,sBAAA,IAAmD,CAAC;EACjH,OAAO,OAAO,SAAS,CAAC,qBAAqB,uBAAuB;EACpE,mBAAmB,OAAO,qBAAqB;EAC/C,iBAAiB;EACjB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;CAC/E;CAEA,OAAO,kBACL;EACE;EAEA;EAGA;EAKA;EAEA;EAEA;EAGA;EACA;EACA;EAGA;EAKA;EAGA;EAKA;CACF,GACA;EACE,QAAQ;EACR,cAAc,EAEZ,eAAe,KACjB;CACF,CACF;AACF"}
|