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.
package/src/loader.ts ADDED
@@ -0,0 +1,220 @@
1
+ import {
2
+ Core,
3
+ CoreRequestError,
4
+ ProcessedManifest,
5
+ byteRangeFromRangeHeader,
6
+ debug,
7
+ } from "p2p-media-loader-core";
8
+ import {
9
+ CommonMediaRequestLike,
10
+ CommonMediaResponseLike,
11
+ FactoryMakerThis,
12
+ REQUEST_TYPE,
13
+ XhrLoaderLike,
14
+ } from "./types.js";
15
+
16
+ export type LoaderHooks = {
17
+ /** Called with what the core read from each MPD, before dash.js parses it. */
18
+ onManifestProcessed?: (manifest: ProcessedManifest) => void;
19
+ };
20
+
21
+ const SEGMENT_TYPES: ReadonlySet<string> = new Set([
22
+ REQUEST_TYPE.INIT_SEGMENT,
23
+ REQUEST_TYPE.MEDIA_SEGMENT,
24
+ REQUEST_TYPE.INDEX_SEGMENT,
25
+ ]);
26
+
27
+ /**
28
+ * The `XHRLoader` replacement, in the shape dash.js's `FactoryMaker` applies
29
+ * it: a plain function it calls with `this.parent` set to the real loader,
30
+ * whose `load` and `abort` the returned object overrides. Registered per
31
+ * player through `player.extend("XHRLoader", extension, true)`.
32
+ *
33
+ * Every request dash.js makes over HTTP passes through here — MPD, init,
34
+ * media and index segments, licences — and is told apart by the type of the
35
+ * `FragmentRequest` behind it. See specs/player-adapters.md, "dash.js".
36
+ */
37
+ export function createXhrLoaderExtension(core: Core, hooks: LoaderHooks = {}) {
38
+ return function xhrLoaderExtension(this: FactoryMakerThis): XhrLoaderLike {
39
+ // FactoryMaker copies the returned `load` and `abort` onto the parent
40
+ // instance itself, so `this.parent.load` would point back here once the
41
+ // override is applied. Keep dash.js's own methods before that happens.
42
+ const { parent } = this;
43
+ const original: XhrLoaderLike = {
44
+ load: parent.load.bind(parent),
45
+ abort: parent.abort.bind(parent),
46
+ };
47
+ const router = new RequestRouter(core, original, hooks);
48
+ return {
49
+ load: (request, response) => router.load(request, response),
50
+ abort: () => router.abort(),
51
+ };
52
+ };
53
+ }
54
+
55
+ class RequestRouter {
56
+ private readonly logger = debug("p2pml-dashjs:loader");
57
+ /** Aborts the request served by the core most recently, if still in flight. */
58
+ private abortCurrent?: () => void;
59
+
60
+ constructor(
61
+ private readonly core: Core,
62
+ private readonly parent: XhrLoaderLike,
63
+ private readonly hooks: LoaderHooks,
64
+ ) {}
65
+
66
+ load(
67
+ request: CommonMediaRequestLike,
68
+ response: CommonMediaResponseLike,
69
+ ): boolean {
70
+ const type = request.customData?.request?.type ?? undefined;
71
+ const { url } = request;
72
+ const byteRange = byteRangeFromRangeHeader(
73
+ request.headers?.Range ?? request.headers?.range,
74
+ );
75
+
76
+ // Every MPD dash.js fetches — first load and each refresh — reaches the
77
+ // core before dash.js parses the same bytes.
78
+ if (type === REQUEST_TYPE.MPD) {
79
+ return this.passThroughAndObserve(request, response, (data) => {
80
+ if (typeof data !== "string" && !isBinary(data)) return;
81
+ // The response URL, when the loader filled it in, follows redirects.
82
+ const responseUrl = response.url;
83
+ const processed = this.core.processManifest({
84
+ url:
85
+ responseUrl !== undefined && responseUrl !== "" ? responseUrl : url,
86
+ data,
87
+ });
88
+ if (processed) this.hooks.onManifestProcessed?.(processed);
89
+ });
90
+ }
91
+
92
+ if (type !== undefined && SEGMENT_TYPES.has(type)) {
93
+ // A SegmentBase stream's index: dash.js loads it, the core reads the
94
+ // segment list from the same bytes. Recognition, not lookup.
95
+ if (this.core.isSegmentIndex(url, byteRange)) {
96
+ return this.passThroughAndObserve(request, response, (data) => {
97
+ if (!isBinary(data)) return;
98
+ this.core.processSegmentIndex({ url, byteRange, data });
99
+ });
100
+ }
101
+
102
+ // Whitelist by lookup: a segment the registry knows on a stream with
103
+ // P2P enabled is served by the core; initialization segments and
104
+ // anything the registry does not know load through dash.js itself.
105
+ if (
106
+ type === REQUEST_TYPE.MEDIA_SEGMENT &&
107
+ this.core.isSegmentLoadable(url, byteRange)
108
+ ) {
109
+ this.serve(request, response, byteRange);
110
+ return true;
111
+ }
112
+ }
113
+
114
+ // Licences, certificates, steering, XLink, init segments: untouched.
115
+ return this.parent.load(request, response);
116
+ }
117
+
118
+ abort() {
119
+ this.abortCurrent?.();
120
+ this.parent.abort();
121
+ }
122
+
123
+ private passThroughAndObserve(
124
+ request: CommonMediaRequestLike,
125
+ response: CommonMediaResponseLike,
126
+ observe: (data: unknown) => void,
127
+ ): boolean {
128
+ request.customData ??= {};
129
+ const { customData } = request;
130
+ const original = customData.onloadend;
131
+ // dash.js's XHRLoader copies `onloadend` onto the XHR at `load`, so the
132
+ // wrap has to be in place before the parent runs.
133
+ customData.onloadend = () => {
134
+ try {
135
+ if (response.status >= 200 && response.status <= 299) {
136
+ observe(response.data);
137
+ }
138
+ } catch (error) {
139
+ this.logger("failed to process %s: %O", request.url, error);
140
+ }
141
+ original?.();
142
+ };
143
+ return this.parent.load(request, response);
144
+ }
145
+
146
+ private serve(
147
+ request: CommonMediaRequestLike,
148
+ response: CommonMediaResponseLike,
149
+ byteRange: ReturnType<typeof byteRangeFromRangeHeader>,
150
+ ) {
151
+ const { url } = request;
152
+ request.customData ??= {};
153
+ const { customData } = request;
154
+ let settled = false;
155
+
156
+ const abort = () => {
157
+ if (settled) return;
158
+ this.core.abortSegmentLoading(url, byteRange);
159
+ };
160
+ customData.abort = abort;
161
+ this.abortCurrent = abort;
162
+
163
+ this.core
164
+ .loadSegment(url, { byteRange })
165
+ .then(({ data, bandwidth }) => {
166
+ settled = true;
167
+ response.url = url;
168
+ response.status = 200;
169
+ response.statusText = "OK";
170
+ response.headers = {};
171
+ response.data = data;
172
+
173
+ // dash.js measures throughput from progress traces, dropping the
174
+ // first (it carries the latency) and summing the rest. Two events
175
+ // give it one download trace whose duration is the core's bandwidth
176
+ // hint — wall-clock time says nothing about the network for a segment
177
+ // that came from a peer or from storage. Never 0 ms.
178
+ const total = data.byteLength;
179
+ customData.onprogress?.({
180
+ lengthComputable: true,
181
+ loaded: 0,
182
+ total,
183
+ time: 1,
184
+ });
185
+ customData.onprogress?.({
186
+ lengthComputable: true,
187
+ loaded: total,
188
+ total,
189
+ time: loadingTimeMs(bandwidth, total),
190
+ });
191
+ customData.onloadend?.();
192
+ })
193
+ .catch((error: unknown) => {
194
+ settled = true;
195
+ if (error instanceof CoreRequestError && error.type === "aborted") {
196
+ customData.onabort?.();
197
+ return;
198
+ }
199
+ // A non-2xx status is what dash.js's HTTPLoader retries on; the
200
+ // failure is reported as one rather than thrown into dash.js.
201
+ response.url = url;
202
+ response.status = 0;
203
+ response.statusText =
204
+ error instanceof Error ? error.message : String(error);
205
+ response.data = undefined;
206
+ this.logger("core failed to load %s: %O", url, error);
207
+ customData.onloadend?.();
208
+ });
209
+ }
210
+ }
211
+
212
+ function isBinary(data: unknown): data is ArrayBuffer | ArrayBufferView {
213
+ return data instanceof ArrayBuffer || ArrayBuffer.isView(data);
214
+ }
215
+
216
+ /** Download time in ms for the core's bandwidth hint; see the Shaka adapter. */
217
+ function loadingTimeMs(bandwidth: number, bytes: number): number {
218
+ if (bandwidth <= 0) return 1;
219
+ return Math.max(1, Math.round((bytes * 8 * 1000) / bandwidth));
220
+ }
package/src/types.ts ADDED
@@ -0,0 +1,78 @@
1
+ /**
2
+ * The slice of dash.js's request plumbing the adapter touches, typed
3
+ * structurally. dash.js's own declarations for these live in
4
+ * `@svta/cml-request`, a transitive dependency this package cannot import
5
+ * directly, and the adapter needs only a handful of fields.
6
+ */
7
+
8
+ /** `HTTPRequest.*_TYPE` values a request carries in `customData.request.type`. */
9
+ export const REQUEST_TYPE = {
10
+ MPD: "MPD",
11
+ INIT_SEGMENT: "InitializationSegment",
12
+ MEDIA_SEGMENT: "MediaSegment",
13
+ INDEX_SEGMENT: "IndexSegment",
14
+ } as const;
15
+
16
+ /** What `_onprogress` in dash.js's HTTPLoader reads off a progress event. */
17
+ export type ProgressEventLike = {
18
+ lengthComputable: boolean;
19
+ loaded: number;
20
+ total: number;
21
+ /** Trace duration in ms; dash.js uses it instead of the wall clock when set. */
22
+ time?: number;
23
+ };
24
+
25
+ /** The dash.js `FragmentRequest` (or `TextRequest`) behind a network request. */
26
+ type FragmentRequestLike = {
27
+ type?: string | null;
28
+ url?: string | null;
29
+ range?: string | null;
30
+ mediaType?: string | null;
31
+ };
32
+
33
+ /** Callbacks and state dash.js's HTTPLoader hangs on a request. */
34
+ type RequestCustomData = {
35
+ request?: FragmentRequestLike;
36
+ onloadend?: () => void;
37
+ onprogress?: (event: ProgressEventLike) => void;
38
+ onabort?: () => void;
39
+ ontimeout?: (event: unknown) => void;
40
+ abort?: () => void;
41
+ };
42
+
43
+ /** `CommonMediaRequest` as HTTPLoader builds it. */
44
+ export type CommonMediaRequestLike = {
45
+ url: string;
46
+ method?: string;
47
+ responseType?: string;
48
+ headers?: Record<string, string | undefined>;
49
+ customData?: RequestCustomData;
50
+ };
51
+
52
+ /** `CommonMediaResponse` as HTTPLoader expects the loader to fill it. */
53
+ export type CommonMediaResponseLike = {
54
+ url?: string;
55
+ status: number;
56
+ statusText?: string;
57
+ headers?: Record<string, string> | null;
58
+ data?: unknown;
59
+ };
60
+
61
+ /** The instance dash.js's own `XHRLoader` factory produces. */
62
+ export type XhrLoaderLike = {
63
+ load(
64
+ request: CommonMediaRequestLike,
65
+ response: CommonMediaResponseLike,
66
+ ): boolean;
67
+ abort(): void;
68
+ };
69
+
70
+ /**
71
+ * What `FactoryMaker` binds as `this` when it applies an `override`
72
+ * extension: the real instance is `parent`.
73
+ */
74
+ export type FactoryMakerThis = {
75
+ context: object;
76
+ factory: unknown;
77
+ parent: XhrLoaderLike;
78
+ };