@videojs/spf 10.0.0-beta.29 → 10.0.0-beta.30
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/default/media/dom/screen.js +7 -24
- package/dist/default/media/dom/screen.js.map +1 -1
- package/dist/default/media/primitives/resolution.js +29 -0
- package/dist/default/media/primitives/resolution.js.map +1 -0
- package/dist/default/media/primitives/select-tracks.js +17 -1
- package/dist/default/media/primitives/select-tracks.js.map +1 -1
- package/dist/default/playback/adapters/hls-background-video/adapter.js +3 -3
- package/dist/default/playback/adapters/hls-background-video/adapter.js.map +1 -1
- package/dist/default/playback/behaviors/collect-errors.js +8 -8
- package/dist/default/playback/behaviors/collect-errors.js.map +1 -1
- package/dist/default/playback/behaviors/dom/track-player-resolution.js +57 -0
- package/dist/default/playback/behaviors/dom/track-player-resolution.js.map +1 -0
- package/dist/default/playback/behaviors/select-tracks.js.map +1 -1
- package/dist/default/playback/behaviors/track-switching.js +48 -6
- package/dist/default/playback/behaviors/track-switching.js.map +1 -1
- package/dist/default/playback/engines/hls/engine-background-video.js +1 -1
- package/dist/default/playback/engines/hls/engine-background-video.js.map +1 -1
- package/dist/default/playback/engines/hls/engine.js +2 -0
- package/dist/default/playback/engines/hls/engine.js.map +1 -1
- package/dist/default/playback/primitives/selection-rules.js +4 -3
- package/dist/default/playback/primitives/selection-rules.js.map +1 -1
- package/dist/dev/media/dom/screen.d.ts +2 -21
- package/dist/dev/media/dom/screen.d.ts.map +1 -1
- package/dist/dev/media/dom/screen.js +7 -24
- package/dist/dev/media/dom/screen.js.map +1 -1
- package/dist/dev/media/primitives/resolution.d.ts +24 -0
- package/dist/dev/media/primitives/resolution.d.ts.map +1 -0
- package/dist/dev/media/primitives/resolution.js +29 -0
- package/dist/dev/media/primitives/resolution.js.map +1 -0
- package/dist/dev/media/primitives/select-tracks.js +17 -1
- package/dist/dev/media/primitives/select-tracks.js.map +1 -1
- package/dist/dev/playback/adapters/hls-background-video/adapter.js +3 -3
- package/dist/dev/playback/adapters/hls-background-video/adapter.js.map +1 -1
- package/dist/dev/playback/behaviors/collect-errors.js +8 -8
- package/dist/dev/playback/behaviors/collect-errors.js.map +1 -1
- package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts +8 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.d.ts.map +1 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.js +57 -0
- package/dist/dev/playback/behaviors/dom/track-player-resolution.js.map +1 -0
- package/dist/dev/playback/behaviors/select-tracks.d.ts.map +1 -1
- package/dist/dev/playback/behaviors/select-tracks.js.map +1 -1
- package/dist/dev/playback/behaviors/track-switching.js +48 -6
- package/dist/dev/playback/behaviors/track-switching.js.map +1 -1
- package/dist/dev/playback/engines/hls/engine-background-video.d.ts +3 -3
- package/dist/dev/playback/engines/hls/engine-background-video.js +1 -1
- package/dist/dev/playback/engines/hls/engine-background-video.js.map +1 -1
- package/dist/dev/playback/engines/hls/engine.d.ts +19 -0
- package/dist/dev/playback/engines/hls/engine.d.ts.map +1 -1
- package/dist/dev/playback/engines/hls/engine.js +2 -0
- package/dist/dev/playback/engines/hls/engine.js.map +1 -1
- package/dist/dev/playback/primitives/selection-rules.d.ts.map +1 -1
- package/dist/dev/playback/primitives/selection-rules.js +4 -3
- package/dist/dev/playback/primitives/selection-rules.js.map +1 -1
- package/package.json +3 -3
|
@@ -21,6 +21,7 @@ import { QualityConfig } from "../../../media/abr/quality-selection.js";
|
|
|
21
21
|
import { addSubtitlesTracksToMedia, getShowingSubtitlesTrackFromMedia, removeAllSubtitlesTracksFromMedia } from "../../../media/dom/text/text-track-slots.js";
|
|
22
22
|
import { BandwidthConfig, BandwidthState } from "../../../network/bandwidth-estimator.js";
|
|
23
23
|
import "../../actors/dom/text-tracks.js";
|
|
24
|
+
import { PlayerResolution } from "../../behaviors/dom/track-player-resolution.js";
|
|
24
25
|
//#region src/playback/engines/hls/engine.d.ts
|
|
25
26
|
/**
|
|
26
27
|
* State shape for the HLS playback engine.
|
|
@@ -85,6 +86,13 @@ interface HlsVideoEngineState {
|
|
|
85
86
|
*/
|
|
86
87
|
errors?: SvtaError[];
|
|
87
88
|
currentTime?: number;
|
|
89
|
+
/**
|
|
90
|
+
* The player element's rendered pixel dimensions, or `undefined` where there
|
|
91
|
+
* is nothing to measure. Written by `trackPlayerResolution`, read by the
|
|
92
|
+
* `playerResolutionCap` selection rule — which treats `undefined` as
|
|
93
|
+
* "don't cap".
|
|
94
|
+
*/
|
|
95
|
+
playerResolution?: PlayerResolution;
|
|
88
96
|
loadActivated?: boolean;
|
|
89
97
|
/**
|
|
90
98
|
* One-shot command: start the current source at this position
|
|
@@ -237,6 +245,17 @@ interface HlsVideoEngineConfig extends ShareSignalsConfig<HlsVideoEngineState, H
|
|
|
237
245
|
* ratio gating ABR upgrades. Defaults: `DEFAULT_QUALITY_CONFIG` (0.85 / 1.15).
|
|
238
246
|
*/
|
|
239
247
|
quality?: Partial<QualityConfig>;
|
|
248
|
+
/**
|
|
249
|
+
* Whether video renditions are capped to the player element's rendered size.
|
|
250
|
+
* Read by `trackPlayerResolution`; `false` measures nothing, which leaves the
|
|
251
|
+
* `playerResolutionCap` rule inert. Defaults to `true`.
|
|
252
|
+
*/
|
|
253
|
+
capRenditionToPlayerSize?: boolean;
|
|
254
|
+
/**
|
|
255
|
+
* Whether `state.playerResolution` is reported in device pixels. Read by
|
|
256
|
+
* `trackPlayerResolution`; defaults to `true`.
|
|
257
|
+
*/
|
|
258
|
+
useDevicePixelRatio?: boolean;
|
|
240
259
|
/**
|
|
241
260
|
* Multi-CDN failover monitor tuning. `cooldownMs` is how long a CDN stays
|
|
242
261
|
* excluded after a failed fetch trips it. Defaults:
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"engine.d.ts","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"mappings":"
|
|
1
|
+
{"version":3,"file":"engine.d.ts","names":[],"sources":["../../../../../src/playback/engines/hls/engine.ts"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;UA6FiB;;;;;EAKf,eAAe;EACf;EACA;EACA;EACA;EACA,iBAAiB;EAGjB,qBAAqB,eAAe;EACpC,0BAA0B,QAAQ;;;;;;;EAOlC,0BAA0B,QAAQ;;;;;;;;;EASlC,yBAAyB,QAAQ;;;;;;;;;;EAUjC;;;;;;;;EAQA;;;;;;;;EAQA,SAAS;EACT;;;;;;;EAOA,mBAAmB;EACnB;;;;;;;;EAQA;;;;;;;;;EASA;;;;;;;;;EASA;;;;;;;UAQe;EACf,eAAe;EACf,cAAc;EACd,mBAAmB;EACnB,mBAAmB;EACnB,0BAA0B;EAC1B,0BAA0B;EAC1B,kBAAkB;EAClB,8BAA8B;;;;;;;;KASpB;EACV,OAAO,aAAa;EACpB,SAAS,eAAe;;;;;;;;UAST,6BAA6B,mBAAmB,qBAAqB;;;;;EAKpF;;;;;;;;EAQA,eAAe;;;;;;;;EAQf,mCAAmC;EACnC;EACA;EACA;EACA;;;;;;EAMA,0BAA0B,yBAAyB;;;;;;;;;EASnD,kBAAkB;;;;;;EAMlB,oBAAoB;;;;;;EAMpB,mCAAmC;;;;;;EAMnC,2CAA2C;;;;;;EAM3C,2CAA2C;;;;;;;;EAQ3C,gBAAgB,QAAQ;;;;;;;EAOxB,aAAa,QAAQ;;;;;;;EAOrB,YAAY,QAAQ;;;;;;EAMpB,UAAU,QAAQ;;;;;;EAMlB;;;;;EAKA;;;;;;;EAOA,WAAW,QAAQ;;;;;;;;EAQnB,WAAW;;;;;;;;;EASX,uBAAuB;;;;;;;EAOvB;;;;;;;;;EASA,aAAa,WAAW;;;;;;;;;;;;;;;;;;;;;;;;;;;;iBAiDV,qBACd,SAAQ,uBACP,YAAY,qBAAqB"}
|
|
@@ -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"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selection-rules.d.ts","names":[],"sources":["../../../../src/playback/primitives/selection-rules.ts"],"mappings":";;;;;;;;UAwBiB,kBAAkB,iBAAiB,mBAAmB;EACrE,OAAO;EACP,UAAU;EACV,QAAQ;;;;;;;;;;KAWE,cAAc,GAAG,iBAAiB,mBAAmB,qBAC/D,iBAAiB,KACjB,MAAM,kBAAkB,OAAO,SAAS,qBAC5B;;;;;;;;;;;
|
|
1
|
+
{"version":3,"file":"selection-rules.d.ts","names":[],"sources":["../../../../src/playback/primitives/selection-rules.ts"],"mappings":";;;;;;;;UAwBiB,kBAAkB,iBAAiB,mBAAmB;EACrE,OAAO;EACP,UAAU;EACV,QAAQ;;;;;;;;;;KAWE,cAAc,GAAG,iBAAiB,mBAAmB,qBAC/D,iBAAiB,KACjB,MAAM,kBAAkB,OAAO,SAAS,qBAC5B;;;;;;;;;;;UA+EG;EACf,eAAe"}
|
|
@@ -30,9 +30,10 @@ function applyRules(rules, tracks, deps) {
|
|
|
30
30
|
* `applyRules`, this never skips an empty result and never early-bails — every
|
|
31
31
|
* constraint always applies, and an empty survivor set is a real outcome
|
|
32
32
|
* ("nothing playable here"), not a fall-through. Because each constraint only
|
|
33
|
-
* removes, the order they run in can't change
|
|
33
|
+
* removes, the order they run in can't change which tracks survive — though one
|
|
34
|
+
* that also *reports* reads the list at its own position, so placement matters.
|
|
34
35
|
*
|
|
35
|
-
* @param constraints - Constraints to apply
|
|
36
|
+
* @param constraints - Constraints to apply, in order
|
|
36
37
|
* @param tracks - Candidate tracks
|
|
37
38
|
* @param deps - The behavior's `{ state, context, config }`, passed to each constraint
|
|
38
39
|
* @returns The playable survivors (possibly empty)
|
|
@@ -72,7 +73,7 @@ function sameCandidateSet(a, b) {
|
|
|
72
73
|
* Passes everything through when there's no probe (a composition that didn't
|
|
73
74
|
* wire one, or DOM-free tests). When it prunes *every* track, the empty result is
|
|
74
75
|
* preserved (per `applyConstraints`) — "nothing playable" — which each consuming
|
|
75
|
-
* behavior answers by clearing its selection
|
|
76
|
+
* behavior answers by clearing its selection; reporting the verdict is separate.
|
|
76
77
|
*/
|
|
77
78
|
function excludeUnplayableTracks(tracks, { config }) {
|
|
78
79
|
const canPlay = config?.canPlayTrack;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"selection-rules.js","names":[],"sources":["../../../../src/playback/primitives/selection-rules.ts"],"sourcesContent":["/**\n * The selection-rule substrate: the shape of a rule, and the two composers that\n * turn a list of them into a pick.\n *\n * Lives here rather than beside `switchVideoTrack` so both track-selection\n * behaviors can share rules. The simple `selectVideoTrack` variant exists\n * specifically to tree-shake the ABR path out, so importing a composer from\n * `behaviors/track-switching.ts` would drag the bandwidth estimator and quality\n * selection back in with it. These four have no dependencies at all — pure\n * generics over a candidate list — so either side can reach them freely.\n *\n * See `internal/design/spf/track-switching-model.md` for the model these\n * implement: a hard constraints pre-pass, then an ordered chain of soft\n * narrowing rules and rankers, with the pick as the first survivor.\n */\n\nimport type { CanPlayTrack } from '../../media/types';\n\n/**\n * Deps handed to each rule and to `applyRules`, mirroring a behavior's setup\n * deps so a rule reads from the same surfaces a behavior does. `context` is\n * optional — it's threaded through but absent on direct setup calls (and\n * unread by today's rules), so the whole deps object can pass straight through.\n */\nexport interface SelectionRuleDeps<State = unknown, Context = unknown, Config = unknown> {\n state: State;\n context?: Context;\n config: Config;\n}\n\n/**\n * A selection rule narrows or reorders the candidate list. It reads the state,\n * context, and config it needs at apply time (tightly-coupled reads), so a\n * rule's `.get()`s subscribe the running effect to exactly what it consulted.\n * Returning an empty list means \"no match\" — the composer skips it, so a soft\n * filter never narrows the set to nothing. A ranker returns the list with its\n * pick at the head.\n */\nexport type SelectionRule<T, State = unknown, Context = unknown, Config = unknown> = (\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => readonly T[];\n\n/**\n * Apply rules to a candidate list in order; the pick is the first survivor.\n * Two responsibilities the rules don't carry: a rule that returns nothing is\n * skipped (fall-through — a preference never empties the set), and once one\n * survivor remains the chain stops (early-bail — later rules, including the\n * bandwidth ranker, never run, so the effect doesn't subscribe to their\n * signals while the choice is fixed).\n *\n * @param rules - Rules to apply, most authoritative first\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed through to each rule\n * @returns The surviving candidates, pick first\n */\nexport function applyRules<T, State, Context, Config>(\n rules: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const rule of rules) {\n const remaining = rule(current, deps);\n if (remaining.length === 0) continue;\n current = remaining;\n if (current.length === 1) break;\n }\n return current;\n}\n\n/**\n * Apply hard constraints to a candidate list — the pre-pass that runs before the\n * rule chain. A constraint shares a rule's signature but its exclusion is\n * *hard*: it removes the unplayable (a codec the environment can't decode, a CDN\n * in failover cooldown) and a removed track is never attempted. Unlike\n * `applyRules`, this never skips an empty result and never early-bails — every\n * constraint always applies, and an empty survivor set is a real outcome\n * (\"nothing playable here\"), not a fall-through. Because each constraint only\n * removes, the order they run in can't change the
|
|
1
|
+
{"version":3,"file":"selection-rules.js","names":[],"sources":["../../../../src/playback/primitives/selection-rules.ts"],"sourcesContent":["/**\n * The selection-rule substrate: the shape of a rule, and the two composers that\n * turn a list of them into a pick.\n *\n * Lives here rather than beside `switchVideoTrack` so both track-selection\n * behaviors can share rules. The simple `selectVideoTrack` variant exists\n * specifically to tree-shake the ABR path out, so importing a composer from\n * `behaviors/track-switching.ts` would drag the bandwidth estimator and quality\n * selection back in with it. These four have no dependencies at all — pure\n * generics over a candidate list — so either side can reach them freely.\n *\n * See `internal/design/spf/track-switching-model.md` for the model these\n * implement: a hard constraints pre-pass, then an ordered chain of soft\n * narrowing rules and rankers, with the pick as the first survivor.\n */\n\nimport type { CanPlayTrack } from '../../media/types';\n\n/**\n * Deps handed to each rule and to `applyRules`, mirroring a behavior's setup\n * deps so a rule reads from the same surfaces a behavior does. `context` is\n * optional — it's threaded through but absent on direct setup calls (and\n * unread by today's rules), so the whole deps object can pass straight through.\n */\nexport interface SelectionRuleDeps<State = unknown, Context = unknown, Config = unknown> {\n state: State;\n context?: Context;\n config: Config;\n}\n\n/**\n * A selection rule narrows or reorders the candidate list. It reads the state,\n * context, and config it needs at apply time (tightly-coupled reads), so a\n * rule's `.get()`s subscribe the running effect to exactly what it consulted.\n * Returning an empty list means \"no match\" — the composer skips it, so a soft\n * filter never narrows the set to nothing. A ranker returns the list with its\n * pick at the head.\n */\nexport type SelectionRule<T, State = unknown, Context = unknown, Config = unknown> = (\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n) => readonly T[];\n\n/**\n * Apply rules to a candidate list in order; the pick is the first survivor.\n * Two responsibilities the rules don't carry: a rule that returns nothing is\n * skipped (fall-through — a preference never empties the set), and once one\n * survivor remains the chain stops (early-bail — later rules, including the\n * bandwidth ranker, never run, so the effect doesn't subscribe to their\n * signals while the choice is fixed).\n *\n * @param rules - Rules to apply, most authoritative first\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed through to each rule\n * @returns The surviving candidates, pick first\n */\nexport function applyRules<T, State, Context, Config>(\n rules: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const rule of rules) {\n const remaining = rule(current, deps);\n if (remaining.length === 0) continue;\n current = remaining;\n if (current.length === 1) break;\n }\n return current;\n}\n\n/**\n * Apply hard constraints to a candidate list — the pre-pass that runs before the\n * rule chain. A constraint shares a rule's signature but its exclusion is\n * *hard*: it removes the unplayable (a codec the environment can't decode, a CDN\n * in failover cooldown) and a removed track is never attempted. Unlike\n * `applyRules`, this never skips an empty result and never early-bails — every\n * constraint always applies, and an empty survivor set is a real outcome\n * (\"nothing playable here\"), not a fall-through. Because each constraint only\n * removes, the order they run in can't change which tracks survive — though one\n * that also *reports* reads the list at its own position, so placement matters.\n *\n * @param constraints - Constraints to apply, in order\n * @param tracks - Candidate tracks\n * @param deps - The behavior's `{ state, context, config }`, passed to each constraint\n * @returns The playable survivors (possibly empty)\n */\nexport function applyConstraints<T, State, Context, Config>(\n constraints: readonly SelectionRule<T, State, Context, Config>[],\n tracks: readonly T[],\n deps: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n let current = tracks;\n for (const constraint of constraints) current = constraint(current, deps);\n return current;\n}\n\n/**\n * Whether two candidate sets hold the same tracks, by id.\n *\n * The `equals` both selection behaviors give their candidate-set `computed`. A\n * live playlist refresh swaps in a new presentation object carrying the same\n * variants, and a constraint's own inputs can churn without changing which\n * tracks survive; in both cases the set is unchanged and the reaction must not\n * re-fire. Compares by id rather than array identity for exactly that.\n */\nexport function sameCandidateSet<T extends { id: string }>(a: readonly T[], b: readonly T[]): boolean {\n return a.length === b.length && a.every((track) => b.some((other) => other.id === track.id));\n}\n\n/**\n * What {@link excludeUnplayableTracks} reads off the config it is handed.\n *\n * Read through a cast rather than constraining the rule's `Config` generic, the\n * same way `screenResolutionCap` reads `screenResolution` off its state: a rule\n * composes into chains whose config types have nothing else in common, and\n * constraining the generic would make every one of those a weak-type mismatch.\n * Each engine defaults `canPlayTrack` to the DOM-bound probe; unwired means \"no\n * capability filtering\" and the constraint passes everything through.\n */\nexport interface CapabilityConstraintConfig {\n canPlayTrack?: CanPlayTrack;\n}\n\n/**\n * Capability constraint — a *hard* filter for the {@link applyConstraints}\n * pre-pass. Removes renditions this environment can't decode, probed via the\n * injected `canPlayTrack` (codec → `MediaSource.isTypeSupported`, plus the\n * container and encryption assertions that probe can't make). Constraining here\n * — before selection — means an unplayable variant is pruned upstream and never\n * picked, instead of surviving into the pipeline to fail late at\n * `createSourceBuffer`. That late throw stays as a defensive structural\n * guarantee; with this constraint it should rarely fire.\n *\n * Lives here rather than beside `switchVideoTrack` for the reason this module\n * exists: both the re-evaluating variant and the pinned `selectVideoTrack` apply\n * it, and reaching it through `behaviors/track-switching.ts` would drag the ABR\n * path into a composition that deliberately omits it.\n *\n * Passes everything through when there's no probe (a composition that didn't\n * wire one, or DOM-free tests). When it prunes *every* track, the empty result is\n * preserved (per `applyConstraints`) — \"nothing playable\" — which each consuming\n * behavior answers by clearing its selection; reporting the verdict is separate.\n */\nexport function excludeUnplayableTracks<T, State, Context, Config>(\n tracks: readonly T[],\n { config }: SelectionRuleDeps<State, Context, Config>\n): readonly T[] {\n const canPlay = (config as CapabilityConstraintConfig | undefined)?.canPlayTrack;\n if (!canPlay) return tracks;\n return tracks.filter((track) => canPlay(track as Parameters<CanPlayTrack>[0]));\n}\n"],"mappings":";;;;;;;;;;;;;;AAwDA,SAAgB,WACd,OACA,QACA,MACc;CACd,IAAI,UAAU;CACd,KAAK,MAAM,QAAQ,OAAO;EACxB,MAAM,YAAY,KAAK,SAAS,IAAI;EACpC,IAAI,UAAU,WAAW,GAAG;EAC5B,UAAU;EACV,IAAI,QAAQ,WAAW,GAAG;CAC5B;CACA,OAAO;AACT;;;;;;;;;;;;;;;;;AAkBA,SAAgB,iBACd,aACA,QACA,MACc;CACd,IAAI,UAAU;CACd,KAAK,MAAM,cAAc,aAAa,UAAU,WAAW,SAAS,IAAI;CACxE,OAAO;AACT;;;;;;;;;;AAWA,SAAgB,iBAA2C,GAAiB,GAA0B;CACpG,OAAO,EAAE,WAAW,EAAE,UAAU,EAAE,OAAO,UAAU,EAAE,MAAM,UAAU,MAAM,OAAO,MAAM,EAAE,CAAC;AAC7F;;;;;;;;;;;;;;;;;;;;;AAoCA,SAAgB,wBACd,QACA,EAAE,UACY;CACd,MAAM,UAAW,QAAmD;CACpE,IAAI,CAAC,SAAS,OAAO;CACrB,OAAO,OAAO,QAAQ,UAAU,QAAQ,KAAoC,CAAC;AAC/E"}
|
package/package.json
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@videojs/spf",
|
|
3
3
|
"type": "module",
|
|
4
|
-
"version": "10.0.0-beta.
|
|
4
|
+
"version": "10.0.0-beta.30",
|
|
5
5
|
"description": "Stream Processing Framework for Video.js 10",
|
|
6
6
|
"license": "Apache-2.0",
|
|
7
7
|
"repository": {
|
|
@@ -77,8 +77,8 @@
|
|
|
77
77
|
],
|
|
78
78
|
"dependencies": {
|
|
79
79
|
"signal-polyfill": "^0.2.2",
|
|
80
|
-
"@videojs/media": "10.0.0-beta.
|
|
81
|
-
"@videojs/utils": "10.0.0-beta.
|
|
80
|
+
"@videojs/media": "10.0.0-beta.30",
|
|
81
|
+
"@videojs/utils": "10.0.0-beta.30"
|
|
82
82
|
},
|
|
83
83
|
"devDependencies": {
|
|
84
84
|
"@vitest/browser": "^4.1.10",
|