p2p-media-loader-dashjs 5.0.0-alpha.4 → 5.0.0-alpha.6

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.
@@ -1,6 +1,6 @@
1
1
  import { dashManifestParser, stripPatchLocation } from "p2p-media-loader-core/dash";
2
2
  import { Core, Core as Core$1, INITIAL_LIVE_DELAY, byteRangeFromRangeHeader, debug, downloadTimeMs, liveDelayFor, maxLiveLatencyFor, playerBufferFor, runAll, trackMediaElementPlayback } from "p2p-media-loader-core";
3
- //#region src/types.ts
3
+ // src/types.ts
4
4
  /**
5
5
  * The slice of dash.js's request plumbing the adapter touches, typed
6
6
  * structurally. dash.js's own declarations for these live in
@@ -14,8 +14,7 @@ var REQUEST_TYPE = {
14
14
  MEDIA_SEGMENT: "MediaSegment",
15
15
  INDEX_SEGMENT: "IndexSegment"
16
16
  };
17
- //#endregion
18
- //#region src/loader.ts
17
+ // src/loader.ts
19
18
  var SEGMENT_TYPES = /* @__PURE__ */ new Set([
20
19
  REQUEST_TYPE.INIT_SEGMENT,
21
20
  REQUEST_TYPE.MEDIA_SEGMENT,
@@ -203,8 +202,7 @@ var RequestRouter = class {
203
202
  function isBinary(data) {
204
203
  return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
205
204
  }
206
- //#endregion
207
- //#region src/engine.ts
205
+ // src/engine.ts
208
206
  /** The three dash.js settings that bound how far ahead of the playhead it fetches. */
209
207
  var FORWARD_BUFFER_KEYS = [
210
208
  "bufferTimeDefault",
@@ -663,7 +661,6 @@ function isBufferTime(value) {
663
661
  function isConfigured(value) {
664
662
  return value !== void 0 && value !== null && !Number.isNaN(value);
665
663
  }
666
- //#endregion
667
664
  export { Core, DashJsP2PEngine };
668
665
 
669
666
  //# sourceMappingURL=p2p-media-loader-dashjs.es.js.map
@@ -1 +1 @@
1
- {"version":3,"file":"p2p-media-loader-dashjs.es.js","names":["Core"],"sources":["../src/types.ts","../src/loader.ts","../src/engine.ts"],"sourcesContent":["/**\n * The slice of dash.js's request plumbing the adapter touches, typed\n * structurally. dash.js's own declarations for these live in\n * `@svta/cml-request`, a transitive dependency this package cannot import\n * directly, and the adapter needs only a handful of fields.\n */\n\n/** `HTTPRequest.*_TYPE` values a request carries in `customData.request.type`. */\nexport const REQUEST_TYPE = {\n MPD: \"MPD\",\n INIT_SEGMENT: \"InitializationSegment\",\n MEDIA_SEGMENT: \"MediaSegment\",\n INDEX_SEGMENT: \"IndexSegment\",\n} as const;\n\n/** What `_onprogress` in dash.js's HTTPLoader reads off a progress event. */\nexport type ProgressEventLike = {\n lengthComputable: boolean;\n loaded: number;\n total: number;\n /** Trace duration in ms; dash.js uses it instead of the wall clock when set. */\n time?: number;\n};\n\n/** The dash.js `FragmentRequest` (or `TextRequest`) behind a network request. */\ntype FragmentRequestLike = {\n type?: string | null;\n url?: string | null;\n range?: string | null;\n mediaType?: string | null;\n /** Presentation time of a media segment; `NaN` on an index probe. */\n startTime?: number | null;\n};\n\n/** Callbacks and state dash.js's HTTPLoader hangs on a request. */\ntype RequestCustomData = {\n request?: FragmentRequestLike;\n onloadend?: () => void;\n onprogress?: (event: ProgressEventLike) => void;\n onabort?: () => void;\n ontimeout?: (event: unknown) => void;\n abort?: () => void;\n};\n\n/** `CommonMediaRequest` as HTTPLoader builds it. */\nexport type CommonMediaRequestLike = {\n url: string;\n method?: string;\n responseType?: string;\n headers?: Record<string, string | undefined>;\n customData?: RequestCustomData;\n};\n\n/** `CommonMediaResponse` as HTTPLoader expects the loader to fill it. */\nexport type CommonMediaResponseLike = {\n url?: string;\n status: number;\n statusText?: string;\n headers?: Record<string, string> | null;\n data?: unknown;\n};\n\n/** The instance dash.js's own `XHRLoader` factory produces. */\nexport type XhrLoaderLike = {\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean;\n /** dash.js names the request it abandons; its own loader ignores the name. */\n abort(request?: CommonMediaRequestLike): void;\n};\n\n/**\n * What `FactoryMaker` binds as `this` when it applies an `override`\n * extension: the real instance is `parent`.\n */\nexport type FactoryMakerThis = {\n context: object;\n factory: unknown;\n parent: XhrLoaderLike;\n};\n","import {\n Core,\n ProcessedManifest,\n byteRangeFromRangeHeader,\n debug,\n downloadTimeMs,\n} from \"p2p-media-loader-core\";\nimport { stripPatchLocation } from \"p2p-media-loader-core/dash\";\nimport {\n CommonMediaRequestLike,\n CommonMediaResponseLike,\n FactoryMakerThis,\n REQUEST_TYPE,\n XhrLoaderLike,\n} from \"./types.js\";\n\n/**\n * The engine a player's requests belong to, looked up per request rather than\n * captured: dash.js keeps an extension for the life of the player and offers\n * no way to remove or replace one, so the extension the first engine installs\n * is the one every later engine has to be served by. No binding — the engine\n * was destroyed, or bound to another player — means every request passes\n * through to dash.js's own loader.\n */\nexport type LoaderBinding = {\n core: Core;\n /** Called with what the core read from each MPD, before dash.js parses it. */\n onManifestProcessed?: (manifest: ProcessedManifest) => void;\n /**\n * Called when another engine takes this player on, so the one that had it\n * gives back what it wrote to the player before the new one reads it.\n */\n release?: () => void;\n /**\n * Reports the player's buffer to the core now. Called just before each\n * segment request: dash.js asks for the next segment right after it\n * appends one, and no media element event has reported the append yet.\n */\n reportPlayback?: () => void;\n};\n\nconst SEGMENT_TYPES: ReadonlySet<string> = new Set([\n REQUEST_TYPE.INIT_SEGMENT,\n REQUEST_TYPE.MEDIA_SEGMENT,\n REQUEST_TYPE.INDEX_SEGMENT,\n]);\n\n/**\n * The `XHRLoader` replacement, in the shape dash.js's `FactoryMaker` applies\n * it: a plain function it calls with `this.parent` set to the real loader,\n * whose `load` and `abort` the returned object overrides. Registered per\n * player through `player.extend(\"XHRLoader\", extension, true)`.\n *\n * Every request dash.js makes over HTTP passes through here — MPD, init,\n * media and index segments, licences — and is told apart by the type of the\n * `FragmentRequest` behind it. See specs/player-adapters.md, \"dash.js\".\n */\nexport function createXhrLoaderExtension(\n binding: () => LoaderBinding | undefined,\n) {\n return function xhrLoaderExtension(this: FactoryMakerThis): XhrLoaderLike {\n // FactoryMaker copies the returned `load` and `abort` onto the parent\n // instance itself, so `this.parent.load` would point back here once the\n // override is applied. Keep dash.js's own methods before that happens.\n const { parent } = this;\n const original: XhrLoaderLike = {\n load: parent.load.bind(parent),\n abort: parent.abort.bind(parent),\n };\n const router = new RequestRouter(binding, original);\n return {\n load: (request, response) => router.load(request, response),\n abort: (request) => router.abort(request),\n };\n };\n}\n\n/**\n * One per dash.js XHRLoader, which dash.js builds once per media type and\n * keeps for the life of the player. Exported for its tests; the package's own\n * surface is the extension above.\n */\nexport class RequestRouter {\n private readonly logger = debug(\"p2pml-dashjs:loader\");\n /** The request the core is serving through this loader, while it is. */\n private current?: { request: CommonMediaRequestLike; abort: () => void };\n\n constructor(\n private readonly binding: () => LoaderBinding | undefined,\n private readonly parent: XhrLoaderLike,\n ) {}\n\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean {\n // Nothing reaches a core no engine is driving this player with: an engine\n // that was destroyed would otherwise have its core rebuilt by the next MPD\n // refresh, resuming P2P the integrator had stopped.\n const binding = this.binding();\n if (!binding) return this.parent.load(request, response);\n const { core } = binding;\n\n const type = request.customData?.request?.type ?? undefined;\n const { url } = request;\n const byteRange = byteRangeFromRangeHeader(\n request.headers?.Range ?? request.headers?.range,\n );\n\n // Every MPD dash.js fetches — first load and each refresh — reaches the\n // core before dash.js parses the same bytes.\n if (type === REQUEST_TYPE.MPD) {\n return this.passThroughAndObserve(binding, request, response, (data) => {\n if (typeof data !== \"string\" && !isBinary(data)) return;\n // Take `PatchLocation` out before dash.js reads the same bytes: a\n // player following it refreshes by patch, which the core cannot read,\n // and its registry would freeze at this window. The wrap runs ahead\n // of dash.js's own handler, so what it parses is what is left here.\n // See specs/player-adapters.md.\n const manifest =\n typeof data === \"string\" ? stripPatchLocation(data) : data;\n if (manifest !== data) {\n response.data = manifest;\n this.logger(\"removed PatchLocation from %s\", url);\n }\n // The response URL, when the loader filled it in, follows redirects.\n const responseUrl = response.url;\n const processed = core.processManifest({\n url:\n responseUrl !== undefined && responseUrl !== \"\" ? responseUrl : url,\n requestedUrl: url,\n data: manifest,\n });\n if (processed) binding.onManifestProcessed?.(processed);\n });\n }\n\n if (type !== undefined && SEGMENT_TYPES.has(type)) {\n // A SegmentBase stream's index: dash.js loads it, the core reads the\n // segment list from the same bytes. Recognition, not lookup.\n if (core.isSegmentIndex(url, byteRange)) {\n return this.passThroughAndObserve(\n binding,\n request,\n response,\n (data) => {\n if (!isBinary(data)) return;\n // The window a `SegmentBase` presentation has is known only once\n // its index is read, so what the index says goes the same way a\n // manifest's does: it is the first thing that can place a live\n // player of one.\n const processed = core.processSegmentIndex({\n url,\n byteRange,\n data,\n });\n if (processed) binding.onManifestProcessed?.(processed);\n },\n );\n }\n\n // dash.js's `SegmentBaseLoader`, given no index range, finds the index\n // by probing the file with media-typed range requests. A probe has no\n // start time, where every media segment has one: not a segment the\n // registry could know, so it is passed through without the lookup —\n // and without the registry miss the lookup would report.\n if (\n type === REQUEST_TYPE.MEDIA_SEGMENT &&\n !Number.isFinite(request.customData?.request?.startTime ?? NaN)\n ) {\n return this.parent.load(request, response);\n }\n\n // Whitelist by lookup: a segment the registry knows on a stream with\n // P2P enabled is served by the core; initialization segments and\n // anything the registry does not know load through dash.js itself.\n if (\n type === REQUEST_TYPE.MEDIA_SEGMENT &&\n core.isSegmentLoadable(url, byteRange)\n ) {\n binding.reportPlayback?.();\n this.serve(core, request, response, byteRange);\n return true;\n }\n }\n\n // Licences, certificates, steering, XLink, init segments: untouched.\n return this.parent.load(request, response);\n }\n\n /**\n * dash.js names the request it abandons; its own `XHRLoader` ignores the\n * name and aborts the XHR it made last, which for a request the core is\n * serving is some other request's. So the named request is aborted where it\n * lives: at the core if it is the one being served, at dash.js's loader if\n * not. Named nothing — an older dash.js, whose `abort()` takes no request —\n * both are aborted.\n */\n abort(request?: CommonMediaRequestLike) {\n if (request === undefined) {\n this.current?.abort();\n this.parent.abort();\n return;\n }\n if (this.current?.request === request) {\n this.current.abort();\n return;\n }\n this.parent.abort(request);\n }\n\n private passThroughAndObserve(\n binding: LoaderBinding,\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n observe: (data: unknown) => void,\n ): boolean {\n request.customData ??= {};\n const { customData } = request;\n const original = customData.onloadend;\n // dash.js's XHRLoader copies `onloadend` onto the XHR at `load`, so the\n // wrap has to be in place before the parent runs.\n customData.onloadend = () => {\n try {\n // The same binding, not merely some binding: what this observes was\n // made against that engine's core, and a response landing after that\n // engine let the player go would otherwise rebuild the core it\n // released — even where another engine has since taken the player on.\n if (\n this.binding() === binding &&\n response.status >= 200 &&\n response.status <= 299\n ) {\n observe(response.data);\n }\n } catch (error) {\n this.logger(\"failed to process %s: %O\", request.url, error);\n }\n original?.();\n };\n return this.parent.load(request, response);\n }\n\n private serve(\n core: Core,\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n byteRange: ReturnType<typeof byteRangeFromRangeHeader>,\n ) {\n const { url } = request;\n request.customData ??= {};\n const { customData } = request;\n let settled = false;\n let aborted = false;\n\n const abort = () => {\n if (settled) return;\n aborted = true;\n core.abortSegmentLoading(url, byteRange);\n };\n customData.abort = abort;\n const current = { request, abort };\n this.current = current;\n // Once the request has settled there is nothing left to abort — and this\n // closure holds the scope the response lives in, so a `RequestRouter`\n // that kept it would keep the last segment's bytes for the life of the\n // player, one segment per media type. dash.js builds one XHRLoader per\n // media type and keeps it.\n const settle = () => {\n settled = true;\n if (this.current === current) this.current = undefined;\n };\n\n // The two outcomes are handled by separate arguments to `then`, not by a\n // `catch` chained after it: delivering a segment runs dash.js's own\n // progress and loadend listeners synchronously, and its event bus catches\n // nothing, so a listener that throws would otherwise land in the failure\n // handler and be reported as the core failing to load a segment dash.js\n // has already consumed — which dash.js then fetches again itself.\n core\n .loadSegment(url, { byteRange })\n .then(\n ({ data, bandwidth }) => {\n // The core cannot always cancel in time — a request waiting for the\n // segment storage has no loader yet — so what dash.js has abandoned\n // is dropped here rather than reported as a download.\n settle();\n if (aborted) {\n customData.onabort?.();\n return;\n }\n response.url = url;\n response.status = 200;\n response.statusText = \"OK\";\n response.headers = {};\n response.data = data;\n\n // dash.js measures throughput from progress traces, dropping the\n // first (it carries the latency) and summing the rest. Two events\n // give it one download trace whose duration is the core's bandwidth\n // hint — wall-clock time says nothing about the network for a segment\n // that came from a peer or from storage. Never 0 ms.\n const total = data.byteLength;\n // Delivered in a `try`, ended in a `finally`. `onprogress` runs\n // dash.js's LOADING_PROGRESS listeners synchronously — its event bus\n // catches nothing, and its own ABR abandonment handler is one of\n // them — so a listener that throws would otherwise skip `onloadend`,\n // and `onloadend` is what takes this request off dash.js's list: a\n // request never ended has no watchdog, the fragment promise never\n // settles, and that media type's buffer never advances again. The\n // segment stands as delivered; the throw is theirs, and is logged\n // by the handler below.\n try {\n customData.onprogress?.({\n lengthComputable: true,\n loaded: 0,\n total,\n time: 1,\n });\n customData.onprogress?.({\n lengthComputable: true,\n loaded: total,\n total,\n time: downloadTimeMs(bandwidth, total),\n });\n } finally {\n customData.onloadend?.();\n }\n },\n (error: unknown) => {\n settle();\n // What dash.js abandoned is reported as the abort it asked for: it\n // drops `onloadend` when it aborts and keeps `onabort`, so a failure\n // reported here instead would tell it nothing and leave the segment\n // waiting for the next schedule tick to be asked for again.\n //\n // An abort dash.js did not ask for is not one — the core gives up on\n // a request superseded by the next one, or when the engine lets the\n // player go — and is reported below as the failure it is, so dash.js\n // fetches the segment itself.\n if (aborted) {\n customData.onabort?.();\n return;\n }\n // A non-2xx status is what dash.js's HTTPLoader retries on; the\n // failure is reported as one rather than thrown into dash.js.\n response.url = url;\n response.status = 0;\n response.statusText =\n error instanceof Error ? error.message : String(error);\n response.data = undefined;\n this.logger(\"core failed to load %s: %O\", url, error);\n customData.onloadend?.();\n },\n )\n // Reached only by a throw out of one of the handlers above: a dash.js\n // or integrator listener failing inside the terminal callback it was\n // given — `onloadend` or `onabort`, on delivery or on failure alike.\n // That callback was called exactly once and is not called again; what\n // dash.js does inside it once a listener of its own has thrown is\n // dash.js's to survive, and cannot be repaired from outside it. The\n // throw is logged rather than lost to an unhandled rejection.\n .catch((error: unknown) => {\n this.logger(\n \"dash.js threw while the result for %s was reported to it: %O\",\n url,\n error,\n );\n });\n }\n}\n\nfunction isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView {\n return data instanceof ArrayBuffer || ArrayBuffer.isView(data);\n}\n","import type { MediaPlayerClass, MediaPlayerEvents } from \"dashjs\";\nimport { dashManifestParser } from \"p2p-media-loader-core/dash\";\nimport {\n Core,\n CoreConfig,\n CoreEventMap,\n DefinedCoreConfig,\n DynamicCoreConfig,\n ProcessedManifest,\n debug,\n runAll,\n trackMediaElementPlayback,\n liveDelayFor,\n maxLiveLatencyFor,\n playerBufferFor,\n type LiveDelay,\n INITIAL_LIVE_DELAY,\n} from \"p2p-media-loader-core\";\nimport { createXhrLoaderExtension, type LoaderBinding } from \"./loader.js\";\nimport { diagnostics } from \"./diagnostics.js\";\n\n/** A type for specifying dynamic configuration options that can be changed at runtime for the P2P engine's core. */\nexport type DynamicDashJsP2PEngineConfig = {\n /** Dynamic core config */\n core?: DynamicCoreConfig;\n};\n\n/** Represents the complete configuration for the `DashJsP2PEngine`. */\nexport type DashJsP2PEngineConfig = {\n /** Complete core configuration settings. */\n core: DefinedCoreConfig;\n};\n\n/** Allows for partial configuration settings for the `DashJsP2PEngine`. */\nexport type PartialDashJsP2PEngineConfig = {\n /** Partial core config */\n core?: Partial<CoreConfig>;\n};\n\n/** The three dash.js settings that bound how far ahead of the playhead it fetches. */\nconst FORWARD_BUFFER_KEYS = [\n \"bufferTimeDefault\",\n \"bufferTimeAtTopQuality\",\n \"bufferTimeAtTopQualityLongForm\",\n] as const;\n\ntype ForwardBuffer = Record<(typeof FORWARD_BUFFER_KEYS)[number], number>;\n/** What the player holds under those keys: a length, or a value that is not one. */\ntype HeldBuffer = Partial<Record<keyof ForwardBuffer, number | null>>;\n\ntype Placement = {\n /** False where the integrator placed the player in the live window. */\n readonly managed: boolean;\n /**\n * What the player held before this engine wrote any of it, and what it is\n * given back — every value under the buffer keys, a length or not, so that\n * a key the integrator held as `null` is not left holding a ceiling. The\n * buffer part is a ledger, kept by `noteOutsideBufferWrites`: it follows\n * later writes from outside — the integrator's, and dash.js's own when a\n * quota error makes it shrink the buffer it can afford — keeping the latest\n * of them rather than the lowest, so the last word on a setting is the one\n * honoured and the one restored. A later write to the delay is the\n * integrator placing the player themselves, and hands the whole placement\n * back.\n */\n readonly held: {\n readonly liveDelay?: number;\n readonly useSuggestedPresentationDelay?: boolean;\n readonly buffer: HeldBuffer;\n };\n};\n\n/**\n * The engine driving a player's requests, by player. dash.js keeps an\n * `XHRLoader` extension for the life of the player and ignores every later\n * `extend` for the same name, so the extension the first engine installs must\n * serve whichever engine is bound now — a second engine would otherwise\n * install nothing and quietly do nothing.\n */\nconst bindings = new WeakMap<MediaPlayerClass, LoaderBinding>();\n\nconst STREAM_INITIALIZED: MediaPlayerEvents[\"STREAM_INITIALIZED\"] =\n \"streamInitialized\";\nconst STREAM_TEARDOWN_COMPLETE: MediaPlayerEvents[\"STREAM_TEARDOWN_COMPLETE\"] =\n \"streamTeardownComplete\";\nconst PLAYBACK_PLAYING: MediaPlayerEvents[\"PLAYBACK_PLAYING\"] =\n \"playbackPlaying\";\n\n/**\n * Represents a Peer-to-Peer (P2P) engine designed to enhance media streaming efficiency.\n * This class integrates P2P technologies into dash.js, enabling the distribution of media segments via a peer network\n * alongside traditional HTTP fetching. This reduces server bandwidth costs and improves scalability by sharing the load\n * across multiple clients.\n *\n * The engine has three responsibilities (see specs/player-adapters.md): it\n * hands every MPD dash.js fetches to the core, routes segment requests\n * through the core, and reports playback state from the media element. dash.js's\n * own manifest parsing runs untouched; the core parses the same bytes itself.\n *\n * @example\n * import { MediaPlayer } from \"dashjs\";\n * import { DashJsP2PEngine } from \"p2p-media-loader-dashjs\";\n *\n * const player = MediaPlayer().create();\n * const engine = new DashJsP2PEngine({\n * core: {\n * swarmId: \"example-swarm-id\",\n * announceTrackers: [\"wss://personal.tracker.com\"],\n * },\n * });\n * engine.bindPlayer(player); // before initialize()\n * player.initialize(videoElement, streamUrl, true);\n */\nexport class DashJsP2PEngine {\n private player?: MediaPlayerClass;\n private readonly playback = trackMediaElementPlayback((state) =>\n this.core.updatePlayback(state),\n );\n private readonly core: Core;\n /**\n * What this engine found and what it decided when it took the current\n * source over, or undefined before the first live manifest of one. Read\n * then rather than at bind: `bindPlayer` runs before `initialize`, and the\n * settings an integrator passes in between are theirs to keep.\n */\n private placement?: Placement;\n /** The live delay this engine wrote, if any; see `applyLivePlacement`. */\n private appliedLiveDelay?: number;\n /** The forward buffer this engine wrote, if any; see `forwardBufferSettings`. */\n private appliedBuffer?: ForwardBuffer;\n /**\n * The placement the current source is held to, while this engine places\n * it; see `resyncIfBehind`.\n */\n private liveTarget?: LiveDelay;\n private readonly debug = debug(\"p2pml-dashjs:engine\");\n /** This engine's handlers on the bound player; see specs/diagnostics.md. */\n private listenersToken?: string;\n\n /**\n * Constructs an instance of `DashJsP2PEngine`.\n *\n * @param config An optional configuration for customizing the P2P engine's behavior.\n */\n constructor(config?: PartialDashJsP2PEngineConfig) {\n this.core = new Core({\n ...config?.core,\n // dash.js plays DASH only, so its bundle carries the DASH parser only.\n manifestParsers: config?.core?.manifestParsers ?? [dashManifestParser],\n });\n }\n\n /**\n * Hooks the engine into a dash.js player. Call before `player.initialize()`:\n * the engine replaces the player's `XHRLoader` through `player.extend`,\n * which dash.js resolves when it first loads.\n *\n * @param player The dash.js `MediaPlayer` instance.\n */\n bindPlayer(player: MediaPlayerClass) {\n if (this.player === player) return;\n // Whatever letting go of the last player, or taking this one off the\n // engine that had it, makes of itself: this player is bound either way.\n // A failure there raised from the middle of a bind would leave this\n // engine holding the player with none of its handlers on it, and a second\n // bind to the same player returns at the top — so it would stay that way,\n // while the engine that was released keeps every request routed to a core\n // it has already reset. What failed is raised once the bind is complete.\n const failures = runAll([\n () => {\n if (this.player) this.destroy();\n },\n ]);\n this.player = player;\n\n // The player's settings are read when the first live manifest of a source\n // arrives, not here: `bindPlayer` runs before `initialize`, so what the\n // integrator configures in between would otherwise be taken for dash.js's\n // own defaults and overwritten. (The placement state is empty here: the\n // release above cleared it, or there was never a player to fill it.)\n // An engine that had this player gives it back before this one reads it:\n // a delay left behind by another engine is indistinguishable from one the\n // integrator set, and would be read as a placement that is not ours.\n failures.push(...runAll([() => bindings.get(player)?.release?.()]));\n bindings.set(player, {\n core: this.core,\n onManifestProcessed: this.applyLivePlacement,\n release: this.releasePlayer,\n reportPlayback: () => this.playback.report(),\n });\n player.extend(\n \"XHRLoader\",\n createXhrLoaderExtension(() => bindings.get(player)),\n true,\n );\n\n player.on(STREAM_INITIALIZED, this.handleStreamInitialized);\n player.on(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n player.on(PLAYBACK_PLAYING, this.resyncIfBehind);\n this.listenersToken = diagnostics?.open(\"DashjsPlayerListeners\");\n this.registerMediaElement();\n if (failures.length) throw failures[0];\n }\n\n /**\n * Applies dynamic configuration updates to the P2P engine.\n *\n * @param dynamicConfig The configuration changes to apply.\n */\n applyDynamicConfig(dynamicConfig: DynamicDashJsP2PEngineConfig) {\n if (dynamicConfig.core) this.core.applyDynamicConfig(dynamicConfig.core);\n }\n\n /**\n * Retrieves the current configuration of the `DashJsP2PEngine`.\n *\n * @returns A copy of the configuration; changing it changes nothing in the\n * engine.\n */\n getConfig(): DashJsP2PEngineConfig {\n return { core: this.core.getConfig() };\n }\n\n /**\n * Adds an event listener for the specified event.\n * @param eventName The name of the event to listen for.\n * @param listener The callback function to be invoked when the event is triggered.\n *\n * @example\n * // Assuming `engine` is an instance of DashJsP2PEngine\n *\n * engine.addEventListener('onSegmentLoaded', (details) => {\n * console.log('Segment Loaded:', details);\n * });\n */\n addEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.addEventListener(eventName, listener);\n }\n\n /**\n * Removes an event listener for the specified event.\n * @param eventName The name of the event.\n * @param listener The callback function that was previously added.\n */\n removeEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.removeEventListener(eventName, listener);\n }\n\n /**\n * Places the player in the live window from the window the core just\n * parsed: how far behind the edge it plays, and how far ahead of the\n * playhead it may fetch. The MPD reaches the core before dash.js parses the\n * same bytes, so both are in place when dash.js computes its live position.\n * Re-applied when the window moves by at least half a segment, or when\n * anything else it writes would change.\n */\n private applyLivePlacement = (manifest: ProcessedManifest) => {\n if (!this.player) return;\n const target = liveDelayFor(manifest);\n if (!target) {\n if (manifest.streams.some((stream) => stream.isLive)) {\n // Live, but not yet measurable — a `SegmentBase` stream has no\n // segments until its index is fetched. Hold the player off the edge\n // until a refresh can size the window.\n this.holdOffTheEdge();\n } else {\n // A presentation with nothing live in it is not this engine's to\n // place — and is the one that would otherwise inherit a live window's\n // ceiling, since the settings are the player's and outlive the source.\n this.restorePlacement();\n }\n return;\n }\n\n if (!this.takeOver()) return;\n const { streaming } = this.player.getSettings();\n\n // A delay the player holds that this engine did not write is the\n // integrator placing the player themselves, after the fact: the\n // placement is theirs from here. What this engine wrote to the buffer\n // is given back; the delay is left as they set it, and the next manifest\n // reads it as theirs.\n const delayNow = streaming?.delay?.liveDelay;\n if (\n this.appliedLiveDelay !== undefined &&\n isConfigured(delayNow) &&\n delayNow !== this.appliedLiveDelay\n ) {\n this.debug(\"liveDelay was set from outside; the placement is theirs\");\n this.restorePlacement();\n return;\n }\n\n this.liveTarget = target;\n this.noteOutsideBufferWrites();\n const buffer = this.forwardBufferSettings(target);\n\n // The two halves are compared and written independently. The delay is\n // compared against what this engine placed, never against what the\n // player holds: its own pre-manifest delay would otherwise read as a\n // placement. A window that moved by less than half a segment is the same\n // window — segment durations are not exact multiples — and rewriting the\n // delay for it would move the target dash.js measures its catch-up\n // against for nothing; so a change to the buffer alone writes the buffer\n // alone. `useSuggestedPresentationDelay` is this engine's too: turned back\n // on from outside, dash.js would park the player near the edge.\n //\n // The buffer is compared against what the player holds, because a ceiling\n // is only a ceiling while it is enforced: a setting raised from outside —\n // by the integrator, the only one who raises these — must be brought back\n // down, and comparing against what this engine last intended would leave\n // it raised for as long as the window holds steady.\n const delayMoved =\n this.appliedLiveDelay === undefined ||\n Math.abs(this.appliedLiveDelay - target.delay) >= target.segment / 2 ||\n streaming?.delay?.useSuggestedPresentationDelay !== false;\n const held = streaming?.buffer;\n const bufferChanged = FORWARD_BUFFER_KEYS.some(\n (key) => held?.[key] !== buffer[key],\n );\n if (!delayMoved && !bufferChanged) {\n // Nothing to write, but this is what the player holds and this engine\n // asked for, so it is this engine's — recording it keeps a later change\n // from outside recognisable as one.\n this.appliedBuffer = buffer;\n return;\n }\n\n const update: {\n delay?: { liveDelay: number; useSuggestedPresentationDelay: boolean };\n buffer?: ForwardBuffer;\n } = {};\n if (delayMoved) {\n this.debug(`Setting liveDelay to ${target.delay}`);\n update.delay = {\n liveDelay: target.delay,\n // A server's suggestion places the player near the edge, where\n // there is nothing to share.\n useSuggestedPresentationDelay: false,\n };\n }\n if (bufferChanged) {\n this.debug(`Setting forward buffer to ${buffer.bufferTimeDefault}`);\n update.buffer = buffer;\n }\n this.player.updateSettings({ streaming: update });\n if (delayMoved) this.appliedLiveDelay = target.delay;\n this.appliedBuffer = buffer;\n };\n\n /**\n * Keeps the ledger of what the player holds under the buffer keys that this\n * engine did not write: somebody else's latest word on the setting — the\n * integrator's, or dash.js's own when a quota error makes it shrink the two\n * top-quality buffers it can no longer afford — which the next write would\n * hide. Reading back what the engine wrote as theirs instead would let the\n * ceiling only ever fall, and treating it as nobody's would raise a setting\n * held below the ceiling, which is the one thing a ceiling must not do.\n */\n private noteOutsideBufferWrites() {\n const current = this.player?.getSettings().streaming?.buffer;\n const ceilings = this.placement?.held.buffer;\n if (!ceilings) return;\n for (const key of FORWARD_BUFFER_KEYS) {\n const value = current?.[key];\n if (isBufferTime(value) && value !== this.appliedBuffer?.[key]) {\n ceilings[key] = value;\n }\n }\n }\n\n /**\n * How far ahead of the playhead dash.js may fetch: a segment short of the\n * live delay, never less than a couple of segments — the rule every adapter\n * shares. The core sets its urgency threshold at half of that buffer, and\n * the other half is the time peers have to fill the player's requests; the\n * segment between the buffer and the edge is the one the registry may not\n * know yet.\n *\n * Left alone, dash.js buffers `bufferTimeAtTopQualityLongForm` — a minute,\n * since a dynamic stream is long-form by its duration — which on a live\n * stream is the whole window. Its playhead then sits a live delay behind the\n * edge while its *fetch* position rides the edge itself. It asks for each\n * segment the moment it exists, before any peer can have it, so the stream\n * plays perfectly with no P2P at all. The core knows every segment dash.js\n * can ask for — it reads each MPD before dash.js does, and lists a segment\n * numbered from the clock as it becomes available — so what the edge costs\n * is time for a peer to supply the segment, not a registry miss.\n *\n * Settings the integrator already holds below this are left alone; the value\n * is a ceiling, not a target.\n */\n private forwardBufferSettings(target: LiveDelay) {\n const bufferTime = playerBufferFor(target);\n\n const ceilings: HeldBuffer = this.placement?.held.buffer ?? {};\n const settings = {} as ForwardBuffer;\n for (const key of FORWARD_BUFFER_KEYS) {\n const held = ceilings[key];\n settings[key] =\n isBufferTime(held) && held < bufferTime ? held : bufferTime;\n }\n return settings;\n }\n\n /**\n * Brings the player back to its live delay once a pause or a stall has\n * left it more than `maxLiveLatencyFor` behind the edge. dash.js has no\n * such threshold of its own. It plays on from wherever a pause left it, and\n * its buffer, which ends a fixed distance ahead of the playhead, reaches\n * back past the window the registry lists: every request from there is\n * fetched over HTTP and shared with nobody. Once the next segment is out of\n * the window it stops fetching, plays out the buffer and stalls, and only\n * then moves the playhead — to the tail of the window, from where the next\n * pause carries it out again.\n *\n * Checked when playback starts or resumes, which is when a pause or a stall\n * ends. A DVR window wider than the threshold raises the threshold to the\n * window: a viewer who rewound into it is left where they chose to be, and\n * brought back only once a pause has carried them out of it.\n *\n * dash.js calls its event handlers with no `try` of its own, so what fails\n * here is logged rather than raised.\n */\n private resyncIfBehind = () => {\n const { player, liveTarget } = this;\n if (!player || !liveTarget) return;\n try {\n if (player.isSeeking()) return;\n const limit = Math.max(\n maxLiveLatencyFor(liveTarget),\n player.getDvrWindow().size,\n );\n const latency = player.getCurrentLiveLatency();\n if (!(latency > limit)) return;\n this.debug(`${latency} s behind the edge, past ${limit} s: re-syncing`);\n player.seekToOriginalLive();\n } catch (error) {\n this.debug(\"re-syncing to the live delay failed: %O\", error);\n }\n };\n\n private handleStreamInitialized = () => {\n this.registerMediaElement();\n };\n\n /**\n * The player has finished tearing a stream down. dash.js calls this from\n * its own event bus, which invokes handlers with no `try` of its own: a\n * throw here aborts `StreamController`'s reset half way — leaving its\n * streams, media-error and autoplay state stale, and the controllers after\n * it never reset — and surfaces out of the integrator's `attachSource`.\n * So each step runs on its own and what failed is logged, not raised.\n *\n * The core goes last, because it is the step that can fail: it destroys an\n * integrator's own segment storage, which is free to throw.\n */\n private handleStreamTeardown = () => {\n const failures = runAll([\n () => this.playback.stop(),\n // The next source starts from the player's own settings, and is placed\n // on its own window rather than measured against this one's.\n () => this.restorePlacement(),\n () => this.core.destroy(),\n ]);\n for (const failure of failures) {\n this.debug(\"tearing the stream down failed: %O\", failure);\n }\n };\n\n /**\n * Takes the current source over, once, on its first live manifest: reads\n * what the player holds — which is the integrator's, since nothing of this\n * engine's has been written for this source — and decides from it whether\n * the placement is theirs or ours.\n *\n * dash.js places the player from `liveDelay` when it has one and from\n * `liveDelayFragmentCount` otherwise, so either one is an integrator who\n * placed it themselves. `useSuggestedPresentationDelay` is not: it is on by\n * default, so it says nothing about what they chose.\n *\n * @returns whether this engine places this source.\n */\n private takeOver(): boolean {\n if (this.placement) return this.placement.managed;\n const { player } = this;\n if (!player) return false;\n\n const delay = player.getSettings().streaming?.delay;\n this.placement = {\n managed:\n !isConfigured(delay?.liveDelay) &&\n !isConfigured(delay?.liveDelayFragmentCount),\n held: {\n liveDelay: delay?.liveDelay,\n useSuggestedPresentationDelay: delay?.useSuggestedPresentationDelay,\n buffer: readForwardBuffer(player),\n },\n };\n return this.placement.managed;\n }\n\n /**\n * Where a live player sits until a manifest says how wide its window is.\n * Written for each source that needs it rather than once for the player: a\n * source whose window cannot be sized yet would otherwise be left wherever\n * dash.js puts it, which is at the edge, where there is nothing to share.\n */\n private holdOffTheEdge() {\n if (!this.takeOver() || !this.player) return;\n if (this.appliedLiveDelay !== undefined) return;\n\n this.debug(`Holding liveDelay at ${INITIAL_LIVE_DELAY}`);\n this.player.updateSettings({\n streaming: {\n delay: {\n liveDelay: INITIAL_LIVE_DELAY,\n // A server's suggestion places the player near the edge, where\n // there is nothing to share.\n useSuggestedPresentationDelay: false,\n },\n },\n });\n this.appliedLiveDelay = INITIAL_LIVE_DELAY;\n }\n\n /**\n * Puts back what the player held before this engine wrote anything: the\n * delay and the buffer alike, since they are the two halves of one\n * placement. dash.js keeps both across `attachSource`, so a live window's\n * ceiling would otherwise be inherited by whatever plays next — a VOD\n * source included — and a delay left behind would park the player where P2P\n * wanted it for as long as the player lives.\n *\n * The next source is taken over afresh, and placed on its own window rather\n * than measured against this one's.\n */\n private restorePlacement() {\n const { placement, appliedLiveDelay, appliedBuffer } = this;\n this.placement = undefined;\n this.appliedLiveDelay = undefined;\n this.appliedBuffer = undefined;\n this.liveTarget = undefined;\n if (!this.player || !placement) return;\n\n // Each half is given back only if this engine wrote it. A live window it\n // only held the player in never had its buffer touched, and writing one\n // back would revert whatever the integrator has set since.\n const streaming: {\n delay?: { liveDelay: number; useSuggestedPresentationDelay?: boolean };\n buffer?: HeldBuffer;\n } = {};\n const { held } = placement;\n\n // The delay only while it is still this engine's: written over from\n // outside since, it is the integrator's word, and stays.\n const delayNow = this.player.getSettings().streaming?.delay?.liveDelay;\n if (appliedLiveDelay !== undefined && delayNow === appliedLiveDelay) {\n streaming.delay = {\n // NaN is how dash.js says a delay was never configured.\n liveDelay: held.liveDelay ?? NaN,\n ...(held.useSuggestedPresentationDelay === undefined\n ? {}\n : {\n useSuggestedPresentationDelay: held.useSuggestedPresentationDelay,\n }),\n };\n }\n\n if (appliedBuffer) {\n // Every key that was held, whatever it held: a `null` given back is a\n // `null`, not a ceiling left behind.\n const buffer: HeldBuffer = {};\n for (const key of FORWARD_BUFFER_KEYS) {\n if (key in held.buffer) buffer[key] = held.buffer[key];\n }\n if (Object.keys(buffer).length > 0) streaming.buffer = buffer;\n }\n\n if (Object.keys(streaming).length === 0) return;\n this.debug(\"Restoring the placement the player came with\");\n this.player.updateSettings({\n streaming: streaming as Parameters<\n MediaPlayerClass[\"updateSettings\"]\n >[0][\"streaming\"],\n });\n }\n\n private registerMediaElement() {\n let media: HTMLMediaElement | undefined;\n try {\n // Throws until a view is attached.\n media = this.player?.getVideoElement();\n } catch {\n return;\n }\n if (media) this.playback.watch(media);\n }\n\n /**\n * Cleans up and releases all resources, and unregisters all event handlers.\n * The bound player is let go and given back the settings the engine wrote.\n *\n * Every step runs even when one before it throws, and the first failure is\n * rethrown once all have run. Listeners added with `addEventListener` are\n * not removed: they are on the core, which is emptied, not discarded.\n */\n destroy() {\n // Only if it is still ours: another engine may have taken this player on\n // since, and it has already been given back to it.\n if (this.player && bindings.get(this.player)?.core === this.core) {\n bindings.delete(this.player);\n }\n this.releasePlayer();\n }\n\n /**\n * Lets the player go: stops working for it, gives back what was written to\n * it, and forgets it. Called on `destroy`, and by the next engine to bind\n * the same player.\n *\n * An engine with no player has nothing to load for, so its core is reset\n * and its playback tracker detached. Leaving them running would keep a\n * second core fetching and announcing in the swarm the engine that took the\n * player over is in, driven by the same media element.\n *\n * Every step runs whatever the ones before it made of themselves: the core\n * destroys an integrator's own segment storage and is free to throw, and\n * stopping there would leave the media element reporting playback into a\n * destroyed core, this engine's handlers on the player, and the player\n * carrying the live delay and buffer ceilings this engine wrote. What\n * failed is raised once there is nothing left to let go of — to whoever\n * asked, which on the takeover path is the engine binding this player next,\n * and which is why that one collects it rather than letting it abort a bind\n * already under way.\n */\n private releasePlayer = () => {\n const failures = runAll([\n () => this.playback.stop(),\n () => {\n if (!this.player) return;\n this.player.off(STREAM_INITIALIZED, this.handleStreamInitialized);\n this.player.off(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n this.player.off(PLAYBACK_PLAYING, this.resyncIfBehind);\n diagnostics?.close(this.listenersToken, \"released\");\n this.listenersToken = undefined;\n },\n () => this.restorePlacement(),\n () => this.core.destroy(),\n ]);\n this.player = undefined;\n if (failures.length) throw failures[0];\n };\n}\n\n/** The forward buffer settings a player currently holds. */\nfunction readForwardBuffer(player: MediaPlayerClass): HeldBuffer {\n const buffer = player.getSettings().streaming?.buffer;\n const held: HeldBuffer = {};\n for (const key of FORWARD_BUFFER_KEYS) {\n const value = buffer?.[key];\n if (value !== undefined) held[key] = value;\n }\n return held;\n}\n\n/**\n * Whether a buffer setting the player holds is a length this engine can reason\n * about. dash.js validates nothing an integrator passes to `updateSettings`\n * and its own typings promise a number, so a `null` left by someone clearing\n * a setting would otherwise be read as a length, compared as zero, and handed\n * back to the player as its ceiling.\n */\nfunction isBufferTime(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/** Whether a dash.js setting holds a value rather than its unset default. */\nfunction isConfigured(value: number | null | undefined): boolean {\n return value !== undefined && value !== null && !Number.isNaN(value);\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAa,eAAe;CAC1B,KAAK;CACL,cAAc;CACd,eAAe;CACf,eAAe;AACjB;;;AC4BA,IAAM,gCAAqC,IAAI,IAAI;CACjD,aAAa;CACb,aAAa;CACb,aAAa;AACf,CAAC;;;;;;;;;;;AAYD,SAAgB,yBACd,SACA;CACA,OAAO,SAAS,qBAA0D;EAIxE,MAAM,EAAE,WAAW;EAKnB,MAAM,SAAS,IAAI,cAAc,SAAS;GAHxC,MAAM,OAAO,KAAK,KAAK,MAAM;GAC7B,OAAO,OAAO,MAAM,KAAK,MAAM;EAES,CAAQ;EAClD,OAAO;GACL,OAAO,SAAS,aAAa,OAAO,KAAK,SAAS,QAAQ;GAC1D,QAAQ,YAAY,OAAO,MAAM,OAAO;EAC1C;CACF;AACF;;;;;;AAOA,IAAa,gBA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loader.ts","../src/engine.ts"],"sourcesContent":["/**\n * The slice of dash.js's request plumbing the adapter touches, typed\n * structurally. dash.js's own declarations for these live in\n * `@svta/cml-request`, a transitive dependency this package cannot import\n * directly, and the adapter needs only a handful of fields.\n */\n\n/** `HTTPRequest.*_TYPE` values a request carries in `customData.request.type`. */\nexport const REQUEST_TYPE = {\n MPD: \"MPD\",\n INIT_SEGMENT: \"InitializationSegment\",\n MEDIA_SEGMENT: \"MediaSegment\",\n INDEX_SEGMENT: \"IndexSegment\",\n} as const;\n\n/** What `_onprogress` in dash.js's HTTPLoader reads off a progress event. */\nexport type ProgressEventLike = {\n lengthComputable: boolean;\n loaded: number;\n total: number;\n /** Trace duration in ms; dash.js uses it instead of the wall clock when set. */\n time?: number;\n};\n\n/** The dash.js `FragmentRequest` (or `TextRequest`) behind a network request. */\ntype FragmentRequestLike = {\n type?: string | null;\n url?: string | null;\n range?: string | null;\n mediaType?: string | null;\n /** Presentation time of a media segment; `NaN` on an index probe. */\n startTime?: number | null;\n};\n\n/** Callbacks and state dash.js's HTTPLoader hangs on a request. */\ntype RequestCustomData = {\n request?: FragmentRequestLike;\n onloadend?: () => void;\n onprogress?: (event: ProgressEventLike) => void;\n onabort?: () => void;\n ontimeout?: (event: unknown) => void;\n abort?: () => void;\n};\n\n/** `CommonMediaRequest` as HTTPLoader builds it. */\nexport type CommonMediaRequestLike = {\n url: string;\n method?: string;\n responseType?: string;\n headers?: Record<string, string | undefined>;\n customData?: RequestCustomData;\n};\n\n/** `CommonMediaResponse` as HTTPLoader expects the loader to fill it. */\nexport type CommonMediaResponseLike = {\n url?: string;\n status: number;\n statusText?: string;\n headers?: Record<string, string> | null;\n data?: unknown;\n};\n\n/** The instance dash.js's own `XHRLoader` factory produces. */\nexport type XhrLoaderLike = {\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean;\n /** dash.js names the request it abandons; its own loader ignores the name. */\n abort(request?: CommonMediaRequestLike): void;\n};\n\n/**\n * What `FactoryMaker` binds as `this` when it applies an `override`\n * extension: the real instance is `parent`.\n */\nexport type FactoryMakerThis = {\n context: object;\n factory: unknown;\n parent: XhrLoaderLike;\n};\n","import {\n Core,\n ProcessedManifest,\n byteRangeFromRangeHeader,\n debug,\n downloadTimeMs,\n} from \"p2p-media-loader-core\";\nimport { stripPatchLocation } from \"p2p-media-loader-core/dash\";\nimport {\n CommonMediaRequestLike,\n CommonMediaResponseLike,\n FactoryMakerThis,\n REQUEST_TYPE,\n XhrLoaderLike,\n} from \"./types.js\";\n\n/**\n * The engine a player's requests belong to, looked up per request rather than\n * captured: dash.js keeps an extension for the life of the player and offers\n * no way to remove or replace one, so the extension the first engine installs\n * is the one every later engine has to be served by. No binding — the engine\n * was destroyed, or bound to another player — means every request passes\n * through to dash.js's own loader.\n */\nexport type LoaderBinding = {\n core: Core;\n /** Called with what the core read from each MPD, before dash.js parses it. */\n onManifestProcessed?: (manifest: ProcessedManifest) => void;\n /**\n * Called when another engine takes this player on, so the one that had it\n * gives back what it wrote to the player before the new one reads it.\n */\n release?: () => void;\n /**\n * Reports the player's buffer to the core now. Called just before each\n * segment request: dash.js asks for the next segment right after it\n * appends one, and no media element event has reported the append yet.\n */\n reportPlayback?: () => void;\n};\n\nconst SEGMENT_TYPES: ReadonlySet<string> = new Set([\n REQUEST_TYPE.INIT_SEGMENT,\n REQUEST_TYPE.MEDIA_SEGMENT,\n REQUEST_TYPE.INDEX_SEGMENT,\n]);\n\n/**\n * The `XHRLoader` replacement, in the shape dash.js's `FactoryMaker` applies\n * it: a plain function it calls with `this.parent` set to the real loader,\n * whose `load` and `abort` the returned object overrides. Registered per\n * player through `player.extend(\"XHRLoader\", extension, true)`.\n *\n * Every request dash.js makes over HTTP passes through here — MPD, init,\n * media and index segments, licences — and is told apart by the type of the\n * `FragmentRequest` behind it. See specs/player-adapters.md, \"dash.js\".\n */\nexport function createXhrLoaderExtension(\n binding: () => LoaderBinding | undefined,\n) {\n return function xhrLoaderExtension(this: FactoryMakerThis): XhrLoaderLike {\n // FactoryMaker copies the returned `load` and `abort` onto the parent\n // instance itself, so `this.parent.load` would point back here once the\n // override is applied. Keep dash.js's own methods before that happens.\n const { parent } = this;\n const original: XhrLoaderLike = {\n load: parent.load.bind(parent),\n abort: parent.abort.bind(parent),\n };\n const router = new RequestRouter(binding, original);\n return {\n load: (request, response) => router.load(request, response),\n abort: (request) => router.abort(request),\n };\n };\n}\n\n/**\n * One per dash.js XHRLoader, which dash.js builds once per media type and\n * keeps for the life of the player. Exported for its tests; the package's own\n * surface is the extension above.\n */\nexport class RequestRouter {\n private readonly logger = debug(\"p2pml-dashjs:loader\");\n /** The request the core is serving through this loader, while it is. */\n private current?: { request: CommonMediaRequestLike; abort: () => void };\n\n constructor(\n private readonly binding: () => LoaderBinding | undefined,\n private readonly parent: XhrLoaderLike,\n ) {}\n\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean {\n // Nothing reaches a core no engine is driving this player with: an engine\n // that was destroyed would otherwise have its core rebuilt by the next MPD\n // refresh, resuming P2P the integrator had stopped.\n const binding = this.binding();\n if (!binding) return this.parent.load(request, response);\n const { core } = binding;\n\n const type = request.customData?.request?.type ?? undefined;\n const { url } = request;\n const byteRange = byteRangeFromRangeHeader(\n request.headers?.Range ?? request.headers?.range,\n );\n\n // Every MPD dash.js fetches — first load and each refresh — reaches the\n // core before dash.js parses the same bytes.\n if (type === REQUEST_TYPE.MPD) {\n return this.passThroughAndObserve(binding, request, response, (data) => {\n if (typeof data !== \"string\" && !isBinary(data)) return;\n // Take `PatchLocation` out before dash.js reads the same bytes: a\n // player following it refreshes by patch, which the core cannot read,\n // and its registry would freeze at this window. The wrap runs ahead\n // of dash.js's own handler, so what it parses is what is left here.\n // See specs/player-adapters.md.\n const manifest =\n typeof data === \"string\" ? stripPatchLocation(data) : data;\n if (manifest !== data) {\n response.data = manifest;\n this.logger(\"removed PatchLocation from %s\", url);\n }\n // The response URL, when the loader filled it in, follows redirects.\n const responseUrl = response.url;\n const processed = core.processManifest({\n url:\n responseUrl !== undefined && responseUrl !== \"\" ? responseUrl : url,\n requestedUrl: url,\n data: manifest,\n });\n if (processed) binding.onManifestProcessed?.(processed);\n });\n }\n\n if (type !== undefined && SEGMENT_TYPES.has(type)) {\n // A SegmentBase stream's index: dash.js loads it, the core reads the\n // segment list from the same bytes. Recognition, not lookup.\n if (core.isSegmentIndex(url, byteRange)) {\n return this.passThroughAndObserve(\n binding,\n request,\n response,\n (data) => {\n if (!isBinary(data)) return;\n // The window a `SegmentBase` presentation has is known only once\n // its index is read, so what the index says goes the same way a\n // manifest's does: it is the first thing that can place a live\n // player of one.\n const processed = core.processSegmentIndex({\n url,\n byteRange,\n data,\n });\n if (processed) binding.onManifestProcessed?.(processed);\n },\n );\n }\n\n // dash.js's `SegmentBaseLoader`, given no index range, finds the index\n // by probing the file with media-typed range requests. A probe has no\n // start time, where every media segment has one: not a segment the\n // registry could know, so it is passed through without the lookup —\n // and without the registry miss the lookup would report.\n if (\n type === REQUEST_TYPE.MEDIA_SEGMENT &&\n !Number.isFinite(request.customData?.request?.startTime ?? NaN)\n ) {\n return this.parent.load(request, response);\n }\n\n // Whitelist by lookup: a segment the registry knows on a stream with\n // P2P enabled is served by the core; initialization segments and\n // anything the registry does not know load through dash.js itself.\n if (\n type === REQUEST_TYPE.MEDIA_SEGMENT &&\n core.isSegmentLoadable(url, byteRange)\n ) {\n binding.reportPlayback?.();\n this.serve(core, request, response, byteRange);\n return true;\n }\n }\n\n // Licences, certificates, steering, XLink, init segments: untouched.\n return this.parent.load(request, response);\n }\n\n /**\n * dash.js names the request it abandons; its own `XHRLoader` ignores the\n * name and aborts the XHR it made last, which for a request the core is\n * serving is some other request's. So the named request is aborted where it\n * lives: at the core if it is the one being served, at dash.js's loader if\n * not. Named nothing — an older dash.js, whose `abort()` takes no request —\n * both are aborted.\n */\n abort(request?: CommonMediaRequestLike) {\n if (request === undefined) {\n this.current?.abort();\n this.parent.abort();\n return;\n }\n if (this.current?.request === request) {\n this.current.abort();\n return;\n }\n this.parent.abort(request);\n }\n\n private passThroughAndObserve(\n binding: LoaderBinding,\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n observe: (data: unknown) => void,\n ): boolean {\n request.customData ??= {};\n const { customData } = request;\n const original = customData.onloadend;\n // dash.js's XHRLoader copies `onloadend` onto the XHR at `load`, so the\n // wrap has to be in place before the parent runs.\n customData.onloadend = () => {\n try {\n // The same binding, not merely some binding: what this observes was\n // made against that engine's core, and a response landing after that\n // engine let the player go would otherwise rebuild the core it\n // released — even where another engine has since taken the player on.\n if (\n this.binding() === binding &&\n response.status >= 200 &&\n response.status <= 299\n ) {\n observe(response.data);\n }\n } catch (error) {\n this.logger(\"failed to process %s: %O\", request.url, error);\n }\n original?.();\n };\n return this.parent.load(request, response);\n }\n\n private serve(\n core: Core,\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n byteRange: ReturnType<typeof byteRangeFromRangeHeader>,\n ) {\n const { url } = request;\n request.customData ??= {};\n const { customData } = request;\n let settled = false;\n let aborted = false;\n\n const abort = () => {\n if (settled) return;\n aborted = true;\n core.abortSegmentLoading(url, byteRange);\n };\n customData.abort = abort;\n const current = { request, abort };\n this.current = current;\n // Once the request has settled there is nothing left to abort — and this\n // closure holds the scope the response lives in, so a `RequestRouter`\n // that kept it would keep the last segment's bytes for the life of the\n // player, one segment per media type. dash.js builds one XHRLoader per\n // media type and keeps it.\n const settle = () => {\n settled = true;\n if (this.current === current) this.current = undefined;\n };\n\n // The two outcomes are handled by separate arguments to `then`, not by a\n // `catch` chained after it: delivering a segment runs dash.js's own\n // progress and loadend listeners synchronously, and its event bus catches\n // nothing, so a listener that throws would otherwise land in the failure\n // handler and be reported as the core failing to load a segment dash.js\n // has already consumed — which dash.js then fetches again itself.\n core\n .loadSegment(url, { byteRange })\n .then(\n ({ data, bandwidth }) => {\n // The core cannot always cancel in time — a request waiting for the\n // segment storage has no loader yet — so what dash.js has abandoned\n // is dropped here rather than reported as a download.\n settle();\n if (aborted) {\n customData.onabort?.();\n return;\n }\n response.url = url;\n response.status = 200;\n response.statusText = \"OK\";\n response.headers = {};\n response.data = data;\n\n // dash.js measures throughput from progress traces, dropping the\n // first (it carries the latency) and summing the rest. Two events\n // give it one download trace whose duration is the core's bandwidth\n // hint — wall-clock time says nothing about the network for a segment\n // that came from a peer or from storage. Never 0 ms.\n const total = data.byteLength;\n // Delivered in a `try`, ended in a `finally`. `onprogress` runs\n // dash.js's LOADING_PROGRESS listeners synchronously — its event bus\n // catches nothing, and its own ABR abandonment handler is one of\n // them — so a listener that throws would otherwise skip `onloadend`,\n // and `onloadend` is what takes this request off dash.js's list: a\n // request never ended has no watchdog, the fragment promise never\n // settles, and that media type's buffer never advances again. The\n // segment stands as delivered; the throw is theirs, and is logged\n // by the handler below.\n try {\n customData.onprogress?.({\n lengthComputable: true,\n loaded: 0,\n total,\n time: 1,\n });\n customData.onprogress?.({\n lengthComputable: true,\n loaded: total,\n total,\n time: downloadTimeMs(bandwidth, total),\n });\n } finally {\n customData.onloadend?.();\n }\n },\n (error: unknown) => {\n settle();\n // What dash.js abandoned is reported as the abort it asked for: it\n // drops `onloadend` when it aborts and keeps `onabort`, so a failure\n // reported here instead would tell it nothing and leave the segment\n // waiting for the next schedule tick to be asked for again.\n //\n // An abort dash.js did not ask for is not one — the core gives up on\n // a request superseded by the next one, or when the engine lets the\n // player go — and is reported below as the failure it is, so dash.js\n // fetches the segment itself.\n if (aborted) {\n customData.onabort?.();\n return;\n }\n // A non-2xx status is what dash.js's HTTPLoader retries on; the\n // failure is reported as one rather than thrown into dash.js.\n response.url = url;\n response.status = 0;\n response.statusText =\n error instanceof Error ? error.message : String(error);\n response.data = undefined;\n this.logger(\"core failed to load %s: %O\", url, error);\n customData.onloadend?.();\n },\n )\n // Reached only by a throw out of one of the handlers above: a dash.js\n // or integrator listener failing inside the terminal callback it was\n // given — `onloadend` or `onabort`, on delivery or on failure alike.\n // That callback was called exactly once and is not called again; what\n // dash.js does inside it once a listener of its own has thrown is\n // dash.js's to survive, and cannot be repaired from outside it. The\n // throw is logged rather than lost to an unhandled rejection.\n .catch((error: unknown) => {\n this.logger(\n \"dash.js threw while the result for %s was reported to it: %O\",\n url,\n error,\n );\n });\n }\n}\n\nfunction isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView {\n return data instanceof ArrayBuffer || ArrayBuffer.isView(data);\n}\n","import type { MediaPlayerClass, MediaPlayerEvents } from \"dashjs\";\nimport { dashManifestParser } from \"p2p-media-loader-core/dash\";\nimport {\n Core,\n CoreConfig,\n CoreEventMap,\n DefinedCoreConfig,\n DynamicCoreConfig,\n ProcessedManifest,\n debug,\n runAll,\n trackMediaElementPlayback,\n liveDelayFor,\n maxLiveLatencyFor,\n playerBufferFor,\n type LiveDelay,\n INITIAL_LIVE_DELAY,\n} from \"p2p-media-loader-core\";\nimport { createXhrLoaderExtension, type LoaderBinding } from \"./loader.js\";\nimport { diagnostics } from \"./diagnostics.js\";\n\n/** A type for specifying dynamic configuration options that can be changed at runtime for the P2P engine's core. */\nexport type DynamicDashJsP2PEngineConfig = {\n /** Dynamic core config */\n core?: DynamicCoreConfig;\n};\n\n/** Represents the complete configuration for the `DashJsP2PEngine`. */\nexport type DashJsP2PEngineConfig = {\n /** Complete core configuration settings. */\n core: DefinedCoreConfig;\n};\n\n/** Allows for partial configuration settings for the `DashJsP2PEngine`. */\nexport type PartialDashJsP2PEngineConfig = {\n /** Partial core config */\n core?: Partial<CoreConfig>;\n};\n\n/** The three dash.js settings that bound how far ahead of the playhead it fetches. */\nconst FORWARD_BUFFER_KEYS = [\n \"bufferTimeDefault\",\n \"bufferTimeAtTopQuality\",\n \"bufferTimeAtTopQualityLongForm\",\n] as const;\n\ntype ForwardBuffer = Record<(typeof FORWARD_BUFFER_KEYS)[number], number>;\n/** What the player holds under those keys: a length, or a value that is not one. */\ntype HeldBuffer = Partial<Record<keyof ForwardBuffer, number | null>>;\n\ntype Placement = {\n /** False where the integrator placed the player in the live window. */\n readonly managed: boolean;\n /**\n * What the player held before this engine wrote any of it, and what it is\n * given back — every value under the buffer keys, a length or not, so that\n * a key the integrator held as `null` is not left holding a ceiling. The\n * buffer part is a ledger, kept by `noteOutsideBufferWrites`: it follows\n * later writes from outside — the integrator's, and dash.js's own when a\n * quota error makes it shrink the buffer it can afford — keeping the latest\n * of them rather than the lowest, so the last word on a setting is the one\n * honoured and the one restored. A later write to the delay is the\n * integrator placing the player themselves, and hands the whole placement\n * back.\n */\n readonly held: {\n readonly liveDelay?: number;\n readonly useSuggestedPresentationDelay?: boolean;\n readonly buffer: HeldBuffer;\n };\n};\n\n/**\n * The engine driving a player's requests, by player. dash.js keeps an\n * `XHRLoader` extension for the life of the player and ignores every later\n * `extend` for the same name, so the extension the first engine installs must\n * serve whichever engine is bound now — a second engine would otherwise\n * install nothing and quietly do nothing.\n */\nconst bindings = new WeakMap<MediaPlayerClass, LoaderBinding>();\n\nconst STREAM_INITIALIZED: MediaPlayerEvents[\"STREAM_INITIALIZED\"] =\n \"streamInitialized\";\nconst STREAM_TEARDOWN_COMPLETE: MediaPlayerEvents[\"STREAM_TEARDOWN_COMPLETE\"] =\n \"streamTeardownComplete\";\nconst PLAYBACK_PLAYING: MediaPlayerEvents[\"PLAYBACK_PLAYING\"] =\n \"playbackPlaying\";\n\n/**\n * Represents a Peer-to-Peer (P2P) engine designed to enhance media streaming efficiency.\n * This class integrates P2P technologies into dash.js, enabling the distribution of media segments via a peer network\n * alongside traditional HTTP fetching. This reduces server bandwidth costs and improves scalability by sharing the load\n * across multiple clients.\n *\n * The engine has three responsibilities (see specs/player-adapters.md): it\n * hands every MPD dash.js fetches to the core, routes segment requests\n * through the core, and reports playback state from the media element. dash.js's\n * own manifest parsing runs untouched; the core parses the same bytes itself.\n *\n * @example\n * import { MediaPlayer } from \"dashjs\";\n * import { DashJsP2PEngine } from \"p2p-media-loader-dashjs\";\n *\n * const player = MediaPlayer().create();\n * const engine = new DashJsP2PEngine({\n * core: {\n * swarmId: \"example-swarm-id\",\n * announceTrackers: [\"wss://personal.tracker.com\"],\n * },\n * });\n * engine.bindPlayer(player); // before initialize()\n * player.initialize(videoElement, streamUrl, true);\n */\nexport class DashJsP2PEngine {\n private player?: MediaPlayerClass;\n private readonly playback = trackMediaElementPlayback((state) =>\n this.core.updatePlayback(state),\n );\n private readonly core: Core;\n /**\n * What this engine found and what it decided when it took the current\n * source over, or undefined before the first live manifest of one. Read\n * then rather than at bind: `bindPlayer` runs before `initialize`, and the\n * settings an integrator passes in between are theirs to keep.\n */\n private placement?: Placement;\n /** The live delay this engine wrote, if any; see `applyLivePlacement`. */\n private appliedLiveDelay?: number;\n /** The forward buffer this engine wrote, if any; see `forwardBufferSettings`. */\n private appliedBuffer?: ForwardBuffer;\n /**\n * The placement the current source is held to, while this engine places\n * it; see `resyncIfBehind`.\n */\n private liveTarget?: LiveDelay;\n private readonly debug = debug(\"p2pml-dashjs:engine\");\n /** This engine's handlers on the bound player; see specs/diagnostics.md. */\n private listenersToken?: string;\n\n /**\n * Constructs an instance of `DashJsP2PEngine`.\n *\n * @param config An optional configuration for customizing the P2P engine's behavior.\n */\n constructor(config?: PartialDashJsP2PEngineConfig) {\n this.core = new Core({\n ...config?.core,\n // dash.js plays DASH only, so its bundle carries the DASH parser only.\n manifestParsers: config?.core?.manifestParsers ?? [dashManifestParser],\n });\n }\n\n /**\n * Hooks the engine into a dash.js player. Call before `player.initialize()`:\n * the engine replaces the player's `XHRLoader` through `player.extend`,\n * which dash.js resolves when it first loads.\n *\n * @param player The dash.js `MediaPlayer` instance.\n */\n bindPlayer(player: MediaPlayerClass) {\n if (this.player === player) return;\n // Whatever letting go of the last player, or taking this one off the\n // engine that had it, makes of itself: this player is bound either way.\n // A failure there raised from the middle of a bind would leave this\n // engine holding the player with none of its handlers on it, and a second\n // bind to the same player returns at the top — so it would stay that way,\n // while the engine that was released keeps every request routed to a core\n // it has already reset. What failed is raised once the bind is complete.\n const failures = runAll([\n () => {\n if (this.player) this.destroy();\n },\n ]);\n this.player = player;\n\n // The player's settings are read when the first live manifest of a source\n // arrives, not here: `bindPlayer` runs before `initialize`, so what the\n // integrator configures in between would otherwise be taken for dash.js's\n // own defaults and overwritten. (The placement state is empty here: the\n // release above cleared it, or there was never a player to fill it.)\n // An engine that had this player gives it back before this one reads it:\n // a delay left behind by another engine is indistinguishable from one the\n // integrator set, and would be read as a placement that is not ours.\n failures.push(...runAll([() => bindings.get(player)?.release?.()]));\n bindings.set(player, {\n core: this.core,\n onManifestProcessed: this.applyLivePlacement,\n release: this.releasePlayer,\n reportPlayback: () => this.playback.report(),\n });\n player.extend(\n \"XHRLoader\",\n createXhrLoaderExtension(() => bindings.get(player)),\n true,\n );\n\n player.on(STREAM_INITIALIZED, this.handleStreamInitialized);\n player.on(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n player.on(PLAYBACK_PLAYING, this.resyncIfBehind);\n this.listenersToken = diagnostics?.open(\"DashjsPlayerListeners\");\n this.registerMediaElement();\n if (failures.length) throw failures[0];\n }\n\n /**\n * Applies dynamic configuration updates to the P2P engine.\n *\n * @param dynamicConfig The configuration changes to apply.\n */\n applyDynamicConfig(dynamicConfig: DynamicDashJsP2PEngineConfig) {\n if (dynamicConfig.core) this.core.applyDynamicConfig(dynamicConfig.core);\n }\n\n /**\n * Retrieves the current configuration of the `DashJsP2PEngine`.\n *\n * @returns A copy of the configuration; changing it changes nothing in the\n * engine.\n */\n getConfig(): DashJsP2PEngineConfig {\n return { core: this.core.getConfig() };\n }\n\n /**\n * Adds an event listener for the specified event.\n * @param eventName The name of the event to listen for.\n * @param listener The callback function to be invoked when the event is triggered.\n *\n * @example\n * // Assuming `engine` is an instance of DashJsP2PEngine\n *\n * engine.addEventListener('onSegmentLoaded', (details) => {\n * console.log('Segment Loaded:', details);\n * });\n */\n addEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.addEventListener(eventName, listener);\n }\n\n /**\n * Removes an event listener for the specified event.\n * @param eventName The name of the event.\n * @param listener The callback function that was previously added.\n */\n removeEventListener<K extends keyof CoreEventMap>(\n eventName: K,\n listener: CoreEventMap[K],\n ) {\n this.core.removeEventListener(eventName, listener);\n }\n\n /**\n * Places the player in the live window from the window the core just\n * parsed: how far behind the edge it plays, and how far ahead of the\n * playhead it may fetch. The MPD reaches the core before dash.js parses the\n * same bytes, so both are in place when dash.js computes its live position.\n * Re-applied when the window moves by at least half a segment, or when\n * anything else it writes would change.\n */\n private applyLivePlacement = (manifest: ProcessedManifest) => {\n if (!this.player) return;\n const target = liveDelayFor(manifest);\n if (!target) {\n if (manifest.streams.some((stream) => stream.isLive)) {\n // Live, but not yet measurable — a `SegmentBase` stream has no\n // segments until its index is fetched. Hold the player off the edge\n // until a refresh can size the window.\n this.holdOffTheEdge();\n } else {\n // A presentation with nothing live in it is not this engine's to\n // place — and is the one that would otherwise inherit a live window's\n // ceiling, since the settings are the player's and outlive the source.\n this.restorePlacement();\n }\n return;\n }\n\n if (!this.takeOver()) return;\n const { streaming } = this.player.getSettings();\n\n // A delay the player holds that this engine did not write is the\n // integrator placing the player themselves, after the fact: the\n // placement is theirs from here. What this engine wrote to the buffer\n // is given back; the delay is left as they set it, and the next manifest\n // reads it as theirs.\n const delayNow = streaming?.delay?.liveDelay;\n if (\n this.appliedLiveDelay !== undefined &&\n isConfigured(delayNow) &&\n delayNow !== this.appliedLiveDelay\n ) {\n this.debug(\"liveDelay was set from outside; the placement is theirs\");\n this.restorePlacement();\n return;\n }\n\n this.liveTarget = target;\n this.noteOutsideBufferWrites();\n const buffer = this.forwardBufferSettings(target);\n\n // The two halves are compared and written independently. The delay is\n // compared against what this engine placed, never against what the\n // player holds: its own pre-manifest delay would otherwise read as a\n // placement. A window that moved by less than half a segment is the same\n // window — segment durations are not exact multiples — and rewriting the\n // delay for it would move the target dash.js measures its catch-up\n // against for nothing; so a change to the buffer alone writes the buffer\n // alone. `useSuggestedPresentationDelay` is this engine's too: turned back\n // on from outside, dash.js would park the player near the edge.\n //\n // The buffer is compared against what the player holds, because a ceiling\n // is only a ceiling while it is enforced: a setting raised from outside —\n // by the integrator, the only one who raises these — must be brought back\n // down, and comparing against what this engine last intended would leave\n // it raised for as long as the window holds steady.\n const delayMoved =\n this.appliedLiveDelay === undefined ||\n Math.abs(this.appliedLiveDelay - target.delay) >= target.segment / 2 ||\n streaming?.delay?.useSuggestedPresentationDelay !== false;\n const held = streaming?.buffer;\n const bufferChanged = FORWARD_BUFFER_KEYS.some(\n (key) => held?.[key] !== buffer[key],\n );\n if (!delayMoved && !bufferChanged) {\n // Nothing to write, but this is what the player holds and this engine\n // asked for, so it is this engine's — recording it keeps a later change\n // from outside recognisable as one.\n this.appliedBuffer = buffer;\n return;\n }\n\n const update: {\n delay?: { liveDelay: number; useSuggestedPresentationDelay: boolean };\n buffer?: ForwardBuffer;\n } = {};\n if (delayMoved) {\n this.debug(`Setting liveDelay to ${target.delay}`);\n update.delay = {\n liveDelay: target.delay,\n // A server's suggestion places the player near the edge, where\n // there is nothing to share.\n useSuggestedPresentationDelay: false,\n };\n }\n if (bufferChanged) {\n this.debug(`Setting forward buffer to ${buffer.bufferTimeDefault}`);\n update.buffer = buffer;\n }\n this.player.updateSettings({ streaming: update });\n if (delayMoved) this.appliedLiveDelay = target.delay;\n this.appliedBuffer = buffer;\n };\n\n /**\n * Keeps the ledger of what the player holds under the buffer keys that this\n * engine did not write: somebody else's latest word on the setting — the\n * integrator's, or dash.js's own when a quota error makes it shrink the two\n * top-quality buffers it can no longer afford — which the next write would\n * hide. Reading back what the engine wrote as theirs instead would let the\n * ceiling only ever fall, and treating it as nobody's would raise a setting\n * held below the ceiling, which is the one thing a ceiling must not do.\n */\n private noteOutsideBufferWrites() {\n const current = this.player?.getSettings().streaming?.buffer;\n const ceilings = this.placement?.held.buffer;\n if (!ceilings) return;\n for (const key of FORWARD_BUFFER_KEYS) {\n const value = current?.[key];\n if (isBufferTime(value) && value !== this.appliedBuffer?.[key]) {\n ceilings[key] = value;\n }\n }\n }\n\n /**\n * How far ahead of the playhead dash.js may fetch: a segment short of the\n * live delay, never less than a couple of segments — the rule every adapter\n * shares. The core sets its urgency threshold at half of that buffer, and\n * the other half is the time peers have to fill the player's requests; the\n * segment between the buffer and the edge is the one the registry may not\n * know yet.\n *\n * Left alone, dash.js buffers `bufferTimeAtTopQualityLongForm` — a minute,\n * since a dynamic stream is long-form by its duration — which on a live\n * stream is the whole window. Its playhead then sits a live delay behind the\n * edge while its *fetch* position rides the edge itself. It asks for each\n * segment the moment it exists, before any peer can have it, so the stream\n * plays perfectly with no P2P at all. The core knows every segment dash.js\n * can ask for — it reads each MPD before dash.js does, and lists a segment\n * numbered from the clock as it becomes available — so what the edge costs\n * is time for a peer to supply the segment, not a registry miss.\n *\n * Settings the integrator already holds below this are left alone; the value\n * is a ceiling, not a target.\n */\n private forwardBufferSettings(target: LiveDelay) {\n const bufferTime = playerBufferFor(target);\n\n const ceilings: HeldBuffer = this.placement?.held.buffer ?? {};\n const settings = {} as ForwardBuffer;\n for (const key of FORWARD_BUFFER_KEYS) {\n const held = ceilings[key];\n settings[key] =\n isBufferTime(held) && held < bufferTime ? held : bufferTime;\n }\n return settings;\n }\n\n /**\n * Brings the player back to its live delay once a pause or a stall has\n * left it more than `maxLiveLatencyFor` behind the edge. dash.js has no\n * such threshold of its own. It plays on from wherever a pause left it, and\n * its buffer, which ends a fixed distance ahead of the playhead, reaches\n * back past the window the registry lists: every request from there is\n * fetched over HTTP and shared with nobody. Once the next segment is out of\n * the window it stops fetching, plays out the buffer and stalls, and only\n * then moves the playhead — to the tail of the window, from where the next\n * pause carries it out again.\n *\n * Checked when playback starts or resumes, which is when a pause or a stall\n * ends. A DVR window wider than the threshold raises the threshold to the\n * window: a viewer who rewound into it is left where they chose to be, and\n * brought back only once a pause has carried them out of it.\n *\n * dash.js calls its event handlers with no `try` of its own, so what fails\n * here is logged rather than raised.\n */\n private resyncIfBehind = () => {\n const { player, liveTarget } = this;\n if (!player || !liveTarget) return;\n try {\n if (player.isSeeking()) return;\n const limit = Math.max(\n maxLiveLatencyFor(liveTarget),\n player.getDvrWindow().size,\n );\n const latency = player.getCurrentLiveLatency();\n if (!(latency > limit)) return;\n this.debug(`${latency} s behind the edge, past ${limit} s: re-syncing`);\n player.seekToOriginalLive();\n } catch (error) {\n this.debug(\"re-syncing to the live delay failed: %O\", error);\n }\n };\n\n private handleStreamInitialized = () => {\n this.registerMediaElement();\n };\n\n /**\n * The player has finished tearing a stream down. dash.js calls this from\n * its own event bus, which invokes handlers with no `try` of its own: a\n * throw here aborts `StreamController`'s reset half way — leaving its\n * streams, media-error and autoplay state stale, and the controllers after\n * it never reset — and surfaces out of the integrator's `attachSource`.\n * So each step runs on its own and what failed is logged, not raised.\n *\n * The core goes last, because it is the step that can fail: it destroys an\n * integrator's own segment storage, which is free to throw.\n */\n private handleStreamTeardown = () => {\n const failures = runAll([\n () => this.playback.stop(),\n // The next source starts from the player's own settings, and is placed\n // on its own window rather than measured against this one's.\n () => this.restorePlacement(),\n () => this.core.destroy(),\n ]);\n for (const failure of failures) {\n this.debug(\"tearing the stream down failed: %O\", failure);\n }\n };\n\n /**\n * Takes the current source over, once, on its first live manifest: reads\n * what the player holds — which is the integrator's, since nothing of this\n * engine's has been written for this source — and decides from it whether\n * the placement is theirs or ours.\n *\n * dash.js places the player from `liveDelay` when it has one and from\n * `liveDelayFragmentCount` otherwise, so either one is an integrator who\n * placed it themselves. `useSuggestedPresentationDelay` is not: it is on by\n * default, so it says nothing about what they chose.\n *\n * @returns whether this engine places this source.\n */\n private takeOver(): boolean {\n if (this.placement) return this.placement.managed;\n const { player } = this;\n if (!player) return false;\n\n const delay = player.getSettings().streaming?.delay;\n this.placement = {\n managed:\n !isConfigured(delay?.liveDelay) &&\n !isConfigured(delay?.liveDelayFragmentCount),\n held: {\n liveDelay: delay?.liveDelay,\n useSuggestedPresentationDelay: delay?.useSuggestedPresentationDelay,\n buffer: readForwardBuffer(player),\n },\n };\n return this.placement.managed;\n }\n\n /**\n * Where a live player sits until a manifest says how wide its window is.\n * Written for each source that needs it rather than once for the player: a\n * source whose window cannot be sized yet would otherwise be left wherever\n * dash.js puts it, which is at the edge, where there is nothing to share.\n */\n private holdOffTheEdge() {\n if (!this.takeOver() || !this.player) return;\n if (this.appliedLiveDelay !== undefined) return;\n\n this.debug(`Holding liveDelay at ${INITIAL_LIVE_DELAY}`);\n this.player.updateSettings({\n streaming: {\n delay: {\n liveDelay: INITIAL_LIVE_DELAY,\n // A server's suggestion places the player near the edge, where\n // there is nothing to share.\n useSuggestedPresentationDelay: false,\n },\n },\n });\n this.appliedLiveDelay = INITIAL_LIVE_DELAY;\n }\n\n /**\n * Puts back what the player held before this engine wrote anything: the\n * delay and the buffer alike, since they are the two halves of one\n * placement. dash.js keeps both across `attachSource`, so a live window's\n * ceiling would otherwise be inherited by whatever plays next — a VOD\n * source included — and a delay left behind would park the player where P2P\n * wanted it for as long as the player lives.\n *\n * The next source is taken over afresh, and placed on its own window rather\n * than measured against this one's.\n */\n private restorePlacement() {\n const { placement, appliedLiveDelay, appliedBuffer } = this;\n this.placement = undefined;\n this.appliedLiveDelay = undefined;\n this.appliedBuffer = undefined;\n this.liveTarget = undefined;\n if (!this.player || !placement) return;\n\n // Each half is given back only if this engine wrote it. A live window it\n // only held the player in never had its buffer touched, and writing one\n // back would revert whatever the integrator has set since.\n const streaming: {\n delay?: { liveDelay: number; useSuggestedPresentationDelay?: boolean };\n buffer?: HeldBuffer;\n } = {};\n const { held } = placement;\n\n // The delay only while it is still this engine's: written over from\n // outside since, it is the integrator's word, and stays.\n const delayNow = this.player.getSettings().streaming?.delay?.liveDelay;\n if (appliedLiveDelay !== undefined && delayNow === appliedLiveDelay) {\n streaming.delay = {\n // NaN is how dash.js says a delay was never configured.\n liveDelay: held.liveDelay ?? NaN,\n ...(held.useSuggestedPresentationDelay === undefined\n ? {}\n : {\n useSuggestedPresentationDelay: held.useSuggestedPresentationDelay,\n }),\n };\n }\n\n if (appliedBuffer) {\n // Every key that was held, whatever it held: a `null` given back is a\n // `null`, not a ceiling left behind.\n const buffer: HeldBuffer = {};\n for (const key of FORWARD_BUFFER_KEYS) {\n if (key in held.buffer) buffer[key] = held.buffer[key];\n }\n if (Object.keys(buffer).length > 0) streaming.buffer = buffer;\n }\n\n if (Object.keys(streaming).length === 0) return;\n this.debug(\"Restoring the placement the player came with\");\n this.player.updateSettings({\n streaming: streaming as Parameters<\n MediaPlayerClass[\"updateSettings\"]\n >[0][\"streaming\"],\n });\n }\n\n private registerMediaElement() {\n let media: HTMLMediaElement | undefined;\n try {\n // Throws until a view is attached.\n media = this.player?.getVideoElement();\n } catch {\n return;\n }\n if (media) this.playback.watch(media);\n }\n\n /**\n * Cleans up and releases all resources, and unregisters all event handlers.\n * The bound player is let go and given back the settings the engine wrote.\n *\n * Every step runs even when one before it throws, and the first failure is\n * rethrown once all have run. Listeners added with `addEventListener` are\n * not removed: they are on the core, which is emptied, not discarded.\n */\n destroy() {\n // Only if it is still ours: another engine may have taken this player on\n // since, and it has already been given back to it.\n if (this.player && bindings.get(this.player)?.core === this.core) {\n bindings.delete(this.player);\n }\n this.releasePlayer();\n }\n\n /**\n * Lets the player go: stops working for it, gives back what was written to\n * it, and forgets it. Called on `destroy`, and by the next engine to bind\n * the same player.\n *\n * An engine with no player has nothing to load for, so its core is reset\n * and its playback tracker detached. Leaving them running would keep a\n * second core fetching and announcing in the swarm the engine that took the\n * player over is in, driven by the same media element.\n *\n * Every step runs whatever the ones before it made of themselves: the core\n * destroys an integrator's own segment storage and is free to throw, and\n * stopping there would leave the media element reporting playback into a\n * destroyed core, this engine's handlers on the player, and the player\n * carrying the live delay and buffer ceilings this engine wrote. What\n * failed is raised once there is nothing left to let go of — to whoever\n * asked, which on the takeover path is the engine binding this player next,\n * and which is why that one collects it rather than letting it abort a bind\n * already under way.\n */\n private releasePlayer = () => {\n const failures = runAll([\n () => this.playback.stop(),\n () => {\n if (!this.player) return;\n this.player.off(STREAM_INITIALIZED, this.handleStreamInitialized);\n this.player.off(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n this.player.off(PLAYBACK_PLAYING, this.resyncIfBehind);\n diagnostics?.close(this.listenersToken, \"released\");\n this.listenersToken = undefined;\n },\n () => this.restorePlacement(),\n () => this.core.destroy(),\n ]);\n this.player = undefined;\n if (failures.length) throw failures[0];\n };\n}\n\n/** The forward buffer settings a player currently holds. */\nfunction readForwardBuffer(player: MediaPlayerClass): HeldBuffer {\n const buffer = player.getSettings().streaming?.buffer;\n const held: HeldBuffer = {};\n for (const key of FORWARD_BUFFER_KEYS) {\n const value = buffer?.[key];\n if (value !== undefined) held[key] = value;\n }\n return held;\n}\n\n/**\n * Whether a buffer setting the player holds is a length this engine can reason\n * about. dash.js validates nothing an integrator passes to `updateSettings`\n * and its own typings promise a number, so a `null` left by someone clearing\n * a setting would otherwise be read as a length, compared as zero, and handed\n * back to the player as its ceiling.\n */\nfunction isBufferTime(value: unknown): value is number {\n return typeof value === \"number\" && !Number.isNaN(value);\n}\n\n/** Whether a dash.js setting holds a value rather than its unset default. */\nfunction isConfigured(value: number | null | undefined): boolean {\n return value !== undefined && value !== null && !Number.isNaN(value);\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAa,eAAe;CAC1B,KAAK;CACL,cAAc;CACd,eAAe;CACf,eAAe;AACjB;;AC4BA,IAAM,gCAAqC,IAAI,IAAI;CACjD,aAAa;CACb,aAAa;CACb,aAAa;AACf,CAAC;;;;;;;;;;;AAYD,SAAgB,yBACd,SACA;CACA,OAAO,SAAS,qBAA0D;EAIxE,MAAM,EAAE,WAAW;EAKnB,MAAM,SAAS,IAAI,cAAc,SAAS;GAHxC,MAAM,OAAO,KAAK,KAAK,MAAM;GAC7B,OAAO,OAAO,MAAM,KAAK,MAAM;EAES,CAAQ;EAClD,OAAO;GACL,OAAO,SAAS,aAAa,OAAO,KAAK,SAAS,QAAQ;GAC1D,QAAQ,YAAY,OAAO,MAAM,OAAO;EAC1C;CACF;AACF;;;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ation as t } from "p2p-media-loader-core/dash";
2
2
  import { Core as n, Core as r, INITIAL_LIVE_DELAY as i, byteRangeFromRangeHeader as a, debug as o, downloadTimeMs as s, liveDelayFor as c, maxLiveLatencyFor as l, playerBufferFor as u, runAll as d, trackMediaElementPlayback as f } from "p2p-media-loader-core";
3
- //#region src/types.ts
3
+ // src/types.ts
4
4
  var p = {
5
5
  MPD: "MPD",
6
6
  INIT_SEGMENT: "InitializationSegment",
@@ -123,8 +123,7 @@ var g = class {
123
123
  function _(e) {
124
124
  return e instanceof ArrayBuffer || ArrayBuffer.isView(e);
125
125
  }
126
- //#endregion
127
- //#region src/engine.ts
126
+ // src/engine.ts
128
127
  var v = [
129
128
  "bufferTimeDefault",
130
129
  "bufferTimeAtTopQuality",
@@ -303,7 +302,6 @@ function T(e) {
303
302
  function E(e) {
304
303
  return e != null && !Number.isNaN(e);
305
304
  }
306
- //#endregion
307
305
  export { n as Core, C as DashJsP2PEngine };
308
306
 
309
307
  //# sourceMappingURL=p2p-media-loader-dashjs.es.min.js.map