p2p-media-loader-dashjs 5.0.0-alpha.1

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.
@@ -0,0 +1,377 @@
1
+ import { dashManifestParser } from "p2p-media-loader-core/dash";
2
+ import { Core, Core as Core$1, CoreRequestError, byteRangeFromRangeHeader, debug, getPlaybackStateFromMediaElement, liveDelayFor } from "p2p-media-loader-core";
3
+ //#region src/types.ts
4
+ /**
5
+ * The slice of dash.js's request plumbing the adapter touches, typed
6
+ * structurally. dash.js's own declarations for these live in
7
+ * `@svta/cml-request`, a transitive dependency this package cannot import
8
+ * directly, and the adapter needs only a handful of fields.
9
+ */
10
+ /** `HTTPRequest.*_TYPE` values a request carries in `customData.request.type`. */
11
+ var REQUEST_TYPE = {
12
+ MPD: "MPD",
13
+ INIT_SEGMENT: "InitializationSegment",
14
+ MEDIA_SEGMENT: "MediaSegment",
15
+ INDEX_SEGMENT: "IndexSegment"
16
+ };
17
+ //#endregion
18
+ //#region src/loader.ts
19
+ var SEGMENT_TYPES = /* @__PURE__ */ new Set([
20
+ REQUEST_TYPE.INIT_SEGMENT,
21
+ REQUEST_TYPE.MEDIA_SEGMENT,
22
+ REQUEST_TYPE.INDEX_SEGMENT
23
+ ]);
24
+ /**
25
+ * The `XHRLoader` replacement, in the shape dash.js's `FactoryMaker` applies
26
+ * it: a plain function it calls with `this.parent` set to the real loader,
27
+ * whose `load` and `abort` the returned object overrides. Registered per
28
+ * player through `player.extend("XHRLoader", extension, true)`.
29
+ *
30
+ * Every request dash.js makes over HTTP passes through here — MPD, init,
31
+ * media and index segments, licences — and is told apart by the type of the
32
+ * `FragmentRequest` behind it. See specs/player-adapters.md, "dash.js".
33
+ */
34
+ function createXhrLoaderExtension(core, hooks = {}) {
35
+ return function xhrLoaderExtension() {
36
+ const { parent } = this;
37
+ const router = new RequestRouter(core, {
38
+ load: parent.load.bind(parent),
39
+ abort: parent.abort.bind(parent)
40
+ }, hooks);
41
+ return {
42
+ load: (request, response) => router.load(request, response),
43
+ abort: () => router.abort()
44
+ };
45
+ };
46
+ }
47
+ var RequestRouter = class {
48
+ core;
49
+ parent;
50
+ hooks;
51
+ logger = debug("p2pml-dashjs:loader");
52
+ /** Aborts the request served by the core most recently, if still in flight. */
53
+ abortCurrent;
54
+ constructor(core, parent, hooks) {
55
+ this.core = core;
56
+ this.parent = parent;
57
+ this.hooks = hooks;
58
+ }
59
+ load(request, response) {
60
+ const type = request.customData?.request?.type ?? void 0;
61
+ const { url } = request;
62
+ const byteRange = byteRangeFromRangeHeader(request.headers?.Range ?? request.headers?.range);
63
+ if (type === REQUEST_TYPE.MPD) return this.passThroughAndObserve(request, response, (data) => {
64
+ if (typeof data !== "string" && !isBinary(data)) return;
65
+ const responseUrl = response.url;
66
+ const processed = this.core.processManifest({
67
+ url: responseUrl !== void 0 && responseUrl !== "" ? responseUrl : url,
68
+ data
69
+ });
70
+ if (processed) this.hooks.onManifestProcessed?.(processed);
71
+ });
72
+ if (type !== void 0 && SEGMENT_TYPES.has(type)) {
73
+ if (this.core.isSegmentIndex(url, byteRange)) return this.passThroughAndObserve(request, response, (data) => {
74
+ if (!isBinary(data)) return;
75
+ this.core.processSegmentIndex({
76
+ url,
77
+ byteRange,
78
+ data
79
+ });
80
+ });
81
+ if (type === REQUEST_TYPE.MEDIA_SEGMENT && this.core.isSegmentLoadable(url, byteRange)) {
82
+ this.serve(request, response, byteRange);
83
+ return true;
84
+ }
85
+ }
86
+ return this.parent.load(request, response);
87
+ }
88
+ abort() {
89
+ this.abortCurrent?.();
90
+ this.parent.abort();
91
+ }
92
+ passThroughAndObserve(request, response, observe) {
93
+ request.customData ??= {};
94
+ const { customData } = request;
95
+ const original = customData.onloadend;
96
+ customData.onloadend = () => {
97
+ try {
98
+ if (response.status >= 200 && response.status <= 299) observe(response.data);
99
+ } catch (error) {
100
+ this.logger("failed to process %s: %O", request.url, error);
101
+ }
102
+ original?.();
103
+ };
104
+ return this.parent.load(request, response);
105
+ }
106
+ serve(request, response, byteRange) {
107
+ const { url } = request;
108
+ request.customData ??= {};
109
+ const { customData } = request;
110
+ let settled = false;
111
+ const abort = () => {
112
+ if (settled) return;
113
+ this.core.abortSegmentLoading(url, byteRange);
114
+ };
115
+ customData.abort = abort;
116
+ this.abortCurrent = abort;
117
+ this.core.loadSegment(url, { byteRange }).then(({ data, bandwidth }) => {
118
+ settled = true;
119
+ response.url = url;
120
+ response.status = 200;
121
+ response.statusText = "OK";
122
+ response.headers = {};
123
+ response.data = data;
124
+ const total = data.byteLength;
125
+ customData.onprogress?.({
126
+ lengthComputable: true,
127
+ loaded: 0,
128
+ total,
129
+ time: 1
130
+ });
131
+ customData.onprogress?.({
132
+ lengthComputable: true,
133
+ loaded: total,
134
+ total,
135
+ time: loadingTimeMs(bandwidth, total)
136
+ });
137
+ customData.onloadend?.();
138
+ }).catch((error) => {
139
+ settled = true;
140
+ if (error instanceof CoreRequestError && error.type === "aborted") {
141
+ customData.onabort?.();
142
+ return;
143
+ }
144
+ response.url = url;
145
+ response.status = 0;
146
+ response.statusText = error instanceof Error ? error.message : String(error);
147
+ response.data = void 0;
148
+ this.logger("core failed to load %s: %O", url, error);
149
+ customData.onloadend?.();
150
+ });
151
+ }
152
+ };
153
+ function isBinary(data) {
154
+ return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
155
+ }
156
+ /** Download time in ms for the core's bandwidth hint; see the Shaka adapter. */
157
+ function loadingTimeMs(bandwidth, bytes) {
158
+ if (bandwidth <= 0) return 1;
159
+ return Math.max(1, Math.round(bytes * 8 * 1e3 / bandwidth));
160
+ }
161
+ //#endregion
162
+ //#region src/engine.ts
163
+ /**
164
+ * Live delay until the first live manifest says how wide the window is; from
165
+ * then on the delay follows the window (see the core's liveDelayFor). Only
166
+ * applied when the integrator left dash.js's own default in place.
167
+ */
168
+ var INITIAL_LIVE_EDGE_DELAY = 25;
169
+ /** Least forward buffer to leave the player, whatever the windows work out to. */
170
+ var MIN_BUFFER_SEGMENTS = 2;
171
+ /** Segments left between the player's forward buffer and the live edge. */
172
+ var LIVE_EDGE_MARGIN_SEGMENTS = 1;
173
+ var STREAM_INITIALIZED = "streamInitialized";
174
+ var STREAM_TEARDOWN_COMPLETE = "streamTeardownComplete";
175
+ var PLAYBACK_EVENTS = [
176
+ "timeupdate",
177
+ "progress",
178
+ "seeking",
179
+ "seeked",
180
+ "ratechange",
181
+ "play",
182
+ "pause",
183
+ "waiting"
184
+ ];
185
+ /**
186
+ * Represents a Peer-to-Peer (P2P) engine designed to enhance media streaming efficiency.
187
+ * This class integrates P2P technologies into dash.js, enabling the distribution of media segments via a peer network
188
+ * alongside traditional HTTP fetching. This reduces server bandwidth costs and improves scalability by sharing the load
189
+ * across multiple clients.
190
+ *
191
+ * The engine has three responsibilities (see specs/player-adapters.md): it
192
+ * hands every MPD dash.js fetches to the core, routes segment requests
193
+ * through the core, and reports playback state from the media element. dash.js's
194
+ * own manifest parsing runs untouched; the core parses the same bytes itself.
195
+ *
196
+ * @example
197
+ * const player = dashjs.MediaPlayer().create();
198
+ * const engine = new DashJsP2PEngine({
199
+ * core: {
200
+ * swarmId: "example-swarm-id",
201
+ * announceTrackers: ["wss://personal.tracker.com"],
202
+ * },
203
+ * });
204
+ * engine.bindPlayer(player); // before initialize()
205
+ * player.initialize(videoElement, manifestUrl, true);
206
+ */
207
+ var DashJsP2PEngine = class {
208
+ player;
209
+ media;
210
+ core;
211
+ /** False when the integrator configured a live delay themselves. */
212
+ managesLiveDelay = false;
213
+ debug = debug("p2pml-dashjs:engine");
214
+ /**
215
+ * Constructs an instance of `DashJsP2PEngine`.
216
+ *
217
+ * @param config An optional configuration for customizing the P2P engine's behavior.
218
+ */
219
+ constructor(config) {
220
+ this.core = new Core$1({
221
+ ...config?.core,
222
+ manifestParsers: config?.core?.manifestParsers ?? [dashManifestParser]
223
+ });
224
+ }
225
+ /**
226
+ * Hooks the engine into a dash.js player. Call before `player.initialize()`:
227
+ * the engine replaces the player's `XHRLoader` through `player.extend`,
228
+ * which dash.js resolves when it first loads.
229
+ *
230
+ * @param player The dash.js `MediaPlayer` instance.
231
+ */
232
+ bindPlayer(player) {
233
+ if (this.player === player) return;
234
+ if (this.player) this.destroy();
235
+ this.player = player;
236
+ const liveDelay = player.getSettings().streaming?.delay?.liveDelay;
237
+ this.managesLiveDelay = liveDelay === void 0 || Number.isNaN(liveDelay);
238
+ if (this.managesLiveDelay) player.updateSettings({ streaming: { delay: {
239
+ liveDelay: INITIAL_LIVE_EDGE_DELAY,
240
+ useSuggestedPresentationDelay: false
241
+ } } });
242
+ player.extend("XHRLoader", createXhrLoaderExtension(this.core, { onManifestProcessed: this.applyLivePlacement }), true);
243
+ player.on(STREAM_INITIALIZED, this.handleStreamInitialized);
244
+ player.on(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);
245
+ this.registerMediaElement();
246
+ }
247
+ /**
248
+ * Applies dynamic configuration updates to the P2P engine.
249
+ *
250
+ * @param dynamicConfig The configuration changes to apply.
251
+ */
252
+ applyDynamicConfig(dynamicConfig) {
253
+ if (dynamicConfig.core) this.core.applyDynamicConfig(dynamicConfig.core);
254
+ }
255
+ /**
256
+ * Retrieves the current configuration of the `DashJsP2PEngine`.
257
+ *
258
+ * @returns The configuration as a readonly object.
259
+ */
260
+ getConfig() {
261
+ return { core: this.core.getConfig() };
262
+ }
263
+ /**
264
+ * Adds an event listener for the specified event.
265
+ * @param eventName The name of the event to listen for.
266
+ * @param listener The callback function to be invoked when the event is triggered.
267
+ *
268
+ * @example
269
+ * engine.addEventListener('onSegmentLoaded', (details) => {
270
+ * console.log('Segment Loaded:', details);
271
+ * });
272
+ */
273
+ addEventListener(eventName, listener) {
274
+ this.core.addEventListener(eventName, listener);
275
+ }
276
+ /**
277
+ * Removes an event listener for the specified event.
278
+ * @param eventName The name of the event.
279
+ * @param listener The callback function that was previously added.
280
+ */
281
+ removeEventListener(eventName, listener) {
282
+ this.core.removeEventListener(eventName, listener);
283
+ }
284
+ /**
285
+ * Places the player in the live window from the window the core just
286
+ * parsed: how far behind the edge it plays, and how far ahead of the
287
+ * playhead it may fetch. The MPD reaches the core before dash.js parses the
288
+ * same bytes, so both are in place when dash.js computes its live position.
289
+ * Re-applied only when the window changes by at least half a segment.
290
+ */
291
+ applyLivePlacement = (manifest) => {
292
+ if (!this.player || !this.managesLiveDelay) return;
293
+ const target = liveDelayFor(manifest);
294
+ if (!target) return;
295
+ const current = this.player.getSettings().streaming?.delay?.liveDelay;
296
+ if (current !== void 0 && !Number.isNaN(current) && Math.abs(current - target.delay) < target.segment / 2) return;
297
+ const buffer = this.forwardBufferSettings(target);
298
+ this.debug(`Setting liveDelay to ${target.delay}, forward buffer to ${buffer.bufferTimeDefault}`);
299
+ this.player.updateSettings({ streaming: {
300
+ delay: { liveDelay: target.delay },
301
+ buffer
302
+ } });
303
+ };
304
+ /**
305
+ * How far ahead of the playhead dash.js may fetch: the high-demand window,
306
+ * never closer to the live edge than a segment, never less than a couple of
307
+ * segments. The segments beyond it are the core's to prefetch, and they are
308
+ * the ones peers exchange.
309
+ *
310
+ * Left alone, dash.js buffers `bufferTimeAtTopQualityLongForm` — a minute,
311
+ * since a dynamic stream is long-form by its duration — which on a live
312
+ * stream is the whole window. Its playhead then sits a live delay behind the
313
+ * edge while its *fetch* position rides the edge itself, where the registry
314
+ * cannot yet know the segment: core learns of one only when dash.js refreshes
315
+ * the MPD, and dash.js derives availability from its own synced clock. Every
316
+ * such request misses the registry and falls through to dash.js's own loader,
317
+ * so the stream plays perfectly with no P2P at all.
318
+ *
319
+ * Settings the integrator already holds below this are left alone; the value
320
+ * is a ceiling, not a target.
321
+ */
322
+ forwardBufferSettings(target) {
323
+ const { mainStream, secondaryStream } = this.core.getConfig();
324
+ const highDemandTimeWindow = Math.max(mainStream.highDemandTimeWindow, secondaryStream.highDemandTimeWindow);
325
+ const bufferTime = Math.max(target.segment * MIN_BUFFER_SEGMENTS, Math.min(highDemandTimeWindow, target.delay - target.segment * LIVE_EDGE_MARGIN_SEGMENTS));
326
+ const current = this.player?.getSettings().streaming?.buffer;
327
+ const lower = (setting) => setting === void 0 || Number.isNaN(setting) || setting > bufferTime ? bufferTime : setting;
328
+ return {
329
+ bufferTimeDefault: lower(current?.bufferTimeDefault),
330
+ bufferTimeAtTopQuality: lower(current?.bufferTimeAtTopQuality),
331
+ bufferTimeAtTopQualityLongForm: lower(current?.bufferTimeAtTopQualityLongForm)
332
+ };
333
+ }
334
+ handleStreamInitialized = () => {
335
+ this.registerMediaElement();
336
+ };
337
+ handleStreamTeardown = () => {
338
+ this.core.destroy();
339
+ this.unregisterMediaElement();
340
+ };
341
+ registerMediaElement() {
342
+ let media;
343
+ try {
344
+ media = this.player?.getVideoElement();
345
+ } catch {
346
+ return;
347
+ }
348
+ if (!media || media === this.media) return;
349
+ this.unregisterMediaElement();
350
+ this.media = media;
351
+ for (const event of PLAYBACK_EVENTS) media.addEventListener(event, this.handlePlaybackUpdate);
352
+ }
353
+ unregisterMediaElement() {
354
+ const { media } = this;
355
+ if (!media) return;
356
+ for (const event of PLAYBACK_EVENTS) media.removeEventListener(event, this.handlePlaybackUpdate);
357
+ this.media = void 0;
358
+ }
359
+ handlePlaybackUpdate = (event) => {
360
+ const media = event.target;
361
+ this.core.updatePlayback(getPlaybackStateFromMediaElement(media));
362
+ };
363
+ /** Cleans up and releases all resources, and unregisters all event handlers. */
364
+ destroy() {
365
+ this.core.destroy();
366
+ this.unregisterMediaElement();
367
+ if (this.player) {
368
+ this.player.off(STREAM_INITIALIZED, this.handleStreamInitialized);
369
+ this.player.off(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);
370
+ }
371
+ this.player = void 0;
372
+ }
373
+ };
374
+ //#endregion
375
+ export { Core, DashJsP2PEngine };
376
+
377
+ //# sourceMappingURL=p2p-media-loader-dashjs.es.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"p2p-media-loader-dashjs.es.js","names":[],"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};\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 abort(): 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 CoreRequestError,\n ProcessedManifest,\n byteRangeFromRangeHeader,\n debug,\n} from \"p2p-media-loader-core\";\nimport {\n CommonMediaRequestLike,\n CommonMediaResponseLike,\n FactoryMakerThis,\n REQUEST_TYPE,\n XhrLoaderLike,\n} from \"./types.js\";\n\nexport type LoaderHooks = {\n /** Called with what the core read from each MPD, before dash.js parses it. */\n onManifestProcessed?: (manifest: ProcessedManifest) => 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(core: Core, hooks: LoaderHooks = {}) {\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(core, original, hooks);\n return {\n load: (request, response) => router.load(request, response),\n abort: () => router.abort(),\n };\n };\n}\n\nclass RequestRouter {\n private readonly logger = debug(\"p2pml-dashjs:loader\");\n /** Aborts the request served by the core most recently, if still in flight. */\n private abortCurrent?: () => void;\n\n constructor(\n private readonly core: Core,\n private readonly parent: XhrLoaderLike,\n private readonly hooks: LoaderHooks,\n ) {}\n\n load(\n request: CommonMediaRequestLike,\n response: CommonMediaResponseLike,\n ): boolean {\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(request, response, (data) => {\n if (typeof data !== \"string\" && !isBinary(data)) return;\n // The response URL, when the loader filled it in, follows redirects.\n const responseUrl = response.url;\n const processed = this.core.processManifest({\n url:\n responseUrl !== undefined && responseUrl !== \"\" ? responseUrl : url,\n data,\n });\n if (processed) this.hooks.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 (this.core.isSegmentIndex(url, byteRange)) {\n return this.passThroughAndObserve(request, response, (data) => {\n if (!isBinary(data)) return;\n this.core.processSegmentIndex({ url, byteRange, data });\n });\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 this.core.isSegmentLoadable(url, byteRange)\n ) {\n this.serve(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 abort() {\n this.abortCurrent?.();\n this.parent.abort();\n }\n\n private passThroughAndObserve(\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 if (response.status >= 200 && response.status <= 299) {\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 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\n const abort = () => {\n if (settled) return;\n this.core.abortSegmentLoading(url, byteRange);\n };\n customData.abort = abort;\n this.abortCurrent = abort;\n\n this.core\n .loadSegment(url, { byteRange })\n .then(({ data, bandwidth }) => {\n settled = true;\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 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: loadingTimeMs(bandwidth, total),\n });\n customData.onloadend?.();\n })\n .catch((error: unknown) => {\n settled = true;\n if (error instanceof CoreRequestError && error.type === \"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}\n\nfunction isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView {\n return data instanceof ArrayBuffer || ArrayBuffer.isView(data);\n}\n\n/** Download time in ms for the core's bandwidth hint; see the Shaka adapter. */\nfunction loadingTimeMs(bandwidth: number, bytes: number): number {\n if (bandwidth <= 0) return 1;\n return Math.max(1, Math.round((bytes * 8 * 1000) / bandwidth));\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 getPlaybackStateFromMediaElement,\n liveDelayFor,\n type LiveDelay,\n} from \"p2p-media-loader-core\";\nimport { createXhrLoaderExtension } from \"./loader.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/**\n * Live delay until the first live manifest says how wide the window is; from\n * then on the delay follows the window (see the core's liveDelayFor). Only\n * applied when the integrator left dash.js's own default in place.\n */\nconst INITIAL_LIVE_EDGE_DELAY = 25;\n\n/** Least forward buffer to leave the player, whatever the windows work out to. */\nconst MIN_BUFFER_SEGMENTS = 2;\n/** Segments left between the player's forward buffer and the live edge. */\nconst LIVE_EDGE_MARGIN_SEGMENTS = 1;\n\nconst STREAM_INITIALIZED: MediaPlayerEvents[\"STREAM_INITIALIZED\"] =\n \"streamInitialized\";\nconst STREAM_TEARDOWN_COMPLETE: MediaPlayerEvents[\"STREAM_TEARDOWN_COMPLETE\"] =\n \"streamTeardownComplete\";\n\n// Every event after which the buffer ahead of the playhead or the rate may\n// have changed. `progress` covers buffer growth without playhead movement.\nconst PLAYBACK_EVENTS = [\n \"timeupdate\",\n \"progress\",\n \"seeking\",\n \"seeked\",\n \"ratechange\",\n \"play\",\n \"pause\",\n \"waiting\",\n] as const;\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 * const player = dashjs.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, manifestUrl, true);\n */\nexport class DashJsP2PEngine {\n private player?: MediaPlayerClass;\n private media?: HTMLMediaElement;\n private readonly core: Core;\n /** False when the integrator configured a live delay themselves. */\n private managesLiveDelay = false;\n private readonly debug = debug(\"p2pml-dashjs:engine\");\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 if (this.player) this.destroy();\n this.player = player;\n\n const liveDelay = player.getSettings().streaming?.delay?.liveDelay;\n this.managesLiveDelay = liveDelay === undefined || Number.isNaN(liveDelay);\n if (this.managesLiveDelay) {\n player.updateSettings({\n streaming: {\n delay: {\n liveDelay: INITIAL_LIVE_EDGE_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 }\n\n player.extend(\n \"XHRLoader\",\n createXhrLoaderExtension(this.core, {\n onManifestProcessed: this.applyLivePlacement,\n }),\n true,\n );\n\n player.on(STREAM_INITIALIZED, this.handleStreamInitialized);\n player.on(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n this.registerMediaElement();\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 The configuration as a readonly object.\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 * 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 only when the window changes by at least half a segment.\n */\n private applyLivePlacement = (manifest: ProcessedManifest) => {\n if (!this.player || !this.managesLiveDelay) return;\n const target = liveDelayFor(manifest);\n if (!target) return;\n\n const current = this.player.getSettings().streaming?.delay?.liveDelay;\n if (\n current !== undefined &&\n !Number.isNaN(current) &&\n Math.abs(current - target.delay) < target.segment / 2\n ) {\n return;\n }\n\n const buffer = this.forwardBufferSettings(target);\n this.debug(\n `Setting liveDelay to ${target.delay}, forward buffer to ${buffer.bufferTimeDefault}`,\n );\n this.player.updateSettings({\n streaming: { delay: { liveDelay: target.delay }, buffer },\n });\n };\n\n /**\n * How far ahead of the playhead dash.js may fetch: the high-demand window,\n * never closer to the live edge than a segment, never less than a couple of\n * segments. The segments beyond it are the core's to prefetch, and they are\n * the ones peers exchange.\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, where the registry\n * cannot yet know the segment: core learns of one only when dash.js refreshes\n * the MPD, and dash.js derives availability from its own synced clock. Every\n * such request misses the registry and falls through to dash.js's own loader,\n * so the stream plays perfectly with no P2P at all.\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 { mainStream, secondaryStream } = this.core.getConfig();\n const highDemandTimeWindow = Math.max(\n mainStream.highDemandTimeWindow,\n secondaryStream.highDemandTimeWindow,\n );\n const bufferTime = Math.max(\n target.segment * MIN_BUFFER_SEGMENTS,\n Math.min(\n highDemandTimeWindow,\n target.delay - target.segment * LIVE_EDGE_MARGIN_SEGMENTS,\n ),\n );\n\n const current = this.player?.getSettings().streaming?.buffer;\n const lower = (setting: number | undefined) =>\n setting === undefined || Number.isNaN(setting) || setting > bufferTime\n ? bufferTime\n : setting;\n\n return {\n bufferTimeDefault: lower(current?.bufferTimeDefault),\n bufferTimeAtTopQuality: lower(current?.bufferTimeAtTopQuality),\n bufferTimeAtTopQualityLongForm: lower(\n current?.bufferTimeAtTopQualityLongForm,\n ),\n };\n }\n\n private handleStreamInitialized = () => {\n this.registerMediaElement();\n };\n\n private handleStreamTeardown = () => {\n this.core.destroy();\n this.unregisterMediaElement();\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 || media === this.media) return;\n this.unregisterMediaElement();\n this.media = media;\n for (const event of PLAYBACK_EVENTS) {\n media.addEventListener(event, this.handlePlaybackUpdate);\n }\n }\n\n private unregisterMediaElement() {\n const { media } = this;\n if (!media) return;\n for (const event of PLAYBACK_EVENTS) {\n media.removeEventListener(event, this.handlePlaybackUpdate);\n }\n this.media = undefined;\n }\n\n private handlePlaybackUpdate = (event: Event) => {\n const media = event.target as HTMLMediaElement;\n this.core.updatePlayback(getPlaybackStateFromMediaElement(media));\n };\n\n /** Cleans up and releases all resources, and unregisters all event handlers. */\n destroy() {\n this.core.destroy();\n this.unregisterMediaElement();\n if (this.player) {\n this.player.off(STREAM_INITIALIZED, this.handleStreamInitialized);\n this.player.off(STREAM_TEARDOWN_COMPLETE, this.handleStreamTeardown);\n }\n this.player = undefined;\n }\n}\n"],"mappings":";;;;;;;;;;AAQA,IAAa,eAAe;CAC1B,KAAK;CACL,cAAc;CACd,eAAe;CACf,eAAe;AACjB;;;ACOA,IAAM,gCAAqC,IAAI,IAAI;CACjD,aAAa;CACb,aAAa;CACb,aAAa;AACf,CAAC;;;;;;;;;;;AAYD,SAAgB,yBAAyB,MAAY,QAAqB,CAAC,GAAG;CAC5E,OAAO,SAAS,qBAA0D;EAIxE,MAAM,EAAE,WAAW;EAKnB,MAAM,SAAS,IAAI,cAAc,MAAM;GAHrC,MAAM,OAAO,KAAK,KAAK,MAAM;GAC7B,OAAO,OAAO,MAAM,KAAK,MAAM;EAEM,GAAU,KAAK;EACtD,OAAO;GACL,OAAO,SAAS,aAAa,OAAO,KAAK,SAAS,QAAQ;GAC1D,aAAa,OAAO,MAAM;EAC5B;CACF;AACF;AAEA,IAAM,gBAAN,MAAoB;CAMC;CACA;CACA;CAPnB,SAA0B,MAAM,qBAAqB;;CAErD;CAEA,YACE,MACA,QACA,OACA;EAHiB,KAAA,OAAA;EACA,KAAA,SAAA;EACA,KAAA,QAAA;CAChB;CAEH,KACE,SACA,UACS;EACT,MAAM,OAAO,QAAQ,YAAY,SAAS,QAAQ,KAAA;EAClD,MAAM,EAAE,QAAQ;EAChB,MAAM,YAAY,yBAChB,QAAQ,SAAS,SAAS,QAAQ,SAA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;EACb,KAAK,MAAM,SAAS,iBAClB,MAAM,iBAAiB,OAAO,KAAK,oBAAoB;CAE3D;CAEA,yBAAiC;EAC/B,MAAM,EAAE,UAAU;EAClB,IAAI,CAAC,OAAO;EACZ,KAAK,MAAM,SAAS,iBAClB,MAAM,oBAAoB,OAAO,KAAK,oBAAoB;EAE5D,KAAK,QAAQ,KAAA;CACf;CAEA,wBAAgC,UAAiB;EAC/C,MAAM,QAAQ,MAAM;EACpB,KAAK,KAAK,eAAe,iCAAiC,KAAK,CAAC;CAClE;;CAGA,UAAU;EACR,KAAK,KAAK,QAAQ;EAClB,KAAK,uBAAuB;EAC5B,IAAI,KAAK,QAAQ;GACf,KAAK,OAAO,IAAI,oBAAoB,KAAK,uBAAuB;GAChE,KAAK,OAAO,IAAI,0BAA0B,KAAK,oBAAoB;EACrE;EACA,KAAK,SAAS,KAAA;CAChB;AACF"}
@@ -0,0 +1,207 @@
1
+ import { dashManifestParser as e } from "p2p-media-loader-core/dash";
2
+ import { Core as t, Core as n, CoreRequestError as r, byteRangeFromRangeHeader as i, debug as a, getPlaybackStateFromMediaElement as o, liveDelayFor as s } from "p2p-media-loader-core";
3
+ //#region src/types.ts
4
+ var c = {
5
+ MPD: "MPD",
6
+ INIT_SEGMENT: "InitializationSegment",
7
+ MEDIA_SEGMENT: "MediaSegment",
8
+ INDEX_SEGMENT: "IndexSegment"
9
+ }, l = /* @__PURE__ */ new Set([
10
+ c.INIT_SEGMENT,
11
+ c.MEDIA_SEGMENT,
12
+ c.INDEX_SEGMENT
13
+ ]);
14
+ function u(e, t = {}) {
15
+ return function() {
16
+ let { parent: n } = this, r = new d(e, {
17
+ load: n.load.bind(n),
18
+ abort: n.abort.bind(n)
19
+ }, t);
20
+ return {
21
+ load: (e, t) => r.load(e, t),
22
+ abort: () => r.abort()
23
+ };
24
+ };
25
+ }
26
+ var d = class {
27
+ core;
28
+ parent;
29
+ hooks;
30
+ logger = a("p2pml-dashjs:loader");
31
+ abortCurrent;
32
+ constructor(e, t, n) {
33
+ this.core = e, this.parent = t, this.hooks = n;
34
+ }
35
+ load(e, t) {
36
+ let n = e.customData?.request?.type ?? void 0, { url: r } = e, a = i(e.headers?.Range ?? e.headers?.range);
37
+ if (n === c.MPD) return this.passThroughAndObserve(e, t, (e) => {
38
+ if (typeof e != "string" && !f(e)) return;
39
+ let n = t.url, i = this.core.processManifest({
40
+ url: n !== void 0 && n !== "" ? n : r,
41
+ data: e
42
+ });
43
+ i && this.hooks.onManifestProcessed?.(i);
44
+ });
45
+ if (n !== void 0 && l.has(n)) {
46
+ if (this.core.isSegmentIndex(r, a)) return this.passThroughAndObserve(e, t, (e) => {
47
+ f(e) && this.core.processSegmentIndex({
48
+ url: r,
49
+ byteRange: a,
50
+ data: e
51
+ });
52
+ });
53
+ if (n === c.MEDIA_SEGMENT && this.core.isSegmentLoadable(r, a)) return this.serve(e, t, a), !0;
54
+ }
55
+ return this.parent.load(e, t);
56
+ }
57
+ abort() {
58
+ this.abortCurrent?.(), this.parent.abort();
59
+ }
60
+ passThroughAndObserve(e, t, n) {
61
+ e.customData ??= {};
62
+ let { customData: r } = e, i = r.onloadend;
63
+ return r.onloadend = () => {
64
+ try {
65
+ t.status >= 200 && t.status <= 299 && n(t.data);
66
+ } catch (t) {
67
+ this.logger("failed to process %s: %O", e.url, t);
68
+ }
69
+ i?.();
70
+ }, this.parent.load(e, t);
71
+ }
72
+ serve(e, t, n) {
73
+ let { url: i } = e;
74
+ e.customData ??= {};
75
+ let { customData: a } = e, o = !1, s = () => {
76
+ o || this.core.abortSegmentLoading(i, n);
77
+ };
78
+ a.abort = s, this.abortCurrent = s, this.core.loadSegment(i, { byteRange: n }).then(({ data: e, bandwidth: n }) => {
79
+ o = !0, t.url = i, t.status = 200, t.statusText = "OK", t.headers = {}, t.data = e;
80
+ let r = e.byteLength;
81
+ a.onprogress?.({
82
+ lengthComputable: !0,
83
+ loaded: 0,
84
+ total: r,
85
+ time: 1
86
+ }), a.onprogress?.({
87
+ lengthComputable: !0,
88
+ loaded: r,
89
+ total: r,
90
+ time: p(n, r)
91
+ }), a.onloadend?.();
92
+ }).catch((e) => {
93
+ if (o = !0, e instanceof r && e.type === "aborted") {
94
+ a.onabort?.();
95
+ return;
96
+ }
97
+ t.url = i, t.status = 0, t.statusText = e instanceof Error ? e.message : String(e), t.data = void 0, this.logger("core failed to load %s: %O", i, e), a.onloadend?.();
98
+ });
99
+ }
100
+ };
101
+ function f(e) {
102
+ return e instanceof ArrayBuffer || ArrayBuffer.isView(e);
103
+ }
104
+ function p(e, t) {
105
+ return e <= 0 ? 1 : Math.max(1, Math.round(t * 8 * 1e3 / e));
106
+ }
107
+ //#endregion
108
+ //#region src/engine.ts
109
+ var m = 25, h = 2, g = 1, _ = "streamInitialized", v = "streamTeardownComplete", y = [
110
+ "timeupdate",
111
+ "progress",
112
+ "seeking",
113
+ "seeked",
114
+ "ratechange",
115
+ "play",
116
+ "pause",
117
+ "waiting"
118
+ ], b = class {
119
+ player;
120
+ media;
121
+ core;
122
+ managesLiveDelay = !1;
123
+ debug = a("p2pml-dashjs:engine");
124
+ constructor(t) {
125
+ this.core = new n({
126
+ ...t?.core,
127
+ manifestParsers: t?.core?.manifestParsers ?? [e]
128
+ });
129
+ }
130
+ bindPlayer(e) {
131
+ if (this.player === e) return;
132
+ this.player && this.destroy(), this.player = e;
133
+ let t = e.getSettings().streaming?.delay?.liveDelay;
134
+ this.managesLiveDelay = t === void 0 || Number.isNaN(t), this.managesLiveDelay && e.updateSettings({ streaming: { delay: {
135
+ liveDelay: m,
136
+ useSuggestedPresentationDelay: !1
137
+ } } }), e.extend("XHRLoader", u(this.core, { onManifestProcessed: this.applyLivePlacement }), !0), e.on(_, this.handleStreamInitialized), e.on(v, this.handleStreamTeardown), this.registerMediaElement();
138
+ }
139
+ applyDynamicConfig(e) {
140
+ e.core && this.core.applyDynamicConfig(e.core);
141
+ }
142
+ getConfig() {
143
+ return { core: this.core.getConfig() };
144
+ }
145
+ addEventListener(e, t) {
146
+ this.core.addEventListener(e, t);
147
+ }
148
+ removeEventListener(e, t) {
149
+ this.core.removeEventListener(e, t);
150
+ }
151
+ applyLivePlacement = (e) => {
152
+ if (!this.player || !this.managesLiveDelay) return;
153
+ let t = s(e);
154
+ if (!t) return;
155
+ let n = this.player.getSettings().streaming?.delay?.liveDelay;
156
+ if (n !== void 0 && !Number.isNaN(n) && Math.abs(n - t.delay) < t.segment / 2) return;
157
+ let r = this.forwardBufferSettings(t);
158
+ this.debug(`Setting liveDelay to ${t.delay}, forward buffer to ${r.bufferTimeDefault}`), this.player.updateSettings({ streaming: {
159
+ delay: { liveDelay: t.delay },
160
+ buffer: r
161
+ } });
162
+ };
163
+ forwardBufferSettings(e) {
164
+ let { mainStream: t, secondaryStream: n } = this.core.getConfig(), r = Math.max(t.highDemandTimeWindow, n.highDemandTimeWindow), i = Math.max(e.segment * h, Math.min(r, e.delay - e.segment * g)), a = this.player?.getSettings().streaming?.buffer, o = (e) => e === void 0 || Number.isNaN(e) || e > i ? i : e;
165
+ return {
166
+ bufferTimeDefault: o(a?.bufferTimeDefault),
167
+ bufferTimeAtTopQuality: o(a?.bufferTimeAtTopQuality),
168
+ bufferTimeAtTopQualityLongForm: o(a?.bufferTimeAtTopQualityLongForm)
169
+ };
170
+ }
171
+ handleStreamInitialized = () => {
172
+ this.registerMediaElement();
173
+ };
174
+ handleStreamTeardown = () => {
175
+ this.core.destroy(), this.unregisterMediaElement();
176
+ };
177
+ registerMediaElement() {
178
+ let e;
179
+ try {
180
+ e = this.player?.getVideoElement();
181
+ } catch {
182
+ return;
183
+ }
184
+ if (e && e !== this.media) {
185
+ this.unregisterMediaElement(), this.media = e;
186
+ for (let t of y) e.addEventListener(t, this.handlePlaybackUpdate);
187
+ }
188
+ }
189
+ unregisterMediaElement() {
190
+ let { media: e } = this;
191
+ if (e) {
192
+ for (let t of y) e.removeEventListener(t, this.handlePlaybackUpdate);
193
+ this.media = void 0;
194
+ }
195
+ }
196
+ handlePlaybackUpdate = (e) => {
197
+ let t = e.target;
198
+ this.core.updatePlayback(o(t));
199
+ };
200
+ destroy() {
201
+ this.core.destroy(), this.unregisterMediaElement(), this.player && (this.player.off(_, this.handleStreamInitialized), this.player.off(v, this.handleStreamTeardown)), this.player = void 0;
202
+ }
203
+ };
204
+ //#endregion
205
+ export { t as Core, b as DashJsP2PEngine };
206
+
207
+ //# sourceMappingURL=p2p-media-loader-dashjs.es.min.js.map