@ac-kit/format-dash 0.0.0-stage → 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (92) hide show
  1. package/CHANGELOG.md +78 -0
  2. package/LICENSE +28 -0
  3. package/README.md +180 -2
  4. package/dist/_template.d.ts +34 -0
  5. package/dist/_template.d.ts.map +1 -0
  6. package/dist/_template.js +90 -0
  7. package/dist/_template.js.map +1 -0
  8. package/dist/_xlink.d.ts +9 -0
  9. package/dist/_xlink.d.ts.map +1 -0
  10. package/dist/_xlink.js +14 -0
  11. package/dist/_xlink.js.map +1 -0
  12. package/dist/dash-namespaces.d.ts +27 -0
  13. package/dist/dash-namespaces.d.ts.map +1 -0
  14. package/dist/dash-namespaces.js +30 -0
  15. package/dist/dash-namespaces.js.map +1 -0
  16. package/dist/errors.d.ts +127 -0
  17. package/dist/errors.d.ts.map +1 -0
  18. package/dist/errors.js +52 -0
  19. package/dist/errors.js.map +1 -0
  20. package/dist/index.d.ts +12 -0
  21. package/dist/index.d.ts.map +1 -0
  22. package/dist/index.js +12 -0
  23. package/dist/index.js.map +1 -0
  24. package/dist/limits.d.ts +51 -0
  25. package/dist/limits.d.ts.map +1 -0
  26. package/dist/limits.js +39 -0
  27. package/dist/limits.js.map +1 -0
  28. package/dist/model/dash-common.d.ts +124 -0
  29. package/dist/model/dash-common.d.ts.map +1 -0
  30. package/dist/model/dash-common.js +2 -0
  31. package/dist/model/dash-common.js.map +1 -0
  32. package/dist/model/dash-mpd.d.ts +111 -0
  33. package/dist/model/dash-mpd.d.ts.map +1 -0
  34. package/dist/model/dash-mpd.js +2 -0
  35. package/dist/model/dash-mpd.js.map +1 -0
  36. package/dist/model/dash-segment-information.d.ts +90 -0
  37. package/dist/model/dash-segment-information.d.ts.map +1 -0
  38. package/dist/model/dash-segment-information.js +2 -0
  39. package/dist/model/dash-segment-information.js.map +1 -0
  40. package/dist/parse/_attribute-reader.d.ts +94 -0
  41. package/dist/parse/_attribute-reader.d.ts.map +1 -0
  42. package/dist/parse/_attribute-reader.js +382 -0
  43. package/dist/parse/_attribute-reader.js.map +1 -0
  44. package/dist/parse/_context.d.ts +35 -0
  45. package/dist/parse/_context.d.ts.map +1 -0
  46. package/dist/parse/_context.js +39 -0
  47. package/dist/parse/_context.js.map +1 -0
  48. package/dist/parse/_xs-temporal.d.ts +22 -0
  49. package/dist/parse/_xs-temporal.d.ts.map +1 -0
  50. package/dist/parse/_xs-temporal.js +98 -0
  51. package/dist/parse/_xs-temporal.js.map +1 -0
  52. package/dist/parse/parse-dash-mpd.d.ts +67 -0
  53. package/dist/parse/parse-dash-mpd.d.ts.map +1 -0
  54. package/dist/parse/parse-dash-mpd.js +928 -0
  55. package/dist/parse/parse-dash-mpd.js.map +1 -0
  56. package/dist/resolve/_base-url.d.ts +41 -0
  57. package/dist/resolve/_base-url.d.ts.map +1 -0
  58. package/dist/resolve/_base-url.js +69 -0
  59. package/dist/resolve/_base-url.js.map +1 -0
  60. package/dist/resolve/_essential-properties.d.ts +38 -0
  61. package/dist/resolve/_essential-properties.d.ts.map +1 -0
  62. package/dist/resolve/_essential-properties.js +106 -0
  63. package/dist/resolve/_essential-properties.js.map +1 -0
  64. package/dist/resolve/_inherit.d.ts +43 -0
  65. package/dist/resolve/_inherit.d.ts.map +1 -0
  66. package/dist/resolve/_inherit.js +105 -0
  67. package/dist/resolve/_inherit.js.map +1 -0
  68. package/dist/resolve/_segment-runs.d.ts +81 -0
  69. package/dist/resolve/_segment-runs.d.ts.map +1 -0
  70. package/dist/resolve/_segment-runs.js +126 -0
  71. package/dist/resolve/_segment-runs.js.map +1 -0
  72. package/dist/resolve/dash-resolve-diagnostic.d.ts +34 -0
  73. package/dist/resolve/dash-resolve-diagnostic.d.ts.map +1 -0
  74. package/dist/resolve/dash-resolve-diagnostic.js +2 -0
  75. package/dist/resolve/dash-resolve-diagnostic.js.map +1 -0
  76. package/dist/resolve/resolve-dash-representations.d.ts +130 -0
  77. package/dist/resolve/resolve-dash-representations.d.ts.map +1 -0
  78. package/dist/resolve/resolve-dash-representations.js +203 -0
  79. package/dist/resolve/resolve-dash-representations.js.map +1 -0
  80. package/dist/resolve/resolve-dash-segments.d.ts +169 -0
  81. package/dist/resolve/resolve-dash-segments.d.ts.map +1 -0
  82. package/dist/resolve/resolve-dash-segments.js +665 -0
  83. package/dist/resolve/resolve-dash-segments.js.map +1 -0
  84. package/dist/timing/_exact-period-timings.d.ts +28 -0
  85. package/dist/timing/_exact-period-timings.d.ts.map +1 -0
  86. package/dist/timing/_exact-period-timings.js +142 -0
  87. package/dist/timing/_exact-period-timings.js.map +1 -0
  88. package/dist/timing/dash-period-timings.d.ts +29 -0
  89. package/dist/timing/dash-period-timings.d.ts.map +1 -0
  90. package/dist/timing/dash-period-timings.js +23 -0
  91. package/dist/timing/dash-period-timings.js.map +1 -0
  92. package/package.json +63 -3
@@ -0,0 +1,665 @@
1
+ import { bigIntDivCeil, bigIntDivFloor, bigIntMax, bigIntMin, float64ToBits, UnsupportedError, withWorkBudget, } from "@ac-kit/core";
2
+ import { parseTemplate, substituteTemplate, templateUses, } from "../_template.js";
3
+ import { xlinkState } from "../_xlink.js";
4
+ import { DashLimitError, DashResolveError } from "../errors.js";
5
+ import { DEFAULT_DASH_LIMITS, DEFAULT_DASH_WORK_BUDGET } from "../limits.js";
6
+ import { exactNanoseconds, exactPeriodTimingFor, } from "../timing/_exact-period-timings.js";
7
+ import { chooseFirstBaseUrl, documentBase, resolveBaseChain, } from "./_base-url.js";
8
+ import { effectiveSegmentInformation, } from "./_inherit.js";
9
+ import { GIGA_, selectInRun, terminalCount, timelineRuns, } from "./_segment-runs.js";
10
+ const MAX_SAFE_ = BigInt(Number.MAX_SAFE_INTEGER);
11
+ /** `Temporal.Instant`'s range: ±10⁸ days in nanoseconds. */
12
+ const MAX_INSTANT_ = 8640000000000000000000n;
13
+ /** MPD attributes listing depends on, refused when a lenient parse lost them. */
14
+ const MPD_CRITICAL_ = new Set([
15
+ "type",
16
+ "availabilityStartTime",
17
+ "availabilityEndTime",
18
+ "mediaPresentationDuration",
19
+ "timeShiftBufferDepth",
20
+ ]);
21
+ /**
22
+ * Lists the segments of one Representation against `mpdUrl`, the URL the MPD
23
+ * was fetched from after redirects. Pure: no I/O, no clock.
24
+ *
25
+ * - Segment information is inherited attribute by attribute Period →
26
+ * AdaptationSet → Representation (§5.3.9.1), SegmentURLs from the nearest
27
+ * SegmentList that has some; BaseURLs are resolved level by level with the
28
+ * WHATWG `URL`, an absolute one resetting the chain; templates are
29
+ * substituted (§5.3.9.4.4) before resolution.
30
+ * - Simple addressing (`@duration`) places segment `k` at `@eptDelta + k ×
31
+ *
32
+ * @throws {RangeError} When `path` is out of range or names a `resolve-to-zero`
33
+ * element, `from`/`to` is `NaN` or too large to scale, or the MPD is dynamic
34
+ * and `now` is missing.
35
+ * @throws {TypeError} When `mpdUrl` is not an absolute URL.
36
+ * @throws {DashResolveError} When the segment description cannot be listed; see
37
+ * {@link DashResolveErrorCode}.
38
+ * @throws {DashLimitError} When more than `maxSegments` segments are selected,
39
+ * or a private `budget` runs out.
40
+ * @throws {UnsupportedError} For an unresolved remote Period, AdaptationSet or
41
+ * SegmentList, `S@k` above 1, `$SubNumber$`, or a BaseURL with `@byteRange`.
42
+ * @throws Whatever a caller's `budget` throws once spent.
43
+ * @duration` from the Period start, up to the segment that reaches the
44
+ * Period end or `@endNumber` (DASH-IF timing model §18.4).
45
+ * - A negative `S@r` repeats up to the next `S@t`, which must be written; on
46
+ * the last `S`, up to the Period end, `@endNumber`, the SegmentURL count or,
47
+ * live, the last segment available at `now`, whichever comes first.
48
+ * - A dynamic MPD keeps the segments available at `now` (DASH-IF IOP 4.3
49
+ * §4.3.2.2.7): from their availability start — `availabilityStartTime` +
50
+ * Period start + segment end − `availabilityTimeOffset`, the offsets of the
51
+ * segment information and of every chosen BaseURL summed, `INF` making every
52
+ * announced segment available early — to their availability end, that time
53
+ * without the offset plus `timeShiftBufferDepth` (the segment
54
+ * information's, a BaseURL's, else the MPD's; unbounded when absent) plus
55
+ * their duration. Nothing is available past `availabilityEndTime`. A
56
+ * SegmentList's timeline is checked against all its SegmentURLs before the
57
+ * window applies.
58
+ * - Segments outside the Period are never listed.
59
+ *
60
+ * Setup costs O(P + S + L) for P Periods, S `<S>` entries and L selected
61
+ * SegmentURLs, independent of timeline repeat counts — `r =
62
+ * 2^62` costs what `r = 0` does, as counts and window bounds come from bigint
63
+ * division. Runs are selected as they are computed, using memory
64
+ * O(selected runs). Each segment then costs O(URL length) when iterated.
65
+ */
66
+ export function resolveDashSegments(mpd, mpdUrl, path, options) {
67
+ const documentUrl = documentBase(mpdUrl);
68
+ const period = mpd.periods[path.period];
69
+ const adaptationSet = period?.adaptationSets[path.adaptationSet];
70
+ const representation = adaptationSet?.representations[path.representation];
71
+ if (period === undefined ||
72
+ adaptationSet === undefined ||
73
+ representation === undefined) {
74
+ throw new RangeError(`No Representation at ${path.period}/${path.adaptationSet}/${path.representation}`);
75
+ }
76
+ for (const [name, xlink] of [
77
+ ["Period", period.xlink],
78
+ ["AdaptationSet", adaptationSet.xlink],
79
+ ]) {
80
+ const state = xlinkState(xlink);
81
+ if (state === "absent") {
82
+ throw new RangeError(`The ${name} resolves to zero: it is absent`);
83
+ }
84
+ if (state === "remote") {
85
+ throw new UnsupportedError(`The remote ${name} "${xlink.href}" is not resolved`);
86
+ }
87
+ }
88
+ if (mpd.type === null) {
89
+ throw new DashResolveError("unreadable-value", "MPD@type could not be read");
90
+ }
91
+ if (mpd.type === "dynamic" && options?.now === undefined) {
92
+ throw new RangeError("A dynamic MPD needs `now`");
93
+ }
94
+ const span = spanBounds_(options?.from, options?.to);
95
+ return withWorkBudget(options?.budget ?? DEFAULT_DASH_WORK_BUDGET, (budget) => plan_({
96
+ mpd,
97
+ period,
98
+ representation,
99
+ path,
100
+ documentUrl,
101
+ now: options?.now ?? null,
102
+ span,
103
+ maxSegments: options?.maxSegments ?? DEFAULT_DASH_LIMITS.maxSegments,
104
+ choose: options?.chooseBaseUrl ?? chooseFirstBaseUrl,
105
+ budget,
106
+ }, [period, adaptationSet, representation], [
107
+ mpd.baseUrls,
108
+ period.baseUrls,
109
+ adaptationSet.baseUrls,
110
+ representation.baseUrls,
111
+ ]), (cause) => new DashLimitError("budget", cause.limit, null, { cause }));
112
+ }
113
+ function plan_(request, levels, baseLevels) {
114
+ const { mpd, representation, path, budget } = request;
115
+ budget.spend(baseLevels.length + levels.length);
116
+ const warnings = [];
117
+ const chain = resolveBaseChain(baseLevels, request.documentUrl, request.choose, path, warnings);
118
+ const information = effectiveSegmentInformation(levels);
119
+ if (information.remoteList !== null) {
120
+ throw new UnsupportedError(`The remote SegmentList "${information.remoteList}" is not resolved`);
121
+ }
122
+ refuseUnreadable_(mpd, information, chain);
123
+ // One segment spanning the Period is timed in nanoseconds, so its end is
124
+ // exact whatever the declared timescale.
125
+ const wholePeriod = spansWholePeriod_(information);
126
+ if (!wholePeriod && information.timescale === 0) {
127
+ throw new DashResolveError("invalid-timescale", "@timescale is 0");
128
+ }
129
+ const timescale = wholePeriod ? GIGA_ : BigInt(information.timescale);
130
+ const timing = exactPeriodTimingFor(mpd, path.period);
131
+ if (timing.start === null) {
132
+ throw new DashResolveError("unknown-period-start", `Period ${path.period} has no known start`);
133
+ }
134
+ const periodStart = timing.start;
135
+ const periodEnd = timing.duration === null ? null : timing.duration * timescale;
136
+ const live = mpd.type === "dynamic"
137
+ ? liveWindow_(mpd, information, chain, request.now, periodStart, timescale)
138
+ : null;
139
+ const maxNumber = information.endNumber === null ? null : BigInt(information.endNumber);
140
+ const span = request.span;
141
+ const from = scaledSpanBound_(span.from, timescale, periodStart, "from");
142
+ const to = scaledSpanBound_(span.to, timescale, periodStart, "to");
143
+ const bounds = {
144
+ startBefore: minNullable_(periodEnd, to),
145
+ endAfter: bigIntMax(0n, from ?? 0n),
146
+ endAtMost: live?.endAtMost ?? null,
147
+ endPlusDurationAtLeast: live?.endPlusDurationAtLeast ?? null,
148
+ maxNumber,
149
+ };
150
+ const terminal = {
151
+ periodEnd,
152
+ availability: live?.endAtMost ?? null,
153
+ maxNumber,
154
+ maxCount: null,
155
+ };
156
+ const plan = planOf_(information, representation, chain.base, timescale, terminal, path, warnings);
157
+ const selections = [];
158
+ let count = 0n;
159
+ const empty = span.empty || live?.ended === true;
160
+ const limit = BigInt(request.maxSegments);
161
+ for (const run of plan.runs()) {
162
+ budget.spend(1);
163
+ if (empty) {
164
+ continue;
165
+ }
166
+ const [first, last] = selectInRun(run, bounds);
167
+ if (last <= first) {
168
+ continue;
169
+ }
170
+ count += last - first;
171
+ if (count <= limit) {
172
+ selections.push([run, first, last]);
173
+ }
174
+ }
175
+ if (count > limit) {
176
+ throw new DashLimitError("maxSegments", request.maxSegments, count);
177
+ }
178
+ for (const [run, first, last] of selections) {
179
+ if (run.firstNumber + last - 1n > MAX_SAFE_) {
180
+ throw new DashResolveError("unsafe-segment-number", "A selected segment number passes 2^53-1");
181
+ }
182
+ if (plan.addressing === "list") {
183
+ const end = Number(run.listOffset + last);
184
+ for (let index = Number(run.listOffset + first); index < end; index++) {
185
+ budget.spend(1);
186
+ const attribute = plan.segmentUrls[index]?.invalidAttributes?.find(({ name }) => name.local === "mediaRange" || name.local === "indexRange");
187
+ if (attribute !== undefined) {
188
+ throw new DashResolveError("unreadable-value", `SegmentURL ${index}@${attribute.name.local} could not be read`);
189
+ }
190
+ }
191
+ }
192
+ if (live !== null) {
193
+ checkInstants_(live, periodStart, timescale, run, first, last);
194
+ }
195
+ }
196
+ const context = {
197
+ plan,
198
+ timescale,
199
+ periodStart,
200
+ live,
201
+ base: chain.base,
202
+ representation,
203
+ indexRange: information.indexRange,
204
+ path,
205
+ };
206
+ return {
207
+ addressing: plan.addressing,
208
+ timeline: plan.timeline,
209
+ initialization: plan.initialization,
210
+ index: plan.index,
211
+ segments: {
212
+ count: Number(count),
213
+ [Symbol.iterator]: () => iterateSegments_(context, selections),
214
+ },
215
+ warnings,
216
+ };
217
+ }
218
+ function spanBounds_(from, to) {
219
+ for (const [name, seconds, open] of [
220
+ ["from", from, -Infinity],
221
+ ["to", to, Infinity],
222
+ ]) {
223
+ if (seconds !== undefined &&
224
+ seconds !== open &&
225
+ !Number.isFinite(seconds * 1e9)) {
226
+ throw new RangeError(`\`${name}\` is ${seconds}, not a usable bound`);
227
+ }
228
+ }
229
+ return {
230
+ from,
231
+ to,
232
+ empty: from !== undefined && to !== undefined && from >= to,
233
+ };
234
+ }
235
+ /** Scales a binary64 bound exactly before rounding for a strict inequality. */
236
+ function scaledSpanBound_(seconds, timescale, periodStart, bound) {
237
+ if (seconds === undefined || !Number.isFinite(seconds)) {
238
+ return null;
239
+ }
240
+ const bits = float64ToBits(seconds);
241
+ const exponent = Number((bits >> 52n) & 0x7ffn);
242
+ const significand = (bits & ((1n << 52n) - 1n)) + (exponent === 0 ? 0n : 1n << 52n);
243
+ const shift = BigInt(Math.max(1, exponent) - 1023 - 52);
244
+ const scaled = (seconds < 0 ? -significand : significand) * GIGA_ * timescale;
245
+ // Segment endpoints in this domain are integers: x > f iff x > floor(f),
246
+ // and x < t iff x < ceil(t). The Period start is already an integer here.
247
+ const rounded = shift >= 0n
248
+ ? scaled << shift
249
+ : bound === "from"
250
+ ? scaled >> -shift
251
+ : bigIntDivCeil(scaled, 1n << -shift);
252
+ return rounded - periodStart * timescale;
253
+ }
254
+ function refuseUnreadable_(mpd, information, chain) {
255
+ const refuse = (where, attribute) => {
256
+ throw new DashResolveError("unreadable-value", `${where}@${attribute.name.local} could not be read`);
257
+ };
258
+ for (const attribute of mpd.invalidAttributes) {
259
+ if (MPD_CRITICAL_.has(attribute.name.local)) {
260
+ refuse("MPD", attribute);
261
+ }
262
+ }
263
+ const [segmentAttribute] = information.invalidAttributes;
264
+ if (segmentAttribute !== undefined) {
265
+ refuse("Segment information", segmentAttribute);
266
+ }
267
+ const [baseAttribute] = chain.invalidAttributes;
268
+ if (baseAttribute !== undefined) {
269
+ refuse("BaseURL", baseAttribute);
270
+ }
271
+ }
272
+ function liveWindow_(mpd, information, chain, now, periodStart, timescale) {
273
+ if (mpd.availabilityStartTime === null) {
274
+ throw new DashResolveError("missing-attribute", "A dynamic MPD has no @availabilityStartTime");
275
+ }
276
+ const availabilityStart = mpd.availabilityStartTime.epochNanoseconds;
277
+ let offset = null;
278
+ if (information.availabilityTimeOffset !== Infinity &&
279
+ !chain.infiniteOffset) {
280
+ const seconds = (information.availabilityTimeOffset ?? 0) + chain.availabilityTimeOffset;
281
+ const scaled = seconds * 1e9;
282
+ if (!Number.isFinite(scaled)) {
283
+ throw new DashResolveError("invalid-availability", `The availabilityTimeOffsets sum to ${seconds} s, past what can be scaled`);
284
+ }
285
+ offset = BigInt(Math.round(scaled));
286
+ }
287
+ const depth = information.timeShiftBufferDepth ??
288
+ chain.timeShiftBufferDepth ??
289
+ mpd.timeShiftBufferDepth;
290
+ const timeShiftBufferDepth = depth === null ? null : exactNanoseconds(depth);
291
+ const elapsed = now.epochNanoseconds - availabilityStart - periodStart;
292
+ return {
293
+ availabilityStart,
294
+ offset,
295
+ timeShiftBufferDepth,
296
+ endAtMost: offset === null ? null : (elapsed + offset) * timescale,
297
+ endPlusDurationAtLeast: timeShiftBufferDepth === null
298
+ ? null
299
+ : (elapsed - timeShiftBufferDepth) * timescale,
300
+ ended: mpd.availabilityEndTime !== null &&
301
+ Temporal.Instant.compare(now, mpd.availabilityEndTime) > 0,
302
+ };
303
+ }
304
+ /**
305
+ * Checks the availability instants of a selection's first and last segments —
306
+ * the extremes, as they grow with the segment end — fit a `Temporal.Instant`,
307
+ * so iterating never throws.
308
+ */
309
+ function checkInstants_(live, periodStart, timescale, run, first, last) {
310
+ for (const k of [first, last - 1n]) {
311
+ const instants = availabilityOf_(live, periodStart, timescale, run, k);
312
+ for (const instant of instants) {
313
+ if (instant !== null &&
314
+ (instant > MAX_INSTANT_ || instant < -MAX_INSTANT_)) {
315
+ throw new DashResolveError("invalid-availability", "A segment's availability falls outside the range of an instant");
316
+ }
317
+ }
318
+ }
319
+ }
320
+ /** Availability start and end of segment `k` of `run`, epoch nanoseconds. */
321
+ function availabilityOf_(live, periodStart, timescale, run, k) {
322
+ const relativeEnd = run.relativeStart + (k + 1n) * run.duration;
323
+ const end = live.availabilityStart +
324
+ periodStart +
325
+ bigIntDivFloor(relativeEnd * GIGA_, timescale);
326
+ return [
327
+ live.offset === null ? null : end - live.offset,
328
+ live.timeShiftBufferDepth === null
329
+ ? null
330
+ : end +
331
+ live.timeShiftBufferDepth +
332
+ bigIntDivFloor(run.duration * GIGA_, timescale),
333
+ ];
334
+ }
335
+ function planOf_(information, representation, base, timescale, terminal, path, warnings) {
336
+ const resource = (url) => url === null ? null : urlResource_(url, base, path, warnings);
337
+ const startNumber = BigInt(information.startNumber);
338
+ const pto = information.presentationTimeOffset;
339
+ const eptDelta = information.eptDelta;
340
+ const wholePeriod = () => [
341
+ {
342
+ firstNumber: startNumber,
343
+ relativeStart: 0n,
344
+ timeValue: 0n,
345
+ duration: wholePeriodDuration_(terminal.periodEnd),
346
+ count: 1n,
347
+ listOffset: 0n,
348
+ },
349
+ ];
350
+ const timeline = information.segmentTimeline;
351
+ if (timeline !== null) {
352
+ for (const entry of timeline.entries) {
353
+ if (entry.k !== null && entry.k > 1) {
354
+ throw new UnsupportedError("S@k (segment sequences) is not supported");
355
+ }
356
+ }
357
+ }
358
+ const constantDuration = () => {
359
+ const duration = BigInt(information.duration);
360
+ if (duration === 0n) {
361
+ throw new DashResolveError("invalid-duration", "@duration is 0");
362
+ }
363
+ return duration;
364
+ };
365
+ switch (information.kind) {
366
+ case "none":
367
+ case "base": {
368
+ const index = information.representationIndex === null
369
+ ? information.indexRange === null
370
+ ? null
371
+ : { href: base?.href ?? null, range: information.indexRange }
372
+ : resource(information.representationIndex);
373
+ const runs = wholePeriod();
374
+ return {
375
+ addressing: "base",
376
+ timeline: false,
377
+ initialization: resource(information.initialization),
378
+ index,
379
+ runs: () => runs,
380
+ media: null,
381
+ segmentIndex: null,
382
+ segmentUrls: [],
383
+ };
384
+ }
385
+ case "list": {
386
+ const segmentUrls = information.segmentUrls;
387
+ const entries = BigInt(segmentUrls.length);
388
+ let runs;
389
+ if (timeline !== null) {
390
+ const listTerminal = {
391
+ periodEnd: terminal.periodEnd,
392
+ availability: null,
393
+ maxNumber: terminal.maxNumber,
394
+ maxCount: entries,
395
+ };
396
+ // The whole mapping is checked before any window applies.
397
+ let described = 0n;
398
+ for (const run of timelineRuns(timeline.entries, pto, startNumber, listTerminal)) {
399
+ described += run.count;
400
+ }
401
+ if (described !== entries) {
402
+ throw new DashResolveError("segment-count-mismatch", `The SegmentTimeline describes ${described} segments for ${entries} SegmentURLs`);
403
+ }
404
+ runs = () => timelineRuns(timeline.entries, pto, startNumber, listTerminal);
405
+ }
406
+ else if (information.duration !== null) {
407
+ const single = [
408
+ {
409
+ firstNumber: startNumber,
410
+ relativeStart: eptDelta,
411
+ timeValue: pto,
412
+ duration: constantDuration(),
413
+ count: entries,
414
+ listOffset: 0n,
415
+ },
416
+ ];
417
+ runs = () => single;
418
+ }
419
+ else if (entries <= 1n) {
420
+ const single = entries === 0n ? [] : wholePeriod();
421
+ runs = () => single;
422
+ }
423
+ else {
424
+ throw new DashResolveError("missing-segment-duration", "A SegmentList of several entries needs @duration or a SegmentTimeline");
425
+ }
426
+ return {
427
+ addressing: "list",
428
+ timeline: timeline !== null,
429
+ initialization: resource(information.initialization),
430
+ index: resource(information.representationIndex),
431
+ runs,
432
+ media: null,
433
+ segmentIndex: null,
434
+ segmentUrls,
435
+ };
436
+ }
437
+ case "template": {
438
+ if (information.media === null) {
439
+ throw new DashResolveError("missing-media", "The SegmentTemplate has no @media");
440
+ }
441
+ const media = templateParts_(information.media, representation);
442
+ const initialization = information.initializationTemplate === null
443
+ ? resource(information.initialization)
444
+ : templateResource_(templateParts_(information.initializationTemplate, representation), representation, base, path, warnings);
445
+ let index = resource(information.representationIndex);
446
+ let segmentIndex = null;
447
+ if (information.index !== null) {
448
+ const parts = templateParts_(information.index, representation);
449
+ if (templateUses(parts, "Number") || templateUses(parts, "Time")) {
450
+ segmentIndex = parts;
451
+ }
452
+ else {
453
+ index = templateResource_(parts, representation, base, path, warnings);
454
+ }
455
+ }
456
+ let runs;
457
+ if (timeline !== null) {
458
+ runs = () => timelineRuns(timeline.entries, pto, startNumber, terminal);
459
+ }
460
+ else if (information.duration !== null) {
461
+ const duration = constantDuration();
462
+ const count = terminalCount(eptDelta, duration, startNumber, 0n, terminal);
463
+ if (count === null) {
464
+ throw new DashResolveError("unknown-period-duration", "Segments of a constant @duration need the Period's end or @endNumber");
465
+ }
466
+ const single = [
467
+ {
468
+ firstNumber: startNumber,
469
+ relativeStart: eptDelta,
470
+ timeValue: pto,
471
+ duration,
472
+ count,
473
+ listOffset: 0n,
474
+ },
475
+ ];
476
+ runs = () => single;
477
+ }
478
+ else {
479
+ const single = wholePeriod();
480
+ runs = () => single;
481
+ }
482
+ return {
483
+ addressing: "template",
484
+ timeline: timeline !== null,
485
+ initialization,
486
+ index,
487
+ runs,
488
+ media,
489
+ segmentIndex,
490
+ segmentUrls: [],
491
+ };
492
+ }
493
+ }
494
+ }
495
+ function spansWholePeriod_(information) {
496
+ switch (information.kind) {
497
+ case "none":
498
+ case "base":
499
+ return true;
500
+ case "list":
501
+ return (information.segmentTimeline === null &&
502
+ information.duration === null &&
503
+ information.segmentUrls.length <= 1);
504
+ case "template":
505
+ return (information.segmentTimeline === null && information.duration === null);
506
+ }
507
+ }
508
+ function wholePeriodDuration_(periodEnd) {
509
+ if (periodEnd === null) {
510
+ throw new DashResolveError("unknown-period-duration", "A single segment spanning the Period needs the Period's end");
511
+ }
512
+ const duration = bigIntDivCeil(periodEnd, GIGA_);
513
+ if (duration === 0n) {
514
+ throw new DashResolveError("unknown-period-duration", "The Period has no duration");
515
+ }
516
+ return duration;
517
+ }
518
+ function templateParts_(template, representation) {
519
+ const parts = parseTemplate(template);
520
+ if (typeof parts === "string") {
521
+ throw new DashResolveError("invalid-template", parts);
522
+ }
523
+ if (templateUses(parts, "SubNumber")) {
524
+ throw new UnsupportedError(`$SubNumber$ in "${template}" is not supported`);
525
+ }
526
+ if (templateUses(parts, "RepresentationID") && representation.id === null) {
527
+ throw new DashResolveError("missing-attribute", `"${template}" needs the Representation's @id`);
528
+ }
529
+ if (templateUses(parts, "Bandwidth") && representation.bandwidth === null) {
530
+ throw new DashResolveError("missing-attribute", `"${template}" needs the Representation's @bandwidth`);
531
+ }
532
+ return parts;
533
+ }
534
+ function templateResource_(parts, representation, base, path, warnings) {
535
+ const text = substituteTemplate(parts, {
536
+ representationId: representation.id,
537
+ bandwidth: representation.bandwidth,
538
+ number: null,
539
+ time: null,
540
+ });
541
+ if (typeof text !== "string") {
542
+ throw new DashResolveError("invalid-template", `$${text.missing}$ cannot be used here`);
543
+ }
544
+ const href = hrefOf_(text, base);
545
+ if (href === null && base !== null) {
546
+ warnings.push(invalidUri_(text, base, path));
547
+ }
548
+ return { href, range: null };
549
+ }
550
+ function urlResource_(url, base, path, warnings) {
551
+ if (url.sourceUrl === null) {
552
+ return { href: base?.href ?? null, range: url.range };
553
+ }
554
+ const href = hrefOf_(url.sourceUrl, base);
555
+ if (href === null && base !== null) {
556
+ warnings.push(invalidUri_(url.sourceUrl, base, path));
557
+ }
558
+ return { href, range: url.range };
559
+ }
560
+ function invalidUri_(uri, base, path) {
561
+ return {
562
+ code: "invalid-uri",
563
+ message: `"${uri}" does not resolve against ${base.href}`,
564
+ period: path.period,
565
+ adaptationSet: path.adaptationSet,
566
+ representation: path.representation,
567
+ uri,
568
+ };
569
+ }
570
+ function hrefOf_(uri, base) {
571
+ return (base === null ? URL.parse(uri) : URL.parse(uri, base))?.href ?? null;
572
+ }
573
+ function* iterateSegments_(context, selections) {
574
+ const { plan, timescale, periodStart, live, base, representation } = context;
575
+ const timescaleNumber = Number(timescale);
576
+ const periodStartSeconds = Number(periodStart) / 1e9;
577
+ for (const [run, first, last] of selections) {
578
+ for (let k = first; k < last; k++) {
579
+ const relativeStart = run.relativeStart + k * run.duration;
580
+ const relativeEnd = relativeStart + run.duration;
581
+ const number = Number(run.firstNumber + k);
582
+ const time = run.timeValue + k * run.duration;
583
+ let diagnostic = null;
584
+ const resolve = (uri) => {
585
+ const href = hrefOf_(uri, base);
586
+ if (href === null && base !== null) {
587
+ diagnostic ??= invalidUri_(uri, base, context.path);
588
+ }
589
+ return href;
590
+ };
591
+ const values = {
592
+ representationId: representation.id,
593
+ bandwidth: representation.bandwidth,
594
+ number,
595
+ time,
596
+ };
597
+ let href;
598
+ let range = null;
599
+ let index = null;
600
+ if (plan.media !== null) {
601
+ const text = substituteTemplate(plan.media, values);
602
+ href = typeof text === "string" ? resolve(text) : null;
603
+ if (plan.segmentIndex !== null) {
604
+ const indexText = substituteTemplate(plan.segmentIndex, values);
605
+ index = {
606
+ href: typeof indexText === "string" ? resolve(indexText) : null,
607
+ range: null,
608
+ };
609
+ }
610
+ }
611
+ else if (plan.addressing === "list") {
612
+ const entry = plan.segmentUrls[Number(run.listOffset + k)];
613
+ href = resolve(entry?.media ?? "");
614
+ range = entry?.mediaRange ?? null;
615
+ if (entry !== undefined &&
616
+ (entry.index !== null || entry.indexRange !== null)) {
617
+ index = {
618
+ href: entry.index === null ? href : resolve(entry.index),
619
+ range: entry.indexRange,
620
+ };
621
+ }
622
+ }
623
+ else {
624
+ href = base?.href ?? null;
625
+ }
626
+ if (index === null &&
627
+ context.indexRange !== null &&
628
+ plan.addressing !== "base") {
629
+ index = { href, range: context.indexRange };
630
+ }
631
+ let availabilityStart = null;
632
+ let availabilityEnd = null;
633
+ if (live !== null) {
634
+ const [startNs, endNs] = availabilityOf_(live, periodStart, timescale, run, k);
635
+ availabilityStart =
636
+ startNs === null
637
+ ? null
638
+ : Temporal.Instant.fromEpochNanoseconds(startNs);
639
+ availabilityEnd =
640
+ endNs === null ? null : Temporal.Instant.fromEpochNanoseconds(endNs);
641
+ }
642
+ yield {
643
+ href,
644
+ range,
645
+ number,
646
+ time,
647
+ duration: run.duration,
648
+ timescale: timescaleNumber,
649
+ start: periodStartSeconds + Number(relativeStart) / timescaleNumber,
650
+ end: periodStartSeconds + Number(relativeEnd) / timescaleNumber,
651
+ index,
652
+ diagnostic,
653
+ availabilityStart,
654
+ availabilityEnd,
655
+ };
656
+ }
657
+ }
658
+ }
659
+ function minNullable_(left, right) {
660
+ if (left === null) {
661
+ return right;
662
+ }
663
+ return right === null ? left : bigIntMin(left, right);
664
+ }
665
+ //# sourceMappingURL=resolve-dash-segments.js.map