mattebox 0.16.2 → 0.17.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.
Files changed (78) hide show
  1. package/dist/cdn/mattebox.dash-drm.min.js +3 -3
  2. package/dist/cdn/mattebox.dash-ll.min.js +3 -3
  3. package/dist/cdn/mattebox.dash.min.js +3 -3
  4. package/dist/cdn/mattebox.dual-drm.min.js +3 -3
  5. package/dist/cdn/mattebox.dual-ll.min.js +3 -3
  6. package/dist/cdn/mattebox.dual-ts-drm.min.js +3 -3
  7. package/dist/cdn/mattebox.dual-ts.min.js +3 -3
  8. package/dist/cdn/mattebox.dual.min.js +3 -3
  9. package/dist/cdn/mattebox.hls-drm.min.js +3 -3
  10. package/dist/cdn/mattebox.hls-ll.min.js +3 -3
  11. package/dist/cdn/mattebox.hls-ts-drm.min.js +3 -3
  12. package/dist/cdn/mattebox.hls-ts.min.js +3 -3
  13. package/dist/cdn/mattebox.hls.min.js +3 -3
  14. package/dist/cdn/mattebox.kernel.min.js +1 -1
  15. package/dist/cdn/mattebox.min.js +5 -5
  16. package/dist/containers/emsg.d.ts +16 -0
  17. package/dist/containers/emsg.d.ts.map +1 -1
  18. package/dist/containers/emsg.js +31 -1
  19. package/dist/containers/emsg.js.map +1 -1
  20. package/dist/eme/index.d.ts.map +1 -1
  21. package/dist/eme/index.js +2 -0
  22. package/dist/eme/index.js.map +1 -1
  23. package/dist/es2015/containers/emsg.js +28 -2
  24. package/dist/es2015/eme/index.js +8 -0
  25. package/dist/es2015/index.js +6 -4
  26. package/dist/es2015/kernel/context.js +6 -0
  27. package/dist/es2015/kernel/dry-run.js +2 -2
  28. package/dist/es2015/kernel/reducer.js +60 -7
  29. package/dist/es2015/protocols/dash-cmaf/parse.js +17 -2
  30. package/dist/es2015/protocols/hls-cmaf/parse.js +58 -2
  31. package/dist/es2015/stages/interstitials/breaks.js +341 -0
  32. package/dist/es2015/stages/interstitials/index.js +750 -0
  33. package/dist/es2015/stages/timed-metadata/index.js +10 -23
  34. package/dist/index.d.ts.map +1 -1
  35. package/dist/index.js +10 -1
  36. package/dist/index.js.map +1 -1
  37. package/dist/kernel/context.d.ts.map +1 -1
  38. package/dist/kernel/context.js +8 -0
  39. package/dist/kernel/context.js.map +1 -1
  40. package/dist/kernel/dry-run.d.ts +2 -0
  41. package/dist/kernel/dry-run.d.ts.map +1 -1
  42. package/dist/kernel/dry-run.js +1 -0
  43. package/dist/kernel/dry-run.js.map +1 -1
  44. package/dist/kernel/reducer.d.ts.map +1 -1
  45. package/dist/kernel/reducer.js +60 -4
  46. package/dist/kernel/reducer.js.map +1 -1
  47. package/dist/protocols/dash-cmaf/parse.d.ts.map +1 -1
  48. package/dist/protocols/dash-cmaf/parse.js +16 -0
  49. package/dist/protocols/dash-cmaf/parse.js.map +1 -1
  50. package/dist/protocols/hls-cmaf/parse.d.ts.map +1 -1
  51. package/dist/protocols/hls-cmaf/parse.js +75 -4
  52. package/dist/protocols/hls-cmaf/parse.js.map +1 -1
  53. package/dist/stages/interstitials/breaks.d.ts +113 -0
  54. package/dist/stages/interstitials/breaks.d.ts.map +1 -0
  55. package/dist/stages/interstitials/breaks.js +390 -0
  56. package/dist/stages/interstitials/breaks.js.map +1 -0
  57. package/dist/stages/interstitials/index.d.ts +57 -0
  58. package/dist/stages/interstitials/index.d.ts.map +1 -0
  59. package/dist/stages/interstitials/index.js +853 -0
  60. package/dist/stages/interstitials/index.js.map +1 -0
  61. package/dist/stages/timed-metadata/index.d.ts.map +1 -1
  62. package/dist/stages/timed-metadata/index.js +10 -27
  63. package/dist/stages/timed-metadata/index.js.map +1 -1
  64. package/dist/types/facade.d.ts +2 -19
  65. package/dist/types/facade.d.ts.map +1 -1
  66. package/dist/types/ir.d.ts +13 -1
  67. package/dist/types/ir.d.ts.map +1 -1
  68. package/dist/types/kernel.d.ts +11 -0
  69. package/dist/types/kernel.d.ts.map +1 -1
  70. package/dist/types/load.d.ts +28 -0
  71. package/dist/types/load.d.ts.map +1 -0
  72. package/dist/types/load.js +3 -0
  73. package/dist/types/load.js.map +1 -0
  74. package/dist/types/messages.d.ts +2 -0
  75. package/dist/types/messages.d.ts.map +1 -1
  76. package/dist/types/stage.d.ts +10 -0
  77. package/dist/types/stage.d.ts.map +1 -1
  78. package/package.json +1 -1
@@ -0,0 +1,853 @@
1
+ /**
2
+ * Plays breaks: HLS interstitials, DASH alternative MPD events, and the
3
+ * breaks a page schedules, on the one engine that plays the presentation.
4
+ * At a break the engine loads the asset in the presentation's place, and
5
+ * after it loads the presentation again at the resume point, each preloaded
6
+ * ahead so the switch fetches nothing. hls.js and Shaka play an asset this
7
+ * way when they cannot append it in place.
8
+ *
9
+ * SCTE-35 cue-outs are breaks with no assets: the presentation plays
10
+ * through them, and the stage reports their start, quartiles and end, so a
11
+ * player shows them as ads. A page fills one by scheduling assets under its
12
+ * id before it starts.
13
+ *
14
+ * The rules follow Appendix D of draft-pantos-hls-rfc8216bis as hls.js
15
+ * applies them: a pre-roll before the first frame, a post-roll at the end,
16
+ * a `once` break plays once, a seek past `noJump` breaks plays the last of
17
+ * them first, a `noSkip` break takes no seek, and a failed asset is skipped.
18
+ *
19
+ * The page reads `engine.interstitials` and listens to its events. The
20
+ * element's `currentTime` stays the browser's: during a break it is the
21
+ * asset's, and `primary` gives the presentation's.
22
+ */
23
+ import { placeEmsg } from '../../containers/emsg.js';
24
+ import { findBox, trackTimescales } from '../../containers/mp4-box/index.js';
25
+ import { bytesToBase64 } from '../../kernel/base64.js';
26
+ import { assetsOf, breaksOf, fromEvent } from './breaks.js';
27
+ /** Seconds ahead of a break at which its asset list is fetched and its first asset preloaded (hls.js's live look-ahead). */
28
+ const LOOKAHEAD = 10;
29
+ /** Segments preloaded per track before a switch: with 3, the reels page started in under 50 ms. */
30
+ const SEGMENTS = 3;
31
+ /** A jump of the playhead larger than this, outside a seek event, counts as a seek. */
32
+ const JUMP = 2;
33
+ const QUARTILES = [0.25, 0.5, 0.75];
34
+ /**
35
+ * Whether a span is a break: an ad or a promotion. The credits and the
36
+ * chapters a SCTE-35 section names are spans of the presentation, which a
37
+ * player shows as such, never as an ad.
38
+ */
39
+ function isBreak(entry) {
40
+ return entry.role === undefined || entry.role === 'ad' || entry.role === 'promo';
41
+ }
42
+ /** How long a break plays, when known: its assets, its limit, or the span it covers. */
43
+ function lengthOf(entry) {
44
+ const assets = entry.assets.reduce((sum, asset) => sum + (asset.duration ?? 0), 0);
45
+ const known = assets > 0 ? assets : entry.covers;
46
+ return entry.playoutLimit !== undefined ? Math.min(known, entry.playoutLimit) : known;
47
+ }
48
+ /**
49
+ * The elements of an alternative MPD event an emsg carries as its message
50
+ * data: the `InsertPresentation` or `ReplacePresentation` element, alone or
51
+ * inside an `Event`. Empty for any other body.
52
+ */
53
+ function presentationElements(data) {
54
+ const text = new TextDecoder().decode(data).trim();
55
+ if (!text.startsWith('<') || typeof DOMParser === 'undefined')
56
+ return [];
57
+ const root = new DOMParser().parseFromString(text, 'application/xml').documentElement;
58
+ if (root === null)
59
+ return [];
60
+ const found = /Presentation$|^AlternativeMPD$/.test(root.localName)
61
+ ? [root]
62
+ : Array.from(root.children).filter((e) => /Presentation$|^AlternativeMPD$/.test(e.localName));
63
+ return found.map((e) => ({
64
+ name: e.localName,
65
+ attributes: Object.fromEntries(Array.from(e.attributes, (a) => [a.localName, a.value])),
66
+ }));
67
+ }
68
+ export default function interstitials() {
69
+ /**
70
+ * What a detach leaves of the presentation: its URL, the breaks played,
71
+ * the asset lists fetched. A player that plays a progressive ad on the
72
+ * video detaches the engine, then loads the presentation again from where
73
+ * it stopped; that load takes them back, so no break plays twice.
74
+ */
75
+ let memory = null;
76
+ return {
77
+ name: 'interstitials',
78
+ provides: ['interstitials'],
79
+ install(ctx) {
80
+ const element = ctx.element;
81
+ const entries = new Map();
82
+ /** The breaks played, by id: a rebuild of the schedule keeps them. */
83
+ const played = new Set();
84
+ /** The assets each fetched asset list named, by break id. */
85
+ const resolved = new Map();
86
+ const page = new Map();
87
+ const told = new Set();
88
+ let primary = null;
89
+ let presentationId = null;
90
+ let duration = Number.NaN;
91
+ let live = false;
92
+ let own = false;
93
+ let playing = null;
94
+ /** A return in progress: the presentation's own seek to the resume point is no viewer seek. */
95
+ let settling = false;
96
+ let started = false;
97
+ let ended = false;
98
+ let lastTime = 0;
99
+ let seekFrom = null;
100
+ let timer = null;
101
+ let tracks = null;
102
+ let seq = 0;
103
+ /** A break waits for its asset list: no other starts meanwhile. */
104
+ let pending = false;
105
+ /** Whether the viewer wants playback: the element pauses at each load and at an asset's end. */
106
+ let wanted = !element.paused;
107
+ let switching = false;
108
+ /** The presentation and its post-rolls are over. */
109
+ let over = false;
110
+ /** A live return: the break's id and the seconds from its start where the broadcast resumes. */
111
+ let liveResume = null;
112
+ /** Breaks the media carries in emsg, by id. */
113
+ const inband = new Map();
114
+ const timescales = new Map();
115
+ const sorted = () => [...entries.values()].sort((a, b) => a.break.start - b.break.start);
116
+ const emit = (event, entry, extra = {}) => ctx.emit(`interstitials:${event}`, { id: entry.break.id, break: entry.break, ...extra });
117
+ function reset() {
118
+ if (playing?.limit != null)
119
+ clearTimeout(playing.limit);
120
+ entries.clear();
121
+ played.clear();
122
+ resolved.clear();
123
+ page.clear();
124
+ told.clear();
125
+ playing = null;
126
+ presentationId = null;
127
+ started = false;
128
+ ended = false;
129
+ over = false;
130
+ liveResume = null;
131
+ inband.clear();
132
+ timescales.clear();
133
+ settling = false;
134
+ lastTime = 0;
135
+ tracks = null;
136
+ }
137
+ /**
138
+ * The segment boundaries of the presentation's video, or its audio,
139
+ * for X-SNAP. HLS only, where the segments are a list.
140
+ */
141
+ function edges(presentation) {
142
+ const active = ctx.getState().tracks.active;
143
+ const id = active.get('video') ?? active.get('audio');
144
+ for (const period of presentation?.periods ?? []) {
145
+ for (const track of period.tracks) {
146
+ if (track.id !== id)
147
+ continue;
148
+ const segments = track.renditions[0]?.segments;
149
+ if (!Array.isArray(segments))
150
+ return [];
151
+ return segments.map((s) => s.start);
152
+ }
153
+ }
154
+ return [];
155
+ }
156
+ /** Where a break starts: at the segment boundary before it with X-SNAP=OUT. */
157
+ function startOf(entry) {
158
+ if (entry.snap?.out !== true)
159
+ return entry.start;
160
+ const before = edges(ctx.getState().presentation).filter((t) => t <= entry.start + 0.001);
161
+ return before.length > 0 ? before[before.length - 1] : entry.start;
162
+ }
163
+ /** Where the presentation resumes: at the segment boundary after it with X-SNAP=IN. */
164
+ function resumeOf(entry, at) {
165
+ if (entry.snap?.in !== true)
166
+ return at;
167
+ return edges(ctx.getState().presentation).find((t) => t >= at - 0.001) ?? at;
168
+ }
169
+ /** Rebuilds the schedule from the presentation. */
170
+ function refresh() {
171
+ if (playing !== null || primary === null)
172
+ return;
173
+ const presentation = ctx.getState().presentation;
174
+ if (presentation === null)
175
+ return;
176
+ presentationId = presentation.id;
177
+ live = presentation.isLive;
178
+ if (presentation.duration !== undefined)
179
+ duration = presentation.duration;
180
+ const fresh = [
181
+ ...breaksOf(presentation, primary.url),
182
+ ...inband.values(),
183
+ ...page.values(),
184
+ ];
185
+ let changed = fresh.length !== entries.size;
186
+ const ids = new Set();
187
+ for (const next of fresh) {
188
+ ids.add(next.id);
189
+ const known = entries.get(next.id);
190
+ // A page break under an opportunity's id fills it.
191
+ const filled = page.get(next.id);
192
+ const signalled = filled !== undefined && next.source === 'scte35' ? filled : next;
193
+ // An asset list already fetched keeps its assets.
194
+ const assets = resolved.get(next.id);
195
+ const value = assets !== undefined &&
196
+ signalled.assets.length === 0 &&
197
+ signalled.assetList !== undefined
198
+ ? { ...signalled, assets }
199
+ : signalled;
200
+ if (known === undefined) {
201
+ entries.set(next.id, { break: value });
202
+ changed = true;
203
+ }
204
+ else if (JSON.stringify(known.break) !== JSON.stringify(value)) {
205
+ known.break = value;
206
+ changed = true;
207
+ }
208
+ }
209
+ for (const id of [...entries.keys()])
210
+ if (!ids.has(id))
211
+ entries.delete(id);
212
+ if (changed)
213
+ ctx.emit('interstitials:changed', { breaks: api.breaks });
214
+ for (const entry of entries.values()) {
215
+ if (entry.break.source === 'scte35' &&
216
+ isBreak(entry.break) &&
217
+ !told.has(entry.break.id)) {
218
+ told.add(entry.break.id);
219
+ emit('opportunity', entry, { duration: entry.break.covers });
220
+ }
221
+ }
222
+ seekLive();
223
+ // A pre-roll plays before the first frame, from wherever the load starts.
224
+ if (!started) {
225
+ const pre = sorted().find((e) => e.break.cue === 'pre' && !played.has(e.break.id));
226
+ if (pre !== undefined)
227
+ void begin(pre, primary.start);
228
+ }
229
+ }
230
+ /**
231
+ * After a live break, the broadcast resumes where the break said: the
232
+ * same break in the reloaded presentation gives its start on the new
233
+ * timeline, since an HLS live reload restarts the presentation clock.
234
+ * Outside the window, the live edge stays.
235
+ */
236
+ function seekLive() {
237
+ const target = liveResume;
238
+ const window = ctx.getState().live;
239
+ if (target === null || window === null)
240
+ return;
241
+ const entry = entries.get(target.id);
242
+ if (entry === undefined)
243
+ return;
244
+ liveResume = null;
245
+ const at = entry.break.start + target.offset;
246
+ if (at < window.span.start || at > window.edge)
247
+ return;
248
+ settling = true;
249
+ lastTime = at;
250
+ element.currentTime = at;
251
+ }
252
+ /** Fetches the asset list of a break, once. A failure leaves it with no assets. */
253
+ function resolve(entry) {
254
+ const list = entry.break.assetList;
255
+ if (list === undefined || entry.break.assets.length > 0)
256
+ return Promise.resolve();
257
+ entry.resolving ??= ctx
258
+ .request(list, { method: 'GET' })
259
+ .then(async (response) => {
260
+ if (!response.ok)
261
+ throw new Error(`HTTP ${response.status}`);
262
+ const assets = assetsOf(await response.text(), response.url || list);
263
+ resolved.set(entry.break.id, assets);
264
+ entry.break = { ...entry.break, assets };
265
+ ctx.emit('interstitials:changed', { breaks: api.breaks });
266
+ })
267
+ .catch((error) => {
268
+ ctx.emit('interstitials:warning', {
269
+ id: entry.break.id,
270
+ url: list,
271
+ reason: `asset list: ${String(error.message ?? error)}`,
272
+ });
273
+ });
274
+ return entry.resolving;
275
+ }
276
+ /** Loads in the presentation's place, playing on when the viewer was playing. */
277
+ function load(url, options) {
278
+ // Read before the load: the element pauses when its source changes.
279
+ const resume = wanted || (!element.paused && !element.ended);
280
+ own = true;
281
+ switching = true;
282
+ ctx.load(url, options);
283
+ own = false;
284
+ if (resume)
285
+ keepPlaying();
286
+ }
287
+ function preload(url, options) {
288
+ ctx.preload(url, { ...options, segments: SEGMENTS }).catch(() => {
289
+ // The load reports what fails; a preload only saves time.
290
+ });
291
+ }
292
+ /** Plays the new source once it can. */
293
+ function keepPlaying() {
294
+ wanted = true;
295
+ const play = () => {
296
+ void element.play()?.catch(() => { });
297
+ };
298
+ element.addEventListener('canplay', play, { once: true });
299
+ play();
300
+ }
301
+ async function begin(entry, resume, at = element.currentTime, ending = false) {
302
+ if (playing !== null || pending)
303
+ return;
304
+ played.add(entry.break.id);
305
+ pending = true;
306
+ await resolve(entry);
307
+ pending = false;
308
+ if (entry.break.assets.length === 0 || primary === null || playing !== null)
309
+ return;
310
+ const active = ctx.getState().tracks.active;
311
+ tracks = new Map([...active].filter(([type]) => type === 'audio' || type === 'text'));
312
+ playing = {
313
+ entry,
314
+ asset: -1,
315
+ resume: ending ? resume : resumeOf(entry.break, resume),
316
+ ending,
317
+ at,
318
+ quartiles: 0,
319
+ last: 0,
320
+ limit: null,
321
+ };
322
+ if (entry.break.playoutLimit !== undefined) {
323
+ const current = playing;
324
+ current.limit = setTimeout(() => {
325
+ if (playing === current)
326
+ finish();
327
+ }, entry.break.playoutLimit * 1000);
328
+ }
329
+ emit('break-start', entry);
330
+ next();
331
+ }
332
+ /** The next asset of the break, or the return to the presentation. */
333
+ function next() {
334
+ const current = playing;
335
+ if (current === null)
336
+ return;
337
+ if (current.asset >= 0) {
338
+ emit('asset-end', current.entry, { asset: current.asset });
339
+ }
340
+ current.asset += 1;
341
+ current.quartiles = 0;
342
+ current.last = 0;
343
+ const asset = current.entry.break.assets[current.asset];
344
+ if (asset === undefined) {
345
+ finish();
346
+ return;
347
+ }
348
+ load(asset.url, asset.mimeType !== undefined ? { mimeType: asset.mimeType } : {});
349
+ emit('asset-start', current.entry, { asset: current.asset, url: asset.url });
350
+ // Whatever comes after this asset starts without a request.
351
+ const after = current.entry.break.assets[current.asset + 1];
352
+ if (after !== undefined)
353
+ preload(after.url, after.mimeType !== undefined ? { mimeType: after.mimeType } : {});
354
+ else if (primary !== null)
355
+ preload(primary.url, returnOptions(current.resume));
356
+ }
357
+ function returnOptions(resume) {
358
+ return {
359
+ ...(primary?.mimeType !== undefined ? { mimeType: primary.mimeType } : {}),
360
+ // Live returns to the edge, where the break replaced the broadcast.
361
+ ...(live ? {} : { start: resume }),
362
+ };
363
+ }
364
+ function finish() {
365
+ const current = playing;
366
+ if (current === null || primary === null)
367
+ return;
368
+ if (current.limit !== null)
369
+ clearTimeout(current.limit);
370
+ if (current.asset >= 0 && current.asset < current.entry.break.assets.length) {
371
+ emit('asset-end', current.entry, { asset: current.asset });
372
+ }
373
+ playing = null;
374
+ emit('break-end', current.entry, { resume: current.resume });
375
+ settling = true;
376
+ lastTime = current.resume;
377
+ if (current.ending) {
378
+ // Back on the presentation's last frame, paused: it is over.
379
+ wanted = false;
380
+ load(primary.url, { ...returnOptions(current.resume), start: current.resume });
381
+ over = true;
382
+ ctx.emit('interstitials:ended', {});
383
+ return;
384
+ }
385
+ if (live) {
386
+ liveResume = {
387
+ id: current.entry.break.id,
388
+ offset: current.resume - current.entry.break.start,
389
+ };
390
+ }
391
+ load(primary.url, returnOptions(current.resume));
392
+ }
393
+ /** The last unplayed `noJump` break a seek from one time to another passes. */
394
+ function jumped(from, to) {
395
+ return sorted()
396
+ .filter((e) => e.break.noJump &&
397
+ !played.has(e.break.id) &&
398
+ e.break.cue === undefined &&
399
+ e.break.assets.length + (e.break.assetList !== undefined ? 1 : 0) > 0 &&
400
+ e.break.start > from &&
401
+ e.break.start <= to)
402
+ .pop();
403
+ }
404
+ /** Follows the presentation's playhead: starts what it reaches, preloads what comes. */
405
+ function follow() {
406
+ if (playing !== null) {
407
+ followAsset(playing);
408
+ return;
409
+ }
410
+ if (primary === null || settling)
411
+ return;
412
+ const presentation = ctx.getState().presentation;
413
+ if (presentation === null || presentation.id !== presentationId) {
414
+ refresh();
415
+ }
416
+ const time = element.currentTime;
417
+ const from = seekFrom ?? lastTime;
418
+ const seeked = seekFrom !== null || Math.abs(time - lastTime) > JUMP;
419
+ seekFrom = null;
420
+ if (seeked) {
421
+ // A seek back from the end: the presentation goes on, and so will its post-rolls.
422
+ if (time < primaryHead.duration - 1) {
423
+ ended = false;
424
+ over = false;
425
+ }
426
+ // A seek back makes the breaks behind the new time playable again, unless once.
427
+ for (const entry of entries.values()) {
428
+ if (!entry.break.once && entry.break.start > time)
429
+ played.delete(entry.break.id);
430
+ }
431
+ const passed = time > from ? jumped(from, time) : undefined;
432
+ if (passed !== undefined) {
433
+ lastTime = time;
434
+ void begin(passed, time, passed.break.start);
435
+ return;
436
+ }
437
+ }
438
+ for (const entry of sorted()) {
439
+ const b = entry.break;
440
+ if (b.cue !== undefined)
441
+ continue;
442
+ if (b.assets.length === 0 && b.assetList === undefined) {
443
+ if (isBreak(b))
444
+ stitched(entry, time);
445
+ continue;
446
+ }
447
+ const start = startOf(b);
448
+ const ahead = start - time;
449
+ if (ahead > 0 && ahead <= Math.max(LOOKAHEAD, b.resolveAhead ?? 0) && !entry.preloaded) {
450
+ entry.preloaded = true;
451
+ void resolve(entry).then(() => {
452
+ const first = entry.break.assets[0];
453
+ if (first !== undefined)
454
+ preload(first.url, first.mimeType !== undefined ? { mimeType: first.mimeType } : {});
455
+ });
456
+ }
457
+ // Playback crossed the start, or a seek landed inside a span the break covers.
458
+ const crossed = !seeked && from < start + 0.001 && time >= start;
459
+ const landed = seeked && b.covers > 0 && time >= start && time < b.start + b.covers;
460
+ if (!played.has(b.id) && (crossed || landed)) {
461
+ lastTime = time;
462
+ void begin(entry, b.start + b.resumeOffset, start);
463
+ return;
464
+ }
465
+ }
466
+ lastTime = time;
467
+ wake(time);
468
+ }
469
+ /** A break the presentation plays itself: report it as the playhead crosses it. */
470
+ function stitched(entry, time) {
471
+ const b = entry.break;
472
+ const inside = time >= b.start && time < b.start + Math.max(b.covers, 0.001);
473
+ if (inside && !entry.inside) {
474
+ entry.inside = true;
475
+ entry.quartiles = 0;
476
+ emit('break-start', entry, { stitched: true });
477
+ }
478
+ if (inside && b.covers > 0) {
479
+ const fraction = (time - b.start) / b.covers;
480
+ while ((entry.quartiles ?? 0) < QUARTILES.length &&
481
+ fraction >= (QUARTILES[entry.quartiles ?? 0] ?? 1)) {
482
+ emit('progress', entry, { quartile: (entry.quartiles ?? 0) + 1 });
483
+ entry.quartiles = (entry.quartiles ?? 0) + 1;
484
+ }
485
+ }
486
+ if (!inside && entry.inside) {
487
+ entry.inside = false;
488
+ emit('break-end', entry, { stitched: true });
489
+ }
490
+ }
491
+ function followAsset(current) {
492
+ const time = element.currentTime;
493
+ if (element.seeking && current.entry.break.noSkip) {
494
+ // A break that takes no seek goes back to where it was.
495
+ if (Math.abs(time - current.last) > 0.5)
496
+ element.currentTime = current.last;
497
+ return;
498
+ }
499
+ current.last = time;
500
+ const asset = current.entry.break.assets[current.asset];
501
+ const length = Number.isFinite(element.duration) ? element.duration : asset?.duration;
502
+ if (length !== undefined && length > 0) {
503
+ const fraction = time / length;
504
+ while (current.quartiles < QUARTILES.length &&
505
+ fraction >= (QUARTILES[current.quartiles] ?? 1)) {
506
+ current.quartiles += 1;
507
+ emit('progress', current.entry, { asset: current.asset, quartile: current.quartiles });
508
+ }
509
+ }
510
+ }
511
+ /** A timer to the next break start ahead, since `timeupdate` fires only every quarter second. */
512
+ function wake(time) {
513
+ if (timer !== null)
514
+ clearTimeout(timer);
515
+ timer = null;
516
+ if (element.paused)
517
+ return;
518
+ let at = Number.POSITIVE_INFINITY;
519
+ for (const entry of entries.values()) {
520
+ const b = entry.break;
521
+ for (const edge of [b.start - LOOKAHEAD, b.start, b.start + b.covers]) {
522
+ if (edge > time)
523
+ at = Math.min(at, edge);
524
+ }
525
+ }
526
+ if (!Number.isFinite(at))
527
+ return;
528
+ const rate = element.playbackRate > 0 ? element.playbackRate : 1;
529
+ timer = setTimeout(follow, ((at - time) / rate) * 1000 + 10);
530
+ }
531
+ const onLoading = ctx.on('lifecycle:loading', (payload) => {
532
+ if (own)
533
+ return;
534
+ // The page loaded another source: its breaks are the ones that count now.
535
+ const { url, mimeType, start } = payload;
536
+ reset();
537
+ primary = { url, ...(mimeType !== undefined ? { mimeType } : {}), start: start ?? 0 };
538
+ // A load from a position of the presentation that left goes on with it.
539
+ const kept = memory;
540
+ memory = null;
541
+ if (kept !== null && kept.url === url && start !== undefined) {
542
+ for (const id of kept.played)
543
+ played.add(id);
544
+ for (const [id, assets] of kept.resolved)
545
+ resolved.set(id, assets);
546
+ started = true;
547
+ }
548
+ });
549
+ /** After a return, the viewer's audio and subtitles again. */
550
+ function restoreTracks() {
551
+ if (tracks === null || settling || playing !== null)
552
+ return;
553
+ const state = ctx.getState();
554
+ if (state.presentation === null)
555
+ return;
556
+ const active = [...state.tracks.active.values()];
557
+ for (const trackId of tracks.values()) {
558
+ if (state.tracks.available.includes(trackId) && !active.includes(trackId)) {
559
+ ctx.dispatch({ type: 'SELECT_TRACK', trackId });
560
+ }
561
+ }
562
+ tracks = null;
563
+ }
564
+ const onTracks = ctx.on('tracks:changed', () => {
565
+ if (playing !== null)
566
+ return;
567
+ refresh();
568
+ restoreTracks();
569
+ });
570
+ // A media playlist brings its date ranges when it merges.
571
+ const onPresentation = ctx.on('presentation:changed', refresh);
572
+ const onError = ctx.on('error', (payload) => {
573
+ // An asset that fails is skipped; the break never stops the programme.
574
+ const current = playing;
575
+ if (current === null || payload?.fatal !== true)
576
+ return;
577
+ ctx.emit('interstitials:warning', {
578
+ id: current.entry.break.id,
579
+ url: current.entry.break.assets[current.asset]?.url,
580
+ reason: 'asset failed',
581
+ });
582
+ // After every listener of this error: a player reads `playing` to
583
+ // tell an asset's error from the presentation's.
584
+ queueMicrotask(() => {
585
+ if (playing === current)
586
+ next();
587
+ });
588
+ });
589
+ const onSeeking = () => {
590
+ if (playing === null && !settling)
591
+ seekFrom ??= lastTime;
592
+ follow();
593
+ };
594
+ /** The return landed: the presentation's own seek to the resume point is behind. */
595
+ function settle() {
596
+ settling = false;
597
+ lastTime = element.currentTime;
598
+ seekFrom = null;
599
+ restoreTracks();
600
+ }
601
+ const onSeeked = () => {
602
+ if (settling && playing === null) {
603
+ settle();
604
+ return;
605
+ }
606
+ follow();
607
+ };
608
+ const onPlaying = () => {
609
+ switching = false;
610
+ if (settling && playing === null)
611
+ settle();
612
+ if (playing === null)
613
+ started = true;
614
+ seekLive();
615
+ follow();
616
+ };
617
+ const onPlay = () => {
618
+ wanted = true;
619
+ follow();
620
+ };
621
+ const onPause = () => {
622
+ // A pause at a load or at the end of an asset is not the viewer's.
623
+ if (!switching && !element.ended)
624
+ wanted = false;
625
+ follow();
626
+ };
627
+ const onCanPlay = () => {
628
+ switching = false;
629
+ };
630
+ const onEnded = () => {
631
+ // An asset's end can arrive after the next load began.
632
+ if (!element.ended)
633
+ return;
634
+ if (playing !== null) {
635
+ next();
636
+ return;
637
+ }
638
+ if (ended || primary === null || settling)
639
+ return;
640
+ ended = true;
641
+ const post = sorted().find((e) => e.break.cue === 'post' && !played.has(e.break.id));
642
+ if (post !== undefined) {
643
+ void begin(post, primaryHead.duration, element.currentTime, true);
644
+ return;
645
+ }
646
+ over = true;
647
+ ctx.emit('interstitials:ended', {});
648
+ };
649
+ const onTime = () => follow();
650
+ element.addEventListener('timeupdate', onTime);
651
+ element.addEventListener('play', onPlay);
652
+ element.addEventListener('pause', onPause);
653
+ element.addEventListener('canplay', onCanPlay);
654
+ element.addEventListener('seeking', onSeeking);
655
+ element.addEventListener('seeked', onSeeked);
656
+ element.addEventListener('playing', onPlaying);
657
+ element.addEventListener('ended', onEnded);
658
+ const primaryHead = {
659
+ get currentTime() {
660
+ return playing !== null ? playing.at : element.currentTime;
661
+ },
662
+ get duration() {
663
+ return Number.isFinite(duration) ? duration : element.duration;
664
+ },
665
+ seek(time) {
666
+ if (playing === null) {
667
+ element.currentTime = time;
668
+ return;
669
+ }
670
+ if (playing.entry.break.noSkip)
671
+ return;
672
+ playing.resume = time;
673
+ finish();
674
+ },
675
+ };
676
+ /** The inserted breaks behind a presentation time, which add their length to it. */
677
+ const before = (time) => sorted()
678
+ .filter((e) => e.break.covers === 0 &&
679
+ e.break.cue !== 'post' &&
680
+ (e.break.start < time || (played.has(e.break.id) && e.break.start <= time)))
681
+ .reduce((sum, e) => sum + lengthOf(e.break), 0);
682
+ const api = {
683
+ get breaks() {
684
+ return sorted().map((e) => e.break);
685
+ },
686
+ get ended() {
687
+ if (over)
688
+ return true;
689
+ const due = sorted().some((e) => e.break.cue === 'post' && !played.has(e.break.id));
690
+ return element.ended && playing === null && !pending && !settling && !due;
691
+ },
692
+ get playing() {
693
+ return playing === null || playing.asset < 0
694
+ ? null
695
+ : { break: playing.entry.break, asset: playing.asset };
696
+ },
697
+ primary: primaryHead,
698
+ integrated: {
699
+ get currentTime() {
700
+ if (playing === null)
701
+ return element.currentTime + before(element.currentTime);
702
+ // Inside an inserted break, the time already spent in it.
703
+ const spent = playing.entry.break.assets
704
+ .slice(0, Math.max(0, playing.asset))
705
+ .reduce((sum, asset) => sum + (asset.duration ?? 0), 0);
706
+ return playing.at + before(playing.at - 0.001) + spent + element.currentTime;
707
+ },
708
+ get duration() {
709
+ const all = sorted()
710
+ .filter((e) => e.break.covers === 0)
711
+ .reduce((sum, e) => sum + lengthOf(e.break), 0);
712
+ return primaryHead.duration + all;
713
+ },
714
+ seek(time) {
715
+ let primaryTime = time;
716
+ for (const entry of sorted()) {
717
+ if (entry.break.covers > 0 || entry.break.start >= primaryTime)
718
+ continue;
719
+ primaryTime -= lengthOf(entry.break);
720
+ }
721
+ primaryHead.seek(Math.max(0, primaryTime));
722
+ },
723
+ },
724
+ schedule(entry) {
725
+ seq += 1;
726
+ const id = entry.id ?? `page-${seq}`;
727
+ const covers = entry.covers ?? 0;
728
+ const value = {
729
+ id,
730
+ source: 'page',
731
+ start: entry.cue === 'pre'
732
+ ? 0
733
+ : entry.cue === 'post'
734
+ ? Number.isFinite(duration)
735
+ ? duration
736
+ : entry.start
737
+ : entry.start,
738
+ ...(entry.cue !== undefined ? { cue: entry.cue } : {}),
739
+ once: entry.once ?? false,
740
+ assets: entry.assets,
741
+ covers,
742
+ resumeOffset: entry.resumeOffset ?? covers,
743
+ noSkip: entry.noSkip ?? false,
744
+ noJump: entry.noJump ?? false,
745
+ ...(entry.skipAfter !== undefined ? { skipAfter: entry.skipAfter } : {}),
746
+ attributes: {},
747
+ };
748
+ page.set(id, value);
749
+ const known = entries.get(id);
750
+ if (known !== undefined && playing?.entry !== known)
751
+ known.break = value;
752
+ else if (known === undefined)
753
+ entries.set(id, { break: value });
754
+ ctx.emit('interstitials:changed', { breaks: api.breaks });
755
+ // A pre-roll a page schedules once its ad server answered still plays
756
+ // when the presentation has just begun.
757
+ if (value.cue === 'pre' && primary !== null && playing === null) {
758
+ if (started && element.currentTime < 1)
759
+ void begin(entries.get(id), primary.start);
760
+ else if (!started)
761
+ refresh();
762
+ }
763
+ return value;
764
+ },
765
+ cancel(id) {
766
+ const known = entries.get(id);
767
+ if (known === undefined || playing?.entry === known)
768
+ return;
769
+ page.delete(id);
770
+ entries.delete(id);
771
+ ctx.emit('interstitials:changed', { breaks: api.breaks });
772
+ },
773
+ skip() {
774
+ const current = playing;
775
+ if (current === null)
776
+ return false;
777
+ // A break that takes no seek can still be skipped from `skipAfter`,
778
+ // as a skippable ad is.
779
+ const after = current.entry.break.skipAfter;
780
+ if (current.entry.break.noSkip && after === undefined)
781
+ return false;
782
+ if (after !== undefined && element.currentTime < after)
783
+ return false;
784
+ ctx.emit('interstitials:skipped', { id: current.entry.break.id, asset: current.asset });
785
+ next();
786
+ return true;
787
+ },
788
+ };
789
+ ctx.registerNamespace('interstitials', api);
790
+ // Breaks in the media: alternative MPD and SCTE-35 events in emsg
791
+ // (ISO/IEC 23009-1 §5.10.3.3), read beside the metadata stage, which
792
+ // lists them too. After trick-play's fit (150); the asset's are not the
793
+ // presentation's.
794
+ ctx.registerTransform({
795
+ name: 'interstitials-emsg',
796
+ order: 161,
797
+ transform(data, meta) {
798
+ if (playing !== null || primary === null)
799
+ return data;
800
+ if (meta.contentType !== 'video' && meta.contentType !== 'audio')
801
+ return data;
802
+ if (meta.isInit || findBox(data, 'moov') !== null) {
803
+ const scales = trackTimescales(data);
804
+ if (scales.size > 0)
805
+ timescales.set(meta.renditionId, scales);
806
+ }
807
+ let added = false;
808
+ for (const { box, start, end } of placeEmsg(data, meta.start, timescales.get(meta.renditionId))) {
809
+ const entry = fromEvent({
810
+ scheme: box.scheme,
811
+ ...(box.value !== '' ? { value: box.value } : {}),
812
+ id: String(box.id),
813
+ start,
814
+ ...(end !== null ? { duration: end - start } : {}),
815
+ data: bytesToBase64(box.data),
816
+ timescale: box.timescale,
817
+ elements: presentationElements(box.data),
818
+ }, primary.url);
819
+ if (entry === null || inband.has(entry.id))
820
+ continue;
821
+ inband.set(entry.id, entry);
822
+ added = true;
823
+ }
824
+ if (added)
825
+ refresh();
826
+ return data;
827
+ },
828
+ });
829
+ return () => {
830
+ if (primary !== null) {
831
+ memory = { url: primary.url, played: [...played], resolved: new Map(resolved) };
832
+ }
833
+ onLoading();
834
+ onTracks();
835
+ onPresentation();
836
+ onError();
837
+ if (timer !== null)
838
+ clearTimeout(timer);
839
+ if (playing?.limit != null)
840
+ clearTimeout(playing.limit);
841
+ element.removeEventListener('timeupdate', onTime);
842
+ element.removeEventListener('play', onPlay);
843
+ element.removeEventListener('pause', onPause);
844
+ element.removeEventListener('canplay', onCanPlay);
845
+ element.removeEventListener('seeking', onSeeking);
846
+ element.removeEventListener('seeked', onSeeked);
847
+ element.removeEventListener('playing', onPlaying);
848
+ element.removeEventListener('ended', onEnded);
849
+ };
850
+ },
851
+ };
852
+ }
853
+ //# sourceMappingURL=index.js.map