@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.
Files changed (54) hide show
  1. package/dist/default/media/dom/screen.js +7 -24
  2. package/dist/default/media/dom/screen.js.map +1 -1
  3. package/dist/default/media/primitives/resolution.js +29 -0
  4. package/dist/default/media/primitives/resolution.js.map +1 -0
  5. package/dist/default/media/primitives/select-tracks.js +17 -1
  6. package/dist/default/media/primitives/select-tracks.js.map +1 -1
  7. package/dist/default/playback/adapters/hls-background-video/adapter.js +3 -3
  8. package/dist/default/playback/adapters/hls-background-video/adapter.js.map +1 -1
  9. package/dist/default/playback/behaviors/collect-errors.js +8 -8
  10. package/dist/default/playback/behaviors/collect-errors.js.map +1 -1
  11. package/dist/default/playback/behaviors/dom/track-player-resolution.js +57 -0
  12. package/dist/default/playback/behaviors/dom/track-player-resolution.js.map +1 -0
  13. package/dist/default/playback/behaviors/select-tracks.js.map +1 -1
  14. package/dist/default/playback/behaviors/track-switching.js +48 -6
  15. package/dist/default/playback/behaviors/track-switching.js.map +1 -1
  16. package/dist/default/playback/engines/hls/engine-background-video.js +1 -1
  17. package/dist/default/playback/engines/hls/engine-background-video.js.map +1 -1
  18. package/dist/default/playback/engines/hls/engine.js +2 -0
  19. package/dist/default/playback/engines/hls/engine.js.map +1 -1
  20. package/dist/default/playback/primitives/selection-rules.js +4 -3
  21. package/dist/default/playback/primitives/selection-rules.js.map +1 -1
  22. package/dist/dev/media/dom/screen.d.ts +2 -21
  23. package/dist/dev/media/dom/screen.d.ts.map +1 -1
  24. package/dist/dev/media/dom/screen.js +7 -24
  25. package/dist/dev/media/dom/screen.js.map +1 -1
  26. package/dist/dev/media/primitives/resolution.d.ts +24 -0
  27. package/dist/dev/media/primitives/resolution.d.ts.map +1 -0
  28. package/dist/dev/media/primitives/resolution.js +29 -0
  29. package/dist/dev/media/primitives/resolution.js.map +1 -0
  30. package/dist/dev/media/primitives/select-tracks.js +17 -1
  31. package/dist/dev/media/primitives/select-tracks.js.map +1 -1
  32. package/dist/dev/playback/adapters/hls-background-video/adapter.js +3 -3
  33. package/dist/dev/playback/adapters/hls-background-video/adapter.js.map +1 -1
  34. package/dist/dev/playback/behaviors/collect-errors.js +8 -8
  35. package/dist/dev/playback/behaviors/collect-errors.js.map +1 -1
  36. package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts +8 -0
  37. package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts.map +1 -0
  38. package/dist/dev/playback/behaviors/dom/track-player-resolution.js +57 -0
  39. package/dist/dev/playback/behaviors/dom/track-player-resolution.js.map +1 -0
  40. package/dist/dev/playback/behaviors/select-tracks.d.ts.map +1 -1
  41. package/dist/dev/playback/behaviors/select-tracks.js.map +1 -1
  42. package/dist/dev/playback/behaviors/track-switching.js +48 -6
  43. package/dist/dev/playback/behaviors/track-switching.js.map +1 -1
  44. package/dist/dev/playback/engines/hls/engine-background-video.d.ts +3 -3
  45. package/dist/dev/playback/engines/hls/engine-background-video.js +1 -1
  46. package/dist/dev/playback/engines/hls/engine-background-video.js.map +1 -1
  47. package/dist/dev/playback/engines/hls/engine.d.ts +19 -0
  48. package/dist/dev/playback/engines/hls/engine.d.ts.map +1 -1
  49. package/dist/dev/playback/engines/hls/engine.js +2 -0
  50. package/dist/dev/playback/engines/hls/engine.js.map +1 -1
  51. package/dist/dev/playback/primitives/selection-rules.d.ts.map +1 -1
  52. package/dist/dev/playback/primitives/selection-rules.js +4 -3
  53. package/dist/dev/playback/primitives/selection-rules.js.map +1 -1
  54. package/package.json +3 -3
@@ -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 is
26
- * three rules, most authoritative first:
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. **ranking** — the terminal sort: `rankByBandwidth`, shared by video and
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; `switchVideoTrack` also accepts ABR tuning config, `switchAudioTrack`
55
- * takes none. `switchTextTrack` differs selection is *optional* (captions are
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":"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"}
1
+ {"version":3,"file":"track-switching.js","names":["getCdnId","defaultGetCdnId"],"sources":["../../../../src/playback/behaviors/track-switching.ts"],"sourcesContent":["/**\n * **Per-type track selection as a rule chain.** While a presentation is\n * resolved, owns that type's `selected{Video,Audio,Text}TrackId` signal: pick a\n * default, react to user intent and algorithmic ranking, and clear it on src\n * unload.\n *\n * Selection runs in two stages. First a **hard-constraints pre-pass**\n * (`applyConstraints`) prunes the unplayable from the candidate set — the\n * failed-CDN constraint (`excludeFailedCdns`, failover cooldown) and the\n * capability constraint (`excludeUnplayableTracks`, codec support). Then a small\n * ordered chain of rules (`applyRules`) picks among the survivors. Each constraint/rule reads the signals it needs at apply\n * time, so the effect subscribes to exactly what was consulted. The chain 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":"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"}
@@ -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), excludeUnplayableTracks],
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"}
@@ -25,6 +25,7 @@ import { setupAudioBufferActors, setupVideoBufferActors } from "../../behaviors/
25
25
  import { setupMediaSource } from "../../behaviors/dom/setup-mediasource.js";
26
26
  import { syncLiveSeekableRange } from "../../behaviors/dom/sync-live-seekable-range.js";
27
27
  import { syncTextTracks } from "../../behaviors/dom/sync-text-tracks.js";
28
+ import { trackPlayerResolution } from "../../behaviors/dom/track-player-resolution.js";
28
29
  import { updateMediaSourceDuration } from "../../behaviors/dom/update-mediasource-duration.js";
29
30
  import { resolvePresentation } from "../../behaviors/resolve-presentation.js";
30
31
  import { resolveAudioTrack, resolveTextTrack, resolveVideoTrack } from "../../behaviors/resolve-track.js";
@@ -115,6 +116,7 @@ function createHlsVideoEngine(config = {}) {
115
116
  setupAirPlay,
116
117
  trackCurrentTime,
117
118
  applyStartPosition,
119
+ trackPlayerResolution,
118
120
  switchVideoTrack,
119
121
  switchAudioTrack,
120
122
  switchTextTrack,
@@ -1 +1 @@
1
- {"version":3,"file":"engine.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { delayedReschedule } from '../../../core/tasks/delayed-reschedule';\nimport type { Reschedule } from '../../../core/tasks/task';\nimport type { QualityConfig } from '../../../media/abr/quality-selection';\nimport type { BackBufferConfig } from '../../../media/buffer/back-buffer';\nimport type { ForwardBufferConfig } from '../../../media/buffer/forward-buffer';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport { attachMediaSourceAsSourceElement } from '../../../media/dom/mse/mediasource-setup';\nimport { resolveVttSegment } from '../../../media/dom/text/resolve-vtt-segment';\nimport {\n addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia,\n} from '../../../media/dom/text/text-track-slots';\nimport type { SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport { mediaPlaylistReloadDelay, resolveLiveLatency } from '../../../media/hls/reload-policy';\nimport type {\n AudioTrack,\n CanPlayTrack,\n MaybeResolvedPresentation,\n MediaContainerData,\n ResolvedTrack,\n TextTrack,\n VideoTrack,\n} from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { BandwidthConfig, BandwidthState } from '../../../network/bandwidth-estimator';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport type { TextTracksActor } from '../../actors/dom/text-tracks';\nimport type { TextTrackSegmentLoaderActor } from '../../actors/text-track-segment-loader';\nimport {\n calculatePresentationDuration,\n type PresentationDurationResolver,\n} from '../../behaviors/calculate-presentation-duration';\nimport { collectErrors } from '../../behaviors/collect-errors';\nimport { deriveCdnPriority } from '../../behaviors/derive-cdn-priority';\nimport { setupAirPlay } from '../../behaviors/dom/airplay';\nimport { applyStartPosition } from '../../behaviors/dom/apply-start-position';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadAudioSegments, loadTextTrackSegments, loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { seekToLiveEdge } from '../../behaviors/dom/seek-to-live-edge';\nimport { setupAudioBufferActors, setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { setupTextTrackActors } from '../../behaviors/dom/setup-text-track-actors';\nimport { syncLiveSeekableRange } from '../../behaviors/dom/sync-live-seekable-range';\nimport { syncTextTracks } from '../../behaviors/dom/sync-text-tracks';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackLoadTriggers } from '../../behaviors/dom/track-load-triggers';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\n// Non-zero-PTS relocation (spike): remove this import, the composed reactor, the\n// `video/audio/textMessagePipelines` finalConfig entries, the `mediaContainerData`\n// state slot, and the `deriveStartMediaTime` config field to drop relocation entirely\n// (text then falls back to the plain `resolveVttSegment` resolver).\nimport {\n type DeriveStartMediaTime,\n deriveSharedMinStartMediaTime,\n establishStartMediaTime,\n gateFirstParseOnAnchor,\n} from '../../behaviors/establish-start-media-time';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveAudioTrack, resolveTextTrack, resolveVideoTrack } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack, switchTextTrack, switchVideoTrack } from '../../behaviors/track-switching';\nimport { relocatingTextPipelines, relocationPipelinesFor } from '../../primitives/relocation-pipelines';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\nimport type { TextTrackSegmentResolver } from '../../primitives/text-segment-load-pipeline';\n\n// ============================================================================\n// HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the HLS playback engine.\n *\n * This is the union of all state required by the behaviors composed into\n * the HLS engine. Each behavior declares its own state interface; this\n * type satisfies all of them.\n */\nexport interface HlsVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n bandwidthState?: BandwidthState;\n // Non-zero-PTS relocation (spike): transient per-track container data owned by\n // `establishStartMediaTime`. Remove with the composed reactor.\n mediaContainerData?: Record<string, MediaContainerData>;\n userVideoTrackSelection?: Partial<VideoTrack>;\n /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection`. Partial-track shape — `{ language: 'es' }`,\n * `{ id: 'audio-en' }`, etc. `selectAudioTrack` reads this and re-picks\n * when it changes. Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * Consumer-driven *intent* for text selection, resolved into\n * `selectedTextTrackId` by `switchTextTrack`. A language-based partial\n * (`{ language: 'es' }`) selects captions, `'off'` disables them, and absence\n * means auto (the engine's `preferredSubtitleLanguage` / DEFAULT-track policy).\n * Also the write path for the DOM caption UI (via `syncTextTracks`); unlike the\n * resolved id it persists across source changes (sticky preference).\n */\n userTextTrackSelection?: Partial<TextTrack> | 'off';\n /**\n * The CDNs the source is served from (track-URL origins), in manifest\n * priority order — most-preferred first (mirrors HLS content steering's\n * `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`, read by\n * `track-switching`'s `preferActiveCdn` scope, which narrows to the\n * highest-priority CDN with surviving tracks so video / audio / text stay on\n * one host. Only meaningful for redundant-stream sources; a single-CDN source\n * has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids (origins) currently in failover cooldown — written by the CDN\n * monitor when a host fails too often, read by `track-switching`'s\n * `excludeFailedCdns` hard constraint, which prunes their tracks so the\n * active-CDN scope falls to the next CDN in `cdnPriority`. Empty / absent\n * means all CDNs are eligible.\n */\n failedCdns?: string[];\n /**\n * Conditions reported during playback, in the order encountered — appended by\n * whichever behavior detects one (`emitError`), owned and cleared per source by\n * `collectErrors`. Carries no severity: which of these is fatal is decided\n * above the engine, at the adapter. See\n * `internal/design/spf/features/errors.md`.\n */\n errors?: SvtaError[];\n currentTime?: number;\n loadActivated?: boolean;\n /**\n * One-shot command: start the current source at this position\n * (presentation-timeline seconds). Written by consumers or by\n * `setupAirPlay`'s session-end snapshot; consumed (cleared) by\n * `applyStartPosition` once the element seeks. See\n * `behaviors/dom/apply-start-position.ts`.\n */\n startPosition?: number;\n /**\n * Intent-level loading policy: initiate no new loading work while `true`.\n * Written by `setupAirPlay` (the only behavior declaring the key) while a\n * remote-playback session owns presentation; observed by the\n * `loadXSegments` dispatchers (park in `'dormant'`) and by\n * `setupMediaSource` (a pending rebuild waits). See\n * `SegmentLoadingState['loadingSuspended']`.\n */\n loadingSuspended?: boolean;\n /**\n * Author intent for the AirPlay/remote-playback picker, written by the media\n * adapter's `disableRemotePlayback` IDL property. `true` is an explicit\n * opt-out: `setupAirPlay` reads it at attach and sets nothing up, leaving the\n * element's remote playback disabled. Distinct from the underlying\n * `<video>.disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the HLS playback engine.\n *\n * Platform objects and actor references managed by HLS behaviors.\n */\nexport interface HlsVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n audioBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n textTracksActor?: TextTracksActor;\n textTrackSegmentLoaderActor?: TextTrackSegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type HlsVideoEngineSignals = {\n state: StateSignals<HlsVideoEngineState>;\n context: ContextSignals<HlsVideoEngineContext>;\n};\n\n/**\n * Configuration for the HLS playback engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read.\n */\nexport interface HlsVideoEngineConfig extends ShareSignalsConfig<HlsVideoEngineState, HlsVideoEngineContext> {\n /**\n * Bandwidth estimate in bps to use before enough samples have been\n * collected. Default: `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\n initialBandwidth?: number;\n /**\n * Codec capability probe injected into `track-switching`'s\n * `excludeUnplayableTracks` constraint — drops renditions the environment\n * can't decode before selection. Defaults to the `MediaSource.isTypeSupported`\n * -backed `canPlayTrack`; supply your own to override (e.g. force-exclude a\n * codec).\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Conditions reported about each rendition as it resolves — the *causes* behind\n * a later verdict, and the copy a verdict reuses when they agree. Defaults to\n * {@link reportUnsupportedTrackConditions}, which reports non-fMP4 containers\n * and encryption; supply your own to report a different set (a provider that\n * never ships MPEG-TS can drop that check) or `() => []` to report nothing.\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n preferredAudioLanguage?: string;\n preferredSubtitleLanguage?: string;\n includeForcedTracks?: boolean;\n enableDefaultTrack?: boolean;\n /**\n * Resolver that turns a text-track segment fetch into VTT cues.\n * Defaults to the DOM-bound `resolveVttSegment` resolver, which uses an\n * offscreen `<track>` element to parse WebVTT.\n */\n resolveTextTrackSegment?: TextTrackSegmentResolver<VTTCue>;\n /**\n * Resolver for `presentation.duration`. Defaults to picking the first\n * resolved selected track's duration (video preferred, audio fallback) —\n * appropriate for VoD and audio-only. Live engines should supply a\n * resolver that returns `Number.POSITIVE_INFINITY` once the presentation\n * is established as live; downstream `updateMediaSourceDuration` propagates\n * that value to `mediaSource.duration` per the MSE spec.\n */\n resolveDuration?: PresentationDurationResolver;\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser; supply your own for alternate format\n * support without forking the engine.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Allocate SPF-owned text-track slots on the media element. Defaults to\n * the standard `<track>`-element implementation in\n * `media/dom/text/text-track-slots`.\n */\n addSubtitlesTracksToMedia?: typeof addSubtitlesTracksToMedia;\n /**\n * Return the SPF-owned subtitle/caption `TextTrack` currently in showing\n * mode. Defaults to the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n getShowingSubtitlesTrackFromMedia?: typeof getShowingSubtitlesTrackFromMedia;\n /**\n * Evict all SPF-owned text-track slots from the media element. Defaults to\n * the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n removeAllSubtitlesTracksFromMedia?: typeof removeAllSubtitlesTracksFromMedia;\n /**\n * Forward-buffer tuning. `bufferDuration` controls how far ahead of the\n * playhead segments are loaded (and where forward-flush kicks in).\n * Defaults: see `DEFAULT_FORWARD_BUFFER_CONFIG` (30 seconds). Threaded to\n * segment-loader actors (v/a + text) at construction time and to\n * `loadXSegments` dispatchers for the load-message range.\n */\n forwardBuffer?: Partial<ForwardBufferConfig>;\n /**\n * Back-buffer tuning. `keepSegments` controls how many segments stay\n * behind the playhead before eviction. Defaults: see\n * `DEFAULT_BACK_BUFFER_CONFIG` (2 segments). Threaded to the v/a\n * segment-loader actor only (text tracks don't use back-buffer eviction).\n */\n backBuffer?: Partial<BackBufferConfig>;\n /**\n * Bandwidth-estimator tuning. Overrides any field of `BandwidthConfig`\n * (`fastHalfLife`, `slowHalfLife`, `minTotalBytes`, `minBytes`,\n * `minDuration`). `bandwidth.minTotalBytes` supersedes the flat\n * `minTotalBytes` field above. Defaults: see `DEFAULT_BANDWIDTH_CONFIG`.\n */\n bandwidth?: Partial<BandwidthConfig>;\n /**\n * Quality-selection tuning. `safetyMargin` is the bandwidth-headroom\n * multiplier used by `selectQuality`; `upgradeMargin` is the hysteresis\n * ratio gating ABR upgrades. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15).\n */\n quality?: Partial<QualityConfig>;\n /**\n * Multi-CDN failover monitor tuning. `cooldownMs` is how long a CDN stays\n * excluded after a failed fetch trips it. Defaults:\n * `DEFAULT_FAILOVER_MONITOR_CONFIG` (300s). Only meaningful for redundant-stream\n * sources.\n */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * How to derive a CDN grouping key from a track URL — used to build\n * `cdnPriority`, to record the failover trip in `failedCdns`, and by the\n * track-switching CDN scope + failover constraint. One function, read by all of\n * them, so the keys stay comparable. Defaults to the URL origin; override to\n * key on something else (e.g. Mux's `cdn=` query param).\n */\n getCdnId?: GetCdnId;\n /**\n * Non-zero-PTS relocation (spike): the reduce seam consumed by the\n * `establishStartMediaTime` reactor. Defaults to per-track own origin (Tier 1);\n * a Tier-2 variant returns the shared `min` across selected A/V. Relocation is\n * composed into the standard engine below — see the marked block — so this only\n * needs setting to swap the tier policy. See\n * `internal/design/spf/presentation-timeline-model.md`.\n */\n deriveStartMediaTime?: DeriveStartMediaTime;\n /**\n * Proximity window (seconds) for the `recoverEndStall` behavior — how close the\n * playhead must be to the reachable buffered end for a `waiting` to be treated as the\n * end-of-stream freeze and nudged to `ended`. Defaults to `0.2`. See\n * `behaviors/dom/recover-end-stall`.\n */\n endStallNudgeWindow?: number;\n /**\n * Live media-playlist re-run policy for the resolve* loaders' `RecurringRunner`:\n * returns a promise that resolves when the playlist should reload, or `null` to\n * stop. Defaults to `mediaPlaylistReloadDelay` (target-duration cadence, half on\n * an unchanged window, stop on `#EXT-X-ENDLIST`) composed with a cancellable\n * `sleep`. Inert for VoD (a complete playlist stops it after the first resolve).\n * Override to tune live reload timing.\n */\n reschedule?: Reschedule<ResolvedTrack>;\n}\n\n// ============================================================================\n// HLS Playback Engine\n// ============================================================================\n\n/**\n * Generic `shareSignals` instantiated against the HLS engine's full state\n * and context — captures composition signal refs into the consumer's\n * `onSignalsReady` callback at setup time, and materializes input slots that no\n * composed behavior produces: `user*TrackSelection` (track-switching only reads\n * them). `failedCdns` is owned by `setupFailoverMonitor`, so it's already\n * materialized and reachable on the `onSignalsReady` refs without being listed\n * here.\n */\nconst shareSignals = makeShareSignals<HlsVideoEngineState, HlsVideoEngineContext>([\n 'userVideoTrackSelection',\n 'userAudioTrackSelection',\n 'userTextTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an HLS playback engine.\n *\n * Composes SPF behaviors into a reactive pipeline for HLS playback over MSE:\n * manifest resolution, track selection, ABR, segment loading, and\n * end-of-stream coordination.\n *\n * @example\n * ```ts\n * let signals: HlsVideoEngineSignals;\n * const engine = createHlsVideoEngine({\n * initialBandwidth: 2_000_000,\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * videoEl.play();\n *\n * await engine.destroy();\n * ```\n */\nexport function createHlsVideoEngine(\n config: HlsVideoEngineConfig = {}\n): Composition<HlsVideoEngineState, HlsVideoEngineContext> {\n // Non-zero-PTS relocation (spike): resolve the coordination seam once so the reactor\n // (model `startMediaTime`) and the loader stamps (buffer `timestampOffset`) apply the\n // SAME derive. Default is shared-`min` across selected A/V (subsumes per-type).\n const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;\n const finalConfig = {\n ...config,\n deriveStartMediaTime,\n // Baked (not user-overridable): this engine composes `setupAirPlay`,\n // whose native fallback `<source>` requires the MSE attachment to keep\n // sibling source alternatives part of resource selection.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n resolveTextTrackSegment: config.resolveTextTrackSegment ?? resolveVttSegment,\n // Non-zero-PTS relocation (spike): the text pipeline rebases cues onto the\n // relocated 0-based timeline. Remove `textMessagePipelines` to drop text relocation.\n textMessagePipelines: relocatingTextPipelines,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n addSubtitlesTracksToMedia: config.addSubtitlesTracksToMedia ?? addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia: config.getShowingSubtitlesTrackFromMedia ?? getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia: config.removeAllSubtitlesTracksFromMedia ?? removeAllSubtitlesTracksFromMedia,\n // Non-zero-PTS relocation (spike): the discover/stamp steps `establishStartMediaTime`\n // pairs with. They apply the same `deriveStartMediaTime` seam as the reactor. Remove\n // these two lines with the reactor.\n videoMessagePipelines: relocationPipelinesFor('video', deriveStartMediaTime),\n audioMessagePipelines: relocationPipelinesFor('audio', deriveStartMediaTime),\n // Live-anchor establishment order: each non-reference track's first parse\n // waits for the reference track to settle the wall-clock anchor question\n // (see `gate-first-parse.ts`); pairs with the reactor's anchor stamp.\n gateFirstParse: gateFirstParseOnAnchor,\n // Format-neutral live-latency seam for `seekToLiveEdge` — the HLS resolver\n // (HOLD-BACK); a DASH engine would inject `suggestedPresentationDelay`.\n resolveLiveLatency,\n // The resolve* loaders' RecurringRunner re-runs on this `reschedule`: the pure\n // target-duration cadence, start-anchored + made awaitable by `delayedReschedule`.\n // Inert for VoD (the cadence returns null once a playlist is complete), so it\n // composes always.\n reschedule: config.reschedule ?? delayedReschedule(mediaPlaylistReloadDelay),\n };\n\n return createComposition(\n [\n syncPreload,\n trackLoadTriggers,\n resolvePresentation,\n\n // Session-level CDN priority for redundant-stream sources. Owns\n // `cdnPriority`; `track-switching`'s preferActiveCdn scope reads it so\n // every type stays on one CDN. No-op for single-CDN sources.\n //\n // Placed before switch* so `cdnPriority` is set before the first pick —\n // but this ordering is only *mildly* load-bearing, not required for\n // correctness. Selection is reactive: a late `cdnPriority` re-fires the\n // pick and converges on the same result (see the late-arrival test in\n // track-switching.test.ts). Order affects only a transient, and only for\n // an *asymmetric* manifest (a type listing a non-primary CDN first):\n // composing this after switch* would let that type fire one wasted\n // media-playlist fetch to the wrong CDN before correcting. Symmetric\n // redundant streams (the norm) never hit it — the first-listed CDN is\n // already the primary we'd pick anyway.\n deriveCdnPriority,\n\n // CDN failover cooldown: owns the expiry half of failover — watches\n // `failedCdns` (tripped directly by track resolution on a failed\n // media-playlist fetch) and removes each CDN once its cooldown lapses.\n setupFailoverMonitor,\n\n // Owns `errors` and its per-source lifecycle. Composed before the\n // behaviors that report into it so the slot exists when they first run;\n // reporting no-ops if it isn't composed at all.\n collectErrors,\n\n // Resolve selected tracks (fetch media playlists). Composed before the\n // switch* slot owners; selection is reactive, so a resolve* re-fires once\n // its switch* sets the id (same convergence for all three types).\n resolveVideoTrack,\n resolveAudioTrack,\n resolveTextTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Video cluster is registered first so that, when both\n // per-type variants flip to `'buffer-ready'` on the shared gate's\n // monitor evaluation, `addSourceBuffer(video)` runs before\n // `addSourceBuffer(audio)` — see the Firefox `mozHasAudio` invariant\n // in setup-buffer-actors.ts.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // ── Non-zero-PTS relocation (spike) ──────────────────────────────────\n // Establishes per-track `startMediaTime` and publishes the relocating\n // segment-loader pipelines to context. MUST precede `setup*BufferActors`\n // so the pipelines are published before the loaders read them. Remove this\n // one line (+ the import, the `mediaContainerData`/`*MessagePipelines`\n // slots including `textMessagePipelines`, and the `deriveStartMediaTime`\n // config) to drop relocation and test the Tier-0 baseline / bundle size.\n establishStartMediaTime,\n // ─────────────────────────────────────────────────────────────────────\n\n setupVideoBufferActors,\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere).\n setupAirPlay,\n\n // Playback tracking\n trackCurrentTime,\n // After trackCurrentTime: the one-shot currentTime seed must land after\n // the mirror's attach-time sync (see apply-start-position.ts).\n applyStartPosition,\n switchVideoTrack,\n switchAudioTrack,\n // Mid-stream audio-buffer flush on language switch is handled in\n // `segment-loader`'s `planTasks` (predicate: language differs from\n // the previously-buffered track) — not in switchAudioTrack itself.\n\n // Text selection: resolves `userTextTrackSelection` intent (incl. 'off',\n // or the configured preferred-language / DEFAULT-track policy) against the\n // failed-CDN-pruned, active-CDN-scoped text renditions. Optional selection\n // (captions are opt-in), so it can resolve to none.\n switchTextTrack,\n\n // Segment loading\n loadVideoSegments,\n loadAudioSegments,\n\n // Live: declare the seekable window, then command the live-edge start\n // position + keep the playhead in-window. No-op for complete playlists\n // (VoD / ended). `seekToLiveEdge` commands `state.startPosition`;\n // `applyStartPosition` (composed above) performs the seek.\n syncLiveSeekableRange,\n seekToLiveEdge,\n\n // End of stream coordination\n endOfStream,\n // Force native `ended` when Chrome freezes the playhead a few frames short of a\n // skewed-A/V end after `endOfStream` (audio-clock stall). Inert otherwise.\n recoverEndStall,\n\n // Text tracks\n syncTextTracks,\n setupTextTrackActors,\n loadTextTrackSegments,\n\n // Behavior whose sole purpose is to use a callback to allow for signal writing from the outside (e.g. an adapter)\n // NOTE: While not required, adding at the end since behaviors are setup in order, so this increases the likelihood\n // that initial signal setup will have occurred before shareSignals' callback is invoked. (CJP)\n shareSignals,\n ],\n {\n config: finalConfig,\n // Seed bandwidthState so switchVideoTrack fires on initial subscribe\n // with the `initialBandwidth` fallback rather than waiting for the\n // first chunk. The empty sample buffer means `getBandwidthEstimate`\n // returns the configured initial bandwidth until real samples land.\n initialState: {\n bandwidthState: {\n fastEstimate: 0,\n fastTotalWeight: 0,\n slowEstimate: 0,\n slowTotalWeight: 0,\n bytesSampled: 0,\n },\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwWA,MAAM,eAAe,iBAA6D;CAChF;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,qBACd,SAA+B,CAAC,GACyB;CAIzD,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAIA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;EAC7E,yBAAyB,OAAO,2BAA2B;EAG3D,sBAAsB;EACtB,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAC/C,2BAA2B,OAAO,6BAA6B;EAC/D,mCAAmC,OAAO,qCAAqC;EAC/E,mCAAmC,OAAO,qCAAqC;EAI/E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAC3E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAI3E,gBAAgB;EAGhB;EAKA,YAAY,OAAO,cAAc,kBAAkB,wBAAwB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAgBA;EAKA;EAKA;EAKA;EACA;EACA;EAGA;EAOA;EACA;EASA;EAGA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EASA;EAGA;EACA;EAMA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EAKA;CACF,GACA;EACE,QAAQ;EAKR,cAAc,EACZ,gBAAgB;GACd,cAAc;GACd,iBAAiB;GACjB,cAAc;GACd,iBAAiB;GACjB,cAAc;EAChB,EACF;CACF,CACF;AACF"}
1
+ {"version":3,"file":"engine.js","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"sourcesContent":["import {\n type Composition,\n type ContextSignals,\n createComposition,\n type StateSignals,\n} from '../../../core/composition/create-composition';\nimport { makeShareSignals, type ShareSignalsConfig } from '../../../core/composition/share-signals';\nimport { delayedReschedule } from '../../../core/tasks/delayed-reschedule';\nimport type { Reschedule } from '../../../core/tasks/task';\nimport type { QualityConfig } from '../../../media/abr/quality-selection';\nimport type { BackBufferConfig } from '../../../media/buffer/back-buffer';\nimport type { ForwardBufferConfig } from '../../../media/buffer/forward-buffer';\nimport { canPlayTrack } from '../../../media/dom/capabilities';\nimport { attachMediaSourceAsSourceElement } from '../../../media/dom/mse/mediasource-setup';\nimport { resolveVttSegment } from '../../../media/dom/text/resolve-vtt-segment';\nimport {\n addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia,\n} from '../../../media/dom/text/text-track-slots';\nimport type { SvtaError } from '../../../media/errors';\nimport { parseMultivariantPlaylist } from '../../../media/hls/parse-multivariant';\nimport { mediaPlaylistReloadDelay, resolveLiveLatency } from '../../../media/hls/reload-policy';\nimport type {\n AudioTrack,\n CanPlayTrack,\n MaybeResolvedPresentation,\n MediaContainerData,\n ResolvedTrack,\n TextTrack,\n VideoTrack,\n} from '../../../media/types';\nimport type { GetCdnId } from '../../../media/utils/cdn';\nimport { getResolvedSelectedTrackDuration } from '../../../media/utils/track-selection';\nimport type { BandwidthConfig, BandwidthState } from '../../../network/bandwidth-estimator';\nimport type { SegmentLoaderActor } from '../../actors/dom/segment-loader';\nimport type { SourceBufferActor } from '../../actors/dom/source-buffer';\nimport type { TextTracksActor } from '../../actors/dom/text-tracks';\nimport type { TextTrackSegmentLoaderActor } from '../../actors/text-track-segment-loader';\nimport {\n calculatePresentationDuration,\n type PresentationDurationResolver,\n} from '../../behaviors/calculate-presentation-duration';\nimport { collectErrors } from '../../behaviors/collect-errors';\nimport { deriveCdnPriority } from '../../behaviors/derive-cdn-priority';\nimport { setupAirPlay } from '../../behaviors/dom/airplay';\nimport { applyStartPosition } from '../../behaviors/dom/apply-start-position';\nimport { endOfStream } from '../../behaviors/dom/end-of-stream';\nimport { loadAudioSegments, loadTextTrackSegments, loadVideoSegments } from '../../behaviors/dom/load-segments';\nimport { recoverEndStall } from '../../behaviors/dom/recover-end-stall';\nimport { seekToLiveEdge } from '../../behaviors/dom/seek-to-live-edge';\nimport { setupAudioBufferActors, setupVideoBufferActors } from '../../behaviors/dom/setup-buffer-actors';\nimport { setupMediaSource } from '../../behaviors/dom/setup-mediasource';\nimport { setupTextTrackActors } from '../../behaviors/dom/setup-text-track-actors';\nimport { syncLiveSeekableRange } from '../../behaviors/dom/sync-live-seekable-range';\nimport { syncTextTracks } from '../../behaviors/dom/sync-text-tracks';\nimport { trackCurrentTime } from '../../behaviors/dom/track-current-time';\nimport { trackLoadTriggers } from '../../behaviors/dom/track-load-triggers';\nimport { type PlayerResolution, trackPlayerResolution } from '../../behaviors/dom/track-player-resolution';\nimport { updateMediaSourceDuration } from '../../behaviors/dom/update-mediasource-duration';\n// Non-zero-PTS relocation (spike): remove this import, the composed reactor, the\n// `video/audio/textMessagePipelines` finalConfig entries, the `mediaContainerData`\n// state slot, and the `deriveStartMediaTime` config field to drop relocation entirely\n// (text then falls back to the plain `resolveVttSegment` resolver).\nimport {\n type DeriveStartMediaTime,\n deriveSharedMinStartMediaTime,\n establishStartMediaTime,\n gateFirstParseOnAnchor,\n} from '../../behaviors/establish-start-media-time';\nimport { type ParsePresentation, resolvePresentation } from '../../behaviors/resolve-presentation';\nimport { resolveAudioTrack, resolveTextTrack, resolveVideoTrack } from '../../behaviors/resolve-track';\nimport { type FailoverMonitorConfig, setupFailoverMonitor } from '../../behaviors/setup-failover-monitor';\nimport { syncPreload } from '../../behaviors/sync-preload';\nimport { switchAudioTrack, switchTextTrack, switchVideoTrack } from '../../behaviors/track-switching';\nimport { relocatingTextPipelines, relocationPipelinesFor } from '../../primitives/relocation-pipelines';\nimport {\n type ReportUnsupportedTrackConditions,\n reportUnsupportedTrackConditions,\n} from '../../primitives/report-track-conditions';\nimport type { TextTrackSegmentResolver } from '../../primitives/text-segment-load-pipeline';\n\n// ============================================================================\n// HLS Engine State & Context\n// ============================================================================\n\n/**\n * State shape for the HLS playback engine.\n *\n * This is the union of all state required by the behaviors composed into\n * the HLS engine. Each behavior declares its own state interface; this\n * type satisfies all of them.\n */\nexport interface HlsVideoEngineState {\n /**\n * The presentation being played. A caller writes `{ url }`;\n * `resolvePresentation` parses the manifest and populates the rest.\n */\n presentation?: MaybeResolvedPresentation;\n preload?: 'auto' | 'metadata' | 'none';\n selectedVideoTrackId?: string;\n selectedAudioTrackId?: string;\n selectedTextTrackId?: string;\n bandwidthState?: BandwidthState;\n // Non-zero-PTS relocation (spike): transient per-track container data owned by\n // `establishStartMediaTime`. Remove with the composed reactor.\n mediaContainerData?: Record<string, MediaContainerData>;\n userVideoTrackSelection?: Partial<VideoTrack>;\n /**\n * Consumer-driven constraint narrowing the audio candidate set. Sibling\n * of `userVideoTrackSelection`. Partial-track shape — `{ language: 'es' }`,\n * `{ id: 'audio-en' }`, etc. `selectAudioTrack` reads this and re-picks\n * when it changes. Multi-language-audio Tier 2 programmatic-write path.\n */\n userAudioTrackSelection?: Partial<AudioTrack>;\n /**\n * Consumer-driven *intent* for text selection, resolved into\n * `selectedTextTrackId` by `switchTextTrack`. A language-based partial\n * (`{ language: 'es' }`) selects captions, `'off'` disables them, and absence\n * means auto (the engine's `preferredSubtitleLanguage` / DEFAULT-track policy).\n * Also the write path for the DOM caption UI (via `syncTextTracks`); unlike the\n * resolved id it persists across source changes (sticky preference).\n */\n userTextTrackSelection?: Partial<TextTrack> | 'off';\n /**\n * The CDNs the source is served from (track-URL origins), in manifest\n * priority order — most-preferred first (mirrors HLS content steering's\n * `PATHWAY-PRIORITY`). Owned by `deriveCdnPriority`, read by\n * `track-switching`'s `preferActiveCdn` scope, which narrows to the\n * highest-priority CDN with surviving tracks so video / audio / text stay on\n * one host. Only meaningful for redundant-stream sources; a single-CDN source\n * has one entry.\n */\n cdnPriority?: string[];\n /**\n * CDN ids (origins) currently in failover cooldown — written by the CDN\n * monitor when a host fails too often, read by `track-switching`'s\n * `excludeFailedCdns` hard constraint, which prunes their tracks so the\n * active-CDN scope falls to the next CDN in `cdnPriority`. Empty / absent\n * means all CDNs are eligible.\n */\n failedCdns?: string[];\n /**\n * Conditions reported during playback, in the order encountered — appended by\n * whichever behavior detects one (`emitError`), owned and cleared per source by\n * `collectErrors`. Carries no severity: which of these is fatal is decided\n * above the engine, at the adapter. See\n * `internal/design/spf/features/errors.md`.\n */\n errors?: SvtaError[];\n currentTime?: number;\n /**\n * The player element's rendered pixel dimensions, or `undefined` where there\n * is nothing to measure. Written by `trackPlayerResolution`, read by the\n * `playerResolutionCap` selection rule — which treats `undefined` as\n * \"don't cap\".\n */\n playerResolution?: PlayerResolution;\n loadActivated?: boolean;\n /**\n * One-shot command: start the current source at this position\n * (presentation-timeline seconds). Written by consumers or by\n * `setupAirPlay`'s session-end snapshot; consumed (cleared) by\n * `applyStartPosition` once the element seeks. See\n * `behaviors/dom/apply-start-position.ts`.\n */\n startPosition?: number;\n /**\n * Intent-level loading policy: initiate no new loading work while `true`.\n * Written by `setupAirPlay` (the only behavior declaring the key) while a\n * remote-playback session owns presentation; observed by the\n * `loadXSegments` dispatchers (park in `'dormant'`) and by\n * `setupMediaSource` (a pending rebuild waits). See\n * `SegmentLoadingState['loadingSuspended']`.\n */\n loadingSuspended?: boolean;\n /**\n * Author intent for the AirPlay/remote-playback picker, written by the media\n * adapter's `disableRemotePlayback` IDL property. `true` is an explicit\n * opt-out: `setupAirPlay` reads it at attach and sets nothing up, leaving the\n * element's remote playback disabled. Distinct from the underlying\n * `<video>.disableRemotePlayback`, which stays programmatically managed\n * (ManagedMediaSource / AirPlay).\n */\n disableRemotePlayback?: boolean;\n}\n\n/**\n * Context shape for the HLS playback engine.\n *\n * Platform objects and actor references managed by HLS behaviors.\n */\nexport interface HlsVideoEngineContext {\n mediaElement?: HTMLMediaElement | undefined;\n mediaSource?: MediaSource;\n videoBufferActor?: SourceBufferActor;\n audioBufferActor?: SourceBufferActor;\n videoSegmentLoaderActor?: SegmentLoaderActor;\n audioSegmentLoaderActor?: SegmentLoaderActor;\n textTracksActor?: TextTracksActor;\n textTrackSegmentLoaderActor?: TextTrackSegmentLoaderActor;\n}\n\n/**\n * The composition signal refs handed to `onSignalsReady` callers — the\n * canonical way to drive the engine externally (writes) or observe its\n * state (reads) without touching `composition.state` / `composition.context`\n * directly.\n */\nexport type HlsVideoEngineSignals = {\n state: StateSignals<HlsVideoEngineState>;\n context: ContextSignals<HlsVideoEngineContext>;\n};\n\n/**\n * Configuration for the HLS playback engine.\n *\n * Each option is consumed by the appropriate behavior — the engine itself\n * has no config beyond what its behaviors read.\n */\nexport interface HlsVideoEngineConfig extends ShareSignalsConfig<HlsVideoEngineState, HlsVideoEngineContext> {\n /**\n * Bandwidth estimate in bps to use before enough samples have been\n * collected. Default: `DEFAULT_INITIAL_BANDWIDTH` (5 Mbps).\n */\n initialBandwidth?: number;\n /**\n * Codec capability probe injected into `track-switching`'s\n * `excludeUnplayableTracks` constraint — drops renditions the environment\n * can't decode before selection. Defaults to the `MediaSource.isTypeSupported`\n * -backed `canPlayTrack`; supply your own to override (e.g. force-exclude a\n * codec).\n */\n canPlayTrack?: CanPlayTrack;\n /**\n * Conditions reported about each rendition as it resolves — the *causes* behind\n * a later verdict, and the copy a verdict reuses when they agree. Defaults to\n * {@link reportUnsupportedTrackConditions}, which reports non-fMP4 containers\n * and encryption; supply your own to report a different set (a provider that\n * never ships MPEG-TS can drop that check) or `() => []` to report nothing.\n */\n reportUnsupportedTrackConditions?: ReportUnsupportedTrackConditions;\n preferredAudioLanguage?: string;\n preferredSubtitleLanguage?: string;\n includeForcedTracks?: boolean;\n enableDefaultTrack?: boolean;\n /**\n * Resolver that turns a text-track segment fetch into VTT cues.\n * Defaults to the DOM-bound `resolveVttSegment` resolver, which uses an\n * offscreen `<track>` element to parse WebVTT.\n */\n resolveTextTrackSegment?: TextTrackSegmentResolver<VTTCue>;\n /**\n * Resolver for `presentation.duration`. Defaults to picking the first\n * resolved selected track's duration (video preferred, audio fallback) —\n * appropriate for VoD and audio-only. Live engines should supply a\n * resolver that returns `Number.POSITIVE_INFINITY` once the presentation\n * is established as live; downstream `updateMediaSourceDuration` propagates\n * that value to `mediaSource.duration` per the MSE spec.\n */\n resolveDuration?: PresentationDurationResolver;\n /**\n * Manifest parser handed to `resolvePresentation`. Defaults to the HLS\n * multivariant-playlist parser; supply your own for alternate format\n * support without forking the engine.\n */\n parsePresentation?: ParsePresentation;\n /**\n * Allocate SPF-owned text-track slots on the media element. Defaults to\n * the standard `<track>`-element implementation in\n * `media/dom/text/text-track-slots`.\n */\n addSubtitlesTracksToMedia?: typeof addSubtitlesTracksToMedia;\n /**\n * Return the SPF-owned subtitle/caption `TextTrack` currently in showing\n * mode. Defaults to the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n getShowingSubtitlesTrackFromMedia?: typeof getShowingSubtitlesTrackFromMedia;\n /**\n * Evict all SPF-owned text-track slots from the media element. Defaults to\n * the standard selector-based implementation in\n * `media/dom/text/text-track-slots`.\n */\n removeAllSubtitlesTracksFromMedia?: typeof removeAllSubtitlesTracksFromMedia;\n /**\n * Forward-buffer tuning. `bufferDuration` controls how far ahead of the\n * playhead segments are loaded (and where forward-flush kicks in).\n * Defaults: see `DEFAULT_FORWARD_BUFFER_CONFIG` (30 seconds). Threaded to\n * segment-loader actors (v/a + text) at construction time and to\n * `loadXSegments` dispatchers for the load-message range.\n */\n forwardBuffer?: Partial<ForwardBufferConfig>;\n /**\n * Back-buffer tuning. `keepSegments` controls how many segments stay\n * behind the playhead before eviction. Defaults: see\n * `DEFAULT_BACK_BUFFER_CONFIG` (2 segments). Threaded to the v/a\n * segment-loader actor only (text tracks don't use back-buffer eviction).\n */\n backBuffer?: Partial<BackBufferConfig>;\n /**\n * Bandwidth-estimator tuning. Overrides any field of `BandwidthConfig`\n * (`fastHalfLife`, `slowHalfLife`, `minTotalBytes`, `minBytes`,\n * `minDuration`). `bandwidth.minTotalBytes` supersedes the flat\n * `minTotalBytes` field above. Defaults: see `DEFAULT_BANDWIDTH_CONFIG`.\n */\n bandwidth?: Partial<BandwidthConfig>;\n /**\n * Quality-selection tuning. `safetyMargin` is the bandwidth-headroom\n * multiplier used by `selectQuality`; `upgradeMargin` is the hysteresis\n * ratio gating ABR upgrades. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15).\n */\n quality?: Partial<QualityConfig>;\n /**\n * Whether video renditions are capped to the player element's rendered size.\n * Read by `trackPlayerResolution`; `false` measures nothing, which leaves the\n * `playerResolutionCap` rule inert. Defaults to `true`.\n */\n capRenditionToPlayerSize?: boolean;\n /**\n * Whether `state.playerResolution` is reported in device pixels. Read by\n * `trackPlayerResolution`; defaults to `true`.\n */\n useDevicePixelRatio?: boolean;\n /**\n * Multi-CDN failover monitor tuning. `cooldownMs` is how long a CDN stays\n * excluded after a failed fetch trips it. Defaults:\n * `DEFAULT_FAILOVER_MONITOR_CONFIG` (300s). Only meaningful for redundant-stream\n * sources.\n */\n failover?: Partial<FailoverMonitorConfig>;\n /**\n * How to derive a CDN grouping key from a track URL — used to build\n * `cdnPriority`, to record the failover trip in `failedCdns`, and by the\n * track-switching CDN scope + failover constraint. One function, read by all of\n * them, so the keys stay comparable. Defaults to the URL origin; override to\n * key on something else (e.g. Mux's `cdn=` query param).\n */\n getCdnId?: GetCdnId;\n /**\n * Non-zero-PTS relocation (spike): the reduce seam consumed by the\n * `establishStartMediaTime` reactor. Defaults to per-track own origin (Tier 1);\n * a Tier-2 variant returns the shared `min` across selected A/V. Relocation is\n * composed into the standard engine below — see the marked block — so this only\n * needs setting to swap the tier policy. See\n * `internal/design/spf/presentation-timeline-model.md`.\n */\n deriveStartMediaTime?: DeriveStartMediaTime;\n /**\n * Proximity window (seconds) for the `recoverEndStall` behavior — how close the\n * playhead must be to the reachable buffered end for a `waiting` to be treated as the\n * end-of-stream freeze and nudged to `ended`. Defaults to `0.2`. See\n * `behaviors/dom/recover-end-stall`.\n */\n endStallNudgeWindow?: number;\n /**\n * Live media-playlist re-run policy for the resolve* loaders' `RecurringRunner`:\n * returns a promise that resolves when the playlist should reload, or `null` to\n * stop. Defaults to `mediaPlaylistReloadDelay` (target-duration cadence, half on\n * an unchanged window, stop on `#EXT-X-ENDLIST`) composed with a cancellable\n * `sleep`. Inert for VoD (a complete playlist stops it after the first resolve).\n * Override to tune live reload timing.\n */\n reschedule?: Reschedule<ResolvedTrack>;\n}\n\n// ============================================================================\n// HLS Playback Engine\n// ============================================================================\n\n/**\n * Generic `shareSignals` instantiated against the HLS engine's full state\n * and context — captures composition signal refs into the consumer's\n * `onSignalsReady` callback at setup time, and materializes input slots that no\n * composed behavior produces: `user*TrackSelection` (track-switching only reads\n * them). `failedCdns` is owned by `setupFailoverMonitor`, so it's already\n * materialized and reachable on the `onSignalsReady` refs without being listed\n * here.\n */\nconst shareSignals = makeShareSignals<HlsVideoEngineState, HlsVideoEngineContext>([\n 'userVideoTrackSelection',\n 'userAudioTrackSelection',\n 'userTextTrackSelection',\n 'disableRemotePlayback',\n]);\n\n/**\n * Create an HLS playback engine.\n *\n * Composes SPF behaviors into a reactive pipeline for HLS playback over MSE:\n * manifest resolution, track selection, ABR, segment loading, and\n * end-of-stream coordination.\n *\n * @example\n * ```ts\n * let signals: HlsVideoEngineSignals;\n * const engine = createHlsVideoEngine({\n * initialBandwidth: 2_000_000,\n * preferredAudioLanguage: 'en',\n * onSignalsReady: (refs) => {\n * signals = refs;\n * },\n * });\n *\n * signals.context.mediaElement.set(videoEl);\n * signals.state.presentation.set({ url: 'https://example.com/stream.m3u8' });\n *\n * videoEl.play();\n *\n * await engine.destroy();\n * ```\n */\nexport function createHlsVideoEngine(\n config: HlsVideoEngineConfig = {}\n): Composition<HlsVideoEngineState, HlsVideoEngineContext> {\n // Non-zero-PTS relocation (spike): resolve the coordination seam once so the reactor\n // (model `startMediaTime`) and the loader stamps (buffer `timestampOffset`) apply the\n // SAME derive. Default is shared-`min` across selected A/V (subsumes per-type).\n const deriveStartMediaTime = config.deriveStartMediaTime ?? deriveSharedMinStartMediaTime;\n const finalConfig = {\n ...config,\n deriveStartMediaTime,\n // Baked (not user-overridable): this engine composes `setupAirPlay`,\n // whose native fallback `<source>` requires the MSE attachment to keep\n // sibling source alternatives part of resource selection.\n attachMediaSource: attachMediaSourceAsSourceElement,\n canPlayTrack: config.canPlayTrack ?? canPlayTrack,\n reportUnsupportedTrackConditions: config.reportUnsupportedTrackConditions ?? reportUnsupportedTrackConditions,\n resolveTextTrackSegment: config.resolveTextTrackSegment ?? resolveVttSegment,\n // Non-zero-PTS relocation (spike): the text pipeline rebases cues onto the\n // relocated 0-based timeline. Remove `textMessagePipelines` to drop text relocation.\n textMessagePipelines: relocatingTextPipelines,\n resolveDuration: config.resolveDuration ?? getResolvedSelectedTrackDuration,\n parsePresentation: config.parsePresentation ?? parseMultivariantPlaylist,\n addSubtitlesTracksToMedia: config.addSubtitlesTracksToMedia ?? addSubtitlesTracksToMedia,\n getShowingSubtitlesTrackFromMedia: config.getShowingSubtitlesTrackFromMedia ?? getShowingSubtitlesTrackFromMedia,\n removeAllSubtitlesTracksFromMedia: config.removeAllSubtitlesTracksFromMedia ?? removeAllSubtitlesTracksFromMedia,\n // Non-zero-PTS relocation (spike): the discover/stamp steps `establishStartMediaTime`\n // pairs with. They apply the same `deriveStartMediaTime` seam as the reactor. Remove\n // these two lines with the reactor.\n videoMessagePipelines: relocationPipelinesFor('video', deriveStartMediaTime),\n audioMessagePipelines: relocationPipelinesFor('audio', deriveStartMediaTime),\n // Live-anchor establishment order: each non-reference track's first parse\n // waits for the reference track to settle the wall-clock anchor question\n // (see `gate-first-parse.ts`); pairs with the reactor's anchor stamp.\n gateFirstParse: gateFirstParseOnAnchor,\n // Format-neutral live-latency seam for `seekToLiveEdge` — the HLS resolver\n // (HOLD-BACK); a DASH engine would inject `suggestedPresentationDelay`.\n resolveLiveLatency,\n // The resolve* loaders' RecurringRunner re-runs on this `reschedule`: the pure\n // target-duration cadence, start-anchored + made awaitable by `delayedReschedule`.\n // Inert for VoD (the cadence returns null once a playlist is complete), so it\n // composes always.\n reschedule: config.reschedule ?? delayedReschedule(mediaPlaylistReloadDelay),\n };\n\n return createComposition(\n [\n syncPreload,\n trackLoadTriggers,\n resolvePresentation,\n\n // Session-level CDN priority for redundant-stream sources. Owns\n // `cdnPriority`; `track-switching`'s preferActiveCdn scope reads it so\n // every type stays on one CDN. No-op for single-CDN sources.\n //\n // Placed before switch* so `cdnPriority` is set before the first pick —\n // but this ordering is only *mildly* load-bearing, not required for\n // correctness. Selection is reactive: a late `cdnPriority` re-fires the\n // pick and converges on the same result (see the late-arrival test in\n // track-switching.test.ts). Order affects only a transient, and only for\n // an *asymmetric* manifest (a type listing a non-primary CDN first):\n // composing this after switch* would let that type fire one wasted\n // media-playlist fetch to the wrong CDN before correcting. Symmetric\n // redundant streams (the norm) never hit it — the first-listed CDN is\n // already the primary we'd pick anyway.\n deriveCdnPriority,\n\n // CDN failover cooldown: owns the expiry half of failover — watches\n // `failedCdns` (tripped directly by track resolution on a failed\n // media-playlist fetch) and removes each CDN once its cooldown lapses.\n setupFailoverMonitor,\n\n // Owns `errors` and its per-source lifecycle. Composed before the\n // behaviors that report into it so the slot exists when they first run;\n // reporting no-ops if it isn't composed at all.\n collectErrors,\n\n // Resolve selected tracks (fetch media playlists). Composed before the\n // switch* slot owners; selection is reactive, so a resolve* re-fires once\n // its switch* sets the id (same convergence for all three types).\n resolveVideoTrack,\n resolveAudioTrack,\n resolveTextTrack,\n\n // Presentation duration\n calculatePresentationDuration,\n\n // MSE setup. Video cluster is registered first so that, when both\n // per-type variants flip to `'buffer-ready'` on the shared gate's\n // monitor evaluation, `addSourceBuffer(video)` runs before\n // `addSourceBuffer(audio)` — see the Firefox `mozHasAudio` invariant\n // in setup-buffer-actors.ts.\n setupMediaSource,\n updateMediaSourceDuration,\n\n // ── Non-zero-PTS relocation (spike) ──────────────────────────────────\n // Establishes per-track `startMediaTime` and publishes the relocating\n // segment-loader pipelines to context. MUST precede `setup*BufferActors`\n // so the pipelines are published before the loaders read them. Remove this\n // one line (+ the import, the `mediaContainerData`/`*MessagePipelines`\n // slots including `textMessagePipelines`, and the `deriveStartMediaTime`\n // config) to drop relocation and test the Tier-0 baseline / bundle size.\n establishStartMediaTime,\n // ─────────────────────────────────────────────────────────────────────\n\n setupVideoBufferActors,\n setupAudioBufferActors,\n\n // AirPlay/MSE bridge (WebKit only; no-op elsewhere).\n setupAirPlay,\n\n // Playback tracking\n trackCurrentTime,\n // After trackCurrentTime: the one-shot currentTime seed must land after\n // the mirror's attach-time sync (see apply-start-position.ts).\n applyStartPosition,\n\n // Ordering isn't load-bearing — selection is reactive, so a measurement\n // that lands after the first pick just re-fires it.\n trackPlayerResolution,\n switchVideoTrack,\n switchAudioTrack,\n // Mid-stream audio-buffer flush on language switch is handled in\n // `segment-loader`'s `planTasks` (predicate: language differs from\n // the previously-buffered track) — not in switchAudioTrack itself.\n\n // Text selection: resolves `userTextTrackSelection` intent (incl. 'off',\n // or the configured preferred-language / DEFAULT-track policy) against the\n // failed-CDN-pruned, active-CDN-scoped text renditions. Optional selection\n // (captions are opt-in), so it can resolve to none.\n switchTextTrack,\n\n // Segment loading\n loadVideoSegments,\n loadAudioSegments,\n\n // Live: declare the seekable window, then command the live-edge start\n // position + keep the playhead in-window. No-op for complete playlists\n // (VoD / ended). `seekToLiveEdge` commands `state.startPosition`;\n // `applyStartPosition` (composed above) performs the seek.\n syncLiveSeekableRange,\n seekToLiveEdge,\n\n // End of stream coordination\n endOfStream,\n // Force native `ended` when Chrome freezes the playhead a few frames short of a\n // skewed-A/V end after `endOfStream` (audio-clock stall). Inert otherwise.\n recoverEndStall,\n\n // Text tracks\n syncTextTracks,\n setupTextTrackActors,\n loadTextTrackSegments,\n\n // Behavior whose sole purpose is to use a callback to allow for signal writing from the outside (e.g. an adapter)\n // NOTE: While not required, adding at the end since behaviors are setup in order, so this increases the likelihood\n // that initial signal setup will have occurred before shareSignals' callback is invoked. (CJP)\n shareSignals,\n ],\n {\n config: finalConfig,\n // Seed bandwidthState so switchVideoTrack fires on initial subscribe\n // with the `initialBandwidth` fallback rather than waiting for the\n // first chunk. The empty sample buffer means `getBandwidthEstimate`\n // returns the configured initial bandwidth until real samples land.\n initialState: {\n bandwidthState: {\n fastEstimate: 0,\n fastTotalWeight: 0,\n slowEstimate: 0,\n slowTotalWeight: 0,\n bytesSampled: 0,\n },\n },\n }\n );\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AA2XA,MAAM,eAAe,iBAA6D;CAChF;CACA;CACA;CACA;AACF,CAAC;;;;;;;;;;;;;;;;;;;;;;;;;;;AA4BD,SAAgB,qBACd,SAA+B,CAAC,GACyB;CAIzD,MAAM,uBAAuB,OAAO,wBAAwB;CAC5D,MAAM,cAAc;EAClB,GAAG;EACH;EAIA,mBAAmB;EACnB,cAAc,OAAO,gBAAgB;EACrC,kCAAkC,OAAO,oCAAoC;EAC7E,yBAAyB,OAAO,2BAA2B;EAG3D,sBAAsB;EACtB,iBAAiB,OAAO,mBAAmB;EAC3C,mBAAmB,OAAO,qBAAqB;EAC/C,2BAA2B,OAAO,6BAA6B;EAC/D,mCAAmC,OAAO,qCAAqC;EAC/E,mCAAmC,OAAO,qCAAqC;EAI/E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAC3E,uBAAuB,uBAAuB,SAAS,oBAAoB;EAI3E,gBAAgB;EAGhB;EAKA,YAAY,OAAO,cAAc,kBAAkB,wBAAwB;CAC7E;CAEA,OAAO,kBACL;EACE;EACA;EACA;EAgBA;EAKA;EAKA;EAKA;EACA;EACA;EAGA;EAOA;EACA;EASA;EAGA;EACA;EAGA;EAGA;EAGA;EAIA;EACA;EACA;EASA;EAGA;EACA;EAMA;EACA;EAGA;EAGA;EAGA;EACA;EACA;EAKA;CACF,GACA;EACE,QAAQ;EAKR,cAAc,EACZ,gBAAgB;GACd,cAAc;GACd,iBAAiB;GACjB,cAAc;GACd,iBAAiB;GACjB,cAAc;EAChB,EACF;CACF,CACF;AACF"}