mattebox 0.5.0 → 0.6.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 (163) hide show
  1. package/dist/cdn/mattebox.dash-drm.min.js +3 -3
  2. package/dist/cdn/mattebox.dash.min.js +3 -3
  3. package/dist/cdn/mattebox.dual-drm.min.js +3 -3
  4. package/dist/cdn/mattebox.dual-ts-drm.min.js +3 -3
  5. package/dist/cdn/mattebox.dual-ts.min.js +3 -3
  6. package/dist/cdn/mattebox.dual.min.js +3 -3
  7. package/dist/cdn/mattebox.hls-drm.min.js +3 -3
  8. package/dist/cdn/mattebox.hls-ts-drm.min.js +3 -3
  9. package/dist/cdn/mattebox.hls-ts.min.js +3 -3
  10. package/dist/cdn/mattebox.hls.min.js +3 -3
  11. package/dist/cdn/mattebox.kernel.min.js +1 -1
  12. package/dist/cdn/mattebox.min.js +4 -4
  13. package/dist/containers/mp4-box/index.d.ts +9 -7
  14. package/dist/containers/mp4-box/index.d.ts.map +1 -1
  15. package/dist/containers/mp4-box/index.js +20 -28
  16. package/dist/containers/mp4-box/index.js.map +1 -1
  17. package/dist/containers/packed-audio/index.d.ts.map +1 -1
  18. package/dist/containers/packed-audio/index.js +5 -1
  19. package/dist/containers/packed-audio/index.js.map +1 -1
  20. package/dist/containers/ts-transmux/index.d.ts.map +1 -1
  21. package/dist/containers/ts-transmux/index.js +2 -1
  22. package/dist/containers/ts-transmux/index.js.map +1 -1
  23. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/asyncToGenerator.js +1 -1
  24. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/defineProperty.js +1 -1
  25. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/objectSpread2.js +1 -1
  26. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/objectWithoutProperties.js +1 -1
  27. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/objectWithoutPropertiesLoose.js +1 -1
  28. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/toPrimitive.js +1 -1
  29. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/toPropertyKey.js +1 -1
  30. package/dist/es2015/_virtual/{_@oxc-project_runtime@0.149.0 → _@oxc-project_runtime@0.150.0}/helpers/esm/typeof.js +1 -1
  31. package/dist/es2015/containers/id3.js +1 -1
  32. package/dist/es2015/containers/mp4-box/index.js +19 -22
  33. package/dist/es2015/containers/packed-audio/index.js +2 -5
  34. package/dist/es2015/containers/ts-transmux/h264.js +1 -1
  35. package/dist/es2015/containers/ts-transmux/index.js +3 -6
  36. package/dist/es2015/index.js +40 -27
  37. package/dist/es2015/kernel/append-queue.js +1 -1
  38. package/dist/es2015/kernel/context.js +7 -0
  39. package/dist/es2015/kernel/loader.js +5 -4
  40. package/dist/es2015/kernel/mse.js +48 -74
  41. package/dist/es2015/kernel/prepare.js +77 -0
  42. package/dist/es2015/kernel/reducer.js +284 -73
  43. package/dist/es2015/kernel/refresh.js +35 -0
  44. package/dist/es2015/kernel/rendition-select.js +62 -2
  45. package/dist/es2015/kernel/scheduler.js +23 -5
  46. package/dist/es2015/kernel/timeline.js +22 -1
  47. package/dist/es2015/kernel/trace.js +1 -1
  48. package/dist/es2015/kernel/transport.js +4 -4
  49. package/dist/es2015/presets/define.js +2 -2
  50. package/dist/es2015/presets/tiers.js +7 -6
  51. package/dist/es2015/protocols/dash-cmaf/index.js +136 -55
  52. package/dist/es2015/protocols/dash-cmaf/parse.js +2 -10
  53. package/dist/es2015/protocols/dash-live/index.js +88 -16
  54. package/dist/es2015/protocols/hls-cmaf/index.js +119 -71
  55. package/dist/es2015/protocols/hls-cmaf/parse.js +35 -25
  56. package/dist/es2015/protocols/hls-cmaf/unavailable.js +42 -0
  57. package/dist/es2015/protocols/hls-live/index.js +221 -78
  58. package/dist/es2015/stages/abr/index.js +1 -1
  59. package/dist/es2015/stages/abr-persist/index.js +1 -1
  60. package/dist/es2015/stages/aes-128/index.js +1 -1
  61. package/dist/es2015/stages/alt-audio/index.js +1 -1
  62. package/dist/es2015/stages/cmaf-timing/index.js +24 -39
  63. package/dist/es2015/stages/cmcd/index.js +15 -2
  64. package/dist/es2015/stages/content-steering/index.js +30 -3
  65. package/dist/es2015/stages/eme-core/index.js +2 -2
  66. package/dist/es2015/stages/eme-fairplay/index.js +1 -1
  67. package/dist/es2015/stages/recovery/index.js +1 -1
  68. package/dist/es2015/stages/text-cea608/decode.js +1 -1
  69. package/dist/es2015/stages/text-webvtt/parse.js +1 -1
  70. package/dist/es2015/stages/thumbnails/index.js +1 -1
  71. package/dist/index.d.ts.map +1 -1
  72. package/dist/index.js +37 -32
  73. package/dist/index.js.map +1 -1
  74. package/dist/kernel/context.d.ts +5 -1
  75. package/dist/kernel/context.d.ts.map +1 -1
  76. package/dist/kernel/context.js +10 -0
  77. package/dist/kernel/context.js.map +1 -1
  78. package/dist/kernel/loader.d.ts.map +1 -1
  79. package/dist/kernel/loader.js +5 -7
  80. package/dist/kernel/loader.js.map +1 -1
  81. package/dist/kernel/mse.d.ts +6 -10
  82. package/dist/kernel/mse.d.ts.map +1 -1
  83. package/dist/kernel/mse.js +45 -76
  84. package/dist/kernel/mse.js.map +1 -1
  85. package/dist/kernel/prepare.d.ts +28 -0
  86. package/dist/kernel/prepare.d.ts.map +1 -0
  87. package/dist/kernel/prepare.js +89 -0
  88. package/dist/kernel/prepare.js.map +1 -0
  89. package/dist/kernel/reducer.d.ts +15 -0
  90. package/dist/kernel/reducer.d.ts.map +1 -1
  91. package/dist/kernel/reducer.js +399 -88
  92. package/dist/kernel/reducer.js.map +1 -1
  93. package/dist/kernel/refresh.d.ts +14 -0
  94. package/dist/kernel/refresh.d.ts.map +1 -0
  95. package/dist/kernel/refresh.js +50 -0
  96. package/dist/kernel/refresh.js.map +1 -0
  97. package/dist/kernel/rendition-select.d.ts +19 -1
  98. package/dist/kernel/rendition-select.d.ts.map +1 -1
  99. package/dist/kernel/rendition-select.js +69 -0
  100. package/dist/kernel/rendition-select.js.map +1 -1
  101. package/dist/kernel/scheduler.d.ts +18 -3
  102. package/dist/kernel/scheduler.d.ts.map +1 -1
  103. package/dist/kernel/scheduler.js +32 -7
  104. package/dist/kernel/scheduler.js.map +1 -1
  105. package/dist/kernel/timeline.d.ts +18 -6
  106. package/dist/kernel/timeline.d.ts.map +1 -1
  107. package/dist/kernel/timeline.js +19 -5
  108. package/dist/kernel/timeline.js.map +1 -1
  109. package/dist/kernel/transport.d.ts.map +1 -1
  110. package/dist/kernel/transport.js +1 -0
  111. package/dist/kernel/transport.js.map +1 -1
  112. package/dist/presets/tiers.d.ts +7 -6
  113. package/dist/presets/tiers.d.ts.map +1 -1
  114. package/dist/presets/tiers.js +7 -6
  115. package/dist/presets/tiers.js.map +1 -1
  116. package/dist/protocols/dash-cmaf/index.d.ts +2 -2
  117. package/dist/protocols/dash-cmaf/index.d.ts.map +1 -1
  118. package/dist/protocols/dash-cmaf/index.js +166 -55
  119. package/dist/protocols/dash-cmaf/index.js.map +1 -1
  120. package/dist/protocols/dash-live/index.d.ts.map +1 -1
  121. package/dist/protocols/dash-live/index.js +83 -11
  122. package/dist/protocols/dash-live/index.js.map +1 -1
  123. package/dist/protocols/hls-cmaf/index.d.ts +3 -2
  124. package/dist/protocols/hls-cmaf/index.d.ts.map +1 -1
  125. package/dist/protocols/hls-cmaf/index.js +140 -82
  126. package/dist/protocols/hls-cmaf/index.js.map +1 -1
  127. package/dist/protocols/hls-cmaf/parse.d.ts +9 -5
  128. package/dist/protocols/hls-cmaf/parse.d.ts.map +1 -1
  129. package/dist/protocols/hls-cmaf/parse.js +50 -47
  130. package/dist/protocols/hls-cmaf/parse.js.map +1 -1
  131. package/dist/protocols/hls-cmaf/unavailable.d.ts +17 -0
  132. package/dist/protocols/hls-cmaf/unavailable.d.ts.map +1 -0
  133. package/dist/protocols/hls-cmaf/unavailable.js +36 -0
  134. package/dist/protocols/hls-cmaf/unavailable.js.map +1 -0
  135. package/dist/protocols/hls-live/index.d.ts +17 -0
  136. package/dist/protocols/hls-live/index.d.ts.map +1 -1
  137. package/dist/protocols/hls-live/index.js +239 -76
  138. package/dist/protocols/hls-live/index.js.map +1 -1
  139. package/dist/stages/aes-128/index.js +2 -2
  140. package/dist/stages/aes-128/index.js.map +1 -1
  141. package/dist/stages/alt-audio/index.d.ts.map +1 -1
  142. package/dist/stages/alt-audio/index.js +5 -3
  143. package/dist/stages/alt-audio/index.js.map +1 -1
  144. package/dist/stages/cmaf-timing/index.d.ts.map +1 -1
  145. package/dist/stages/cmaf-timing/index.js +33 -42
  146. package/dist/stages/cmaf-timing/index.js.map +1 -1
  147. package/dist/stages/cmcd/index.d.ts.map +1 -1
  148. package/dist/stages/cmcd/index.js +15 -3
  149. package/dist/stages/cmcd/index.js.map +1 -1
  150. package/dist/stages/content-steering/index.d.ts.map +1 -1
  151. package/dist/stages/content-steering/index.js +23 -1
  152. package/dist/stages/content-steering/index.js.map +1 -1
  153. package/dist/types/facade.d.ts +12 -0
  154. package/dist/types/facade.d.ts.map +1 -1
  155. package/dist/types/kernel.d.ts +54 -15
  156. package/dist/types/kernel.d.ts.map +1 -1
  157. package/dist/types/kernel.js +2 -1
  158. package/dist/types/kernel.js.map +1 -1
  159. package/dist/types/messages.d.ts +58 -10
  160. package/dist/types/messages.d.ts.map +1 -1
  161. package/dist/types/stage.d.ts +18 -0
  162. package/dist/types/stage.d.ts.map +1 -1
  163. package/package.json +1 -1
@@ -1,8 +1,10 @@
1
+ import { APPENDED_MEMORY } from '../types/kernel.js';
1
2
  import { normalizeMimeType } from './mime.js';
2
- import { canSwitchTo, codecFamily, createArbiter, planPinApply } from './rendition-select.js';
3
+ import { applyRefresh } from './refresh.js';
4
+ import { canSwitchTo, codecFamily, createArbiter, planPinApply, withDeadGroups, } from './rendition-select.js';
3
5
  import { bufferedEndFrom, schedule } from './scheduler.js';
4
6
  import { sbIdFor } from './sinks/mse-sink.js';
5
- import { segmentAtTime } from './timeline.js';
7
+ import { reconciledOffset, segmentAtTime } from './timeline.js';
6
8
  import { DEFAULT_TRACE_CAPACITY } from './trace.js';
7
9
  /**
8
10
  * The default tuning. Every value is overridable through the `config`
@@ -29,7 +31,6 @@ export const DEFAULT_KERNEL_CONFIG = {
29
31
  // Long enough that a recovery stage's zero-delay commands apply first,
30
32
  // short enough that a retry without recovery still feels prompt.
31
33
  baseRetryDelayMs: 400,
32
- mediaTimeNormalized: false,
33
34
  };
34
35
  export function resolveConfig(config) {
35
36
  return { ...DEFAULT_KERNEL_CONFIG, ...config };
@@ -39,7 +40,7 @@ export function initialState(config) {
39
40
  return {
40
41
  lifecycle: { phase: 'idle' },
41
42
  presentation: null,
42
- timeline: { periodOffsets: new Map(), discontinuitySeq: 0 },
43
+ timeline: { periodOffsets: new Map(), discontinuitySeq: 0, reconciled: new Map() },
43
44
  buffers: new Map(),
44
45
  bufferErrors: new Map(),
45
46
  cues: new Map(),
@@ -53,6 +54,21 @@ export function initialState(config) {
53
54
  }
54
55
  /** Gap width treated as continuous when measuring buffered spans. */
55
56
  const GAP_TOLERANCE = 0.25;
57
+ /** Drops one buffer's held init. */
58
+ function withoutPendingInit(pending, sbId) {
59
+ if (pending === undefined || !pending.has(sbId))
60
+ return pending;
61
+ const next = new Map(pending);
62
+ next.delete(sbId);
63
+ return next.size === 0 ? undefined : next;
64
+ }
65
+ /** Writes held inits back into a scheduling slice; the field stays absent while empty. */
66
+ function withPendingInit(scheduling, pending) {
67
+ if (pending !== undefined && pending.size > 0)
68
+ return { ...scheduling, pendingInit: pending };
69
+ const { pendingInit: _pendingInit, ...rest } = scheduling;
70
+ return rest;
71
+ }
56
72
  /** The codecs part of an MSE type string ('video/mp4; codecs="avc1.42c00d"' -> 'avc1.42c00d'). */
57
73
  function bufferCodecString(type) {
58
74
  const match = /codecs="?([^"]+)"?/.exec(type);
@@ -147,6 +163,63 @@ function mergeCoverage(coverage, added) {
147
163
  merged.push(pending);
148
164
  return merged.sort((a, b) => a.start - b.start);
149
165
  }
166
+ /**
167
+ * The spans `before` holds and `after` does not. Browsers round the ranges
168
+ * they report, so a loss narrower than the gap tolerance is that rounding.
169
+ */
170
+ function lostSpans(before, after) {
171
+ const held = [...after].sort((a, b) => a.start - b.start);
172
+ const lost = [];
173
+ for (const range of before) {
174
+ let cursor = range.start;
175
+ for (const kept of held) {
176
+ if (kept.end <= cursor)
177
+ continue;
178
+ if (kept.start >= range.end)
179
+ break;
180
+ if (kept.start - cursor >= GAP_TOLERANCE)
181
+ lost.push({ start: cursor, end: kept.start });
182
+ cursor = kept.end;
183
+ }
184
+ if (range.end - cursor >= GAP_TOLERANCE)
185
+ lost.push({ start: cursor, end: range.end });
186
+ }
187
+ return lost;
188
+ }
189
+ /** The buffers without what they remember receiving: one buffer, or all of them. */
190
+ function forgetAppended(buffers, only) {
191
+ const next = new Map(buffers);
192
+ for (const [sbId, buffer] of buffers) {
193
+ if (buffer.appended === undefined || (only !== undefined && sbId !== only))
194
+ continue;
195
+ const { appended: _appended, ...rest } = buffer;
196
+ next.set(sbId, rest);
197
+ }
198
+ return next;
199
+ }
200
+ /**
201
+ * The buffers after the flushes among `effects`. A flush is an unbounded
202
+ * remove, and it forgets every segment that ends past its start: the next
203
+ * append there starts a new run, so a segment that left nothing the first
204
+ * time can land whole the second time. Lost content cannot say this, a
205
+ * segment that left nothing has none to lose. A bounded remove is eviction
206
+ * and reports through its updateend.
207
+ */
208
+ function forgetFlushed(buffers, effects) {
209
+ let next = buffers;
210
+ for (const effect of effects) {
211
+ if (effect.kind !== 'remove' || effect.end !== Number.POSITIVE_INFINITY)
212
+ continue;
213
+ const buffer = next.get(effect.sbId);
214
+ if (buffer?.appended === undefined)
215
+ continue;
216
+ const appended = buffer.appended.filter((seg) => seg.end <= effect.start);
217
+ if (appended.length === buffer.appended.length)
218
+ continue;
219
+ next = new Map(next).set(effect.sbId, { ...buffer, appended });
220
+ }
221
+ return next;
222
+ }
150
223
  function findTrack(presentation, trackId) {
151
224
  if (presentation === null)
152
225
  return null;
@@ -285,6 +358,26 @@ function reduceCommand(state, msg, cfg, hooks) {
285
358
  [...aborts, ...clears, ...reset],
286
359
  ];
287
360
  }
361
+ case 'SUSPEND': {
362
+ if (state.lifecycle.phase !== 'ready') {
363
+ return reject(state, msg.type, 'not ready');
364
+ }
365
+ const [next, aborts] = abortInflight(state);
366
+ // The live span goes stale the moment reloads stop. Forgetting it
367
+ // gates scheduling until a live slice reports a fresh one on resume,
368
+ // and lets that report count as the first, so a live presentation
369
+ // rejoins at the edge the way a fresh load does.
370
+ return [{ ...next, lifecycle: { phase: 'suspended' }, live: null }, aborts];
371
+ }
372
+ case 'RESUME': {
373
+ if (state.lifecycle.phase !== 'suspended') {
374
+ return reject(state, msg.type, 'not suspended');
375
+ }
376
+ // VOD refills from the playhead at once. Live waits: scheduling
377
+ // declines a live presentation without a span, and the live slice
378
+ // reloads its playlists on this same command to bring one.
379
+ return driveScheduling({ ...state, lifecycle: { phase: 'ready' } }, hooks, cfg);
380
+ }
288
381
  case 'SEEK': {
289
382
  if (state.presentation === null) {
290
383
  return reject(state, msg.type, 'no source');
@@ -319,6 +412,12 @@ function reduceCommand(state, msg, cfg, hooks) {
319
412
  if (track === null) {
320
413
  return reject(state, msg.type, `unknown track: ${msg.trackId}`);
321
414
  }
415
+ // A track the browser cannot decode would fail its buffer.
416
+ const undecodableIds = state.quality.constraints.get(CODECS)?.excludeIds ?? [];
417
+ if (track.renditions.length > 0 &&
418
+ track.renditions.every((r) => undecodableIds.includes(r.id))) {
419
+ return reject(state, msg.type, `undecodable track: ${msg.trackId}`);
420
+ }
322
421
  const previous = state.tracks.active.get(track.contentType);
323
422
  const active = new Map(state.tracks.active);
324
423
  active.set(track.contentType, track.id);
@@ -517,6 +616,89 @@ function reduceCommand(state, msg, cfg, hooks) {
517
616
  }
518
617
  }
519
618
  }
619
+ /** The constraint source for renditions this browser cannot decode. */
620
+ const CODECS = 'codecs';
621
+ /**
622
+ * The renditions this browser cannot play: a declared codec it does not
623
+ * decode, and a video variant whose audio group it cannot decode at all.
624
+ * VHS drops these when the manifest loads; left in, ABR climbs onto one and
625
+ * its buffer fails to open or to append. A rendition that declares no
626
+ * codec counts as decodable.
627
+ */
628
+ function undecodable(presentation, decodable) {
629
+ const out = new Set();
630
+ for (const period of presentation.periods) {
631
+ for (const track of period.tracks) {
632
+ if (track.contentType !== 'video' && track.contentType !== 'audio')
633
+ continue;
634
+ for (const r of track.renditions) {
635
+ if (r.codecs !== null && !decodable(`${r.mimeType}; codecs="${r.codecs}"`))
636
+ out.add(r.id);
637
+ }
638
+ }
639
+ }
640
+ return withDeadGroups(presentation, out);
641
+ }
642
+ /**
643
+ * A presentation replaces the one held: a manifest landed, or a playlist
644
+ * merged into it. Activates default tracks and reports what changed.
645
+ */
646
+ function loadPresentation(state, presentation, undecodableIds = new Set()) {
647
+ const available = [];
648
+ for (const period of presentation.periods) {
649
+ for (const track of period.tracks)
650
+ available.push(track.id);
651
+ }
652
+ const inflight = new Map(state.scheduling.inflight);
653
+ for (const [token, request] of inflight) {
654
+ if (request.trackId === 'manifest')
655
+ inflight.delete(token);
656
+ }
657
+ const phase = state.lifecycle.phase === 'loading' ? 'ready' : state.lifecycle.phase;
658
+ // Default activation: the first video and audio track the browser can
659
+ // decode, so a manifest alone yields a playable composition without a
660
+ // SELECT_TRACK.
661
+ const active = new Map(state.tracks.active);
662
+ for (const period of presentation.periods) {
663
+ for (const track of period.tracks) {
664
+ if ((track.contentType === 'video' || track.contentType === 'audio') &&
665
+ !active.has(track.contentType) &&
666
+ track.renditions.some((r) => !undecodableIds.has(r.id))) {
667
+ active.set(track.contentType, track.id);
668
+ }
669
+ }
670
+ }
671
+ const loaded = {
672
+ ...state,
673
+ lifecycle: { phase },
674
+ presentation,
675
+ scheduling: { ...state.scheduling, inflight },
676
+ tracks: { active, available },
677
+ quality: bumped(state.quality),
678
+ };
679
+ // Every playlist merge lands here too; the track list only changed if
680
+ // the ids did.
681
+ const sameTracks = available.length === state.tracks.available.length &&
682
+ available.every((id, index) => id === state.tracks.available[index]);
683
+ const manifestEffects = sameTracks
684
+ ? []
685
+ : [{ kind: 'emit', event: 'tracks:changed', payload: { available } }];
686
+ // The manifest DRM route: emit every track's protection schemes so
687
+ // eme-core (if loaded) can open sessions. Serializable init data
688
+ // rides the event; nothing DRM-specific enters the reducer.
689
+ const schemes = presentation.periods.flatMap((period) => period.tracks.flatMap((track) => track.protection?.schemes ?? []));
690
+ if (schemes.length > 0) {
691
+ manifestEffects.push({
692
+ kind: 'emit',
693
+ event: 'presentation:protection',
694
+ payload: schemes,
695
+ });
696
+ }
697
+ if (!presentation.isLive && presentation.duration !== undefined) {
698
+ manifestEffects.push({ kind: 'setDuration', seconds: presentation.duration });
699
+ }
700
+ return [loaded, manifestEffects];
701
+ }
520
702
  function reduceFact(state, msg, cfg, hooks) {
521
703
  switch (msg.type) {
522
704
  case 'ELEMENT_ATTACHED':
@@ -525,65 +707,45 @@ function reduceFact(state, msg, cfg, hooks) {
525
707
  // Lifecycle detail owned by the mse module. Absorbed for the trace.
526
708
  return [state, []];
527
709
  case 'MANIFEST_LOADED': {
528
- const available = [];
529
- for (const period of msg.presentation.periods) {
530
- for (const track of period.tracks)
531
- available.push(track.id);
710
+ if (hooks.decodable === undefined)
711
+ return loadPresentation(state, msg.presentation);
712
+ const excluded = undecodable(msg.presentation, hooks.decodable);
713
+ const tracks = msg.presentation.periods.flatMap((period) => period.tracks);
714
+ const lead = ['video', 'audio'].find((c) => tracks.some((t) => t.contentType === c));
715
+ // Nothing to play: say so now, not after a buffer fails to open.
716
+ if (lead !== undefined &&
717
+ !tracks.some((t) => t.contentType === lead && t.renditions.some((r) => !excluded.has(r.id)))) {
718
+ const codecs = new Set(tracks.flatMap((t) => t.renditions.map((r) => r.codecs ?? '')));
719
+ codecs.delete('');
720
+ return failManifest(state, { category: 'media', code: 'MEDIA_CODEC_UNSUPPORTED', fatal: true, recoverable: false }, { codecs: [...codecs] });
532
721
  }
533
- const inflight = new Map(state.scheduling.inflight);
534
- for (const [token, request] of inflight) {
535
- if (request.trackId === 'manifest')
536
- inflight.delete(token);
537
- }
538
- const phase = state.lifecycle.phase === 'loading' ? 'ready' : state.lifecycle.phase;
539
- // Default activation: the first video and audio track, so a manifest
540
- // alone yields a playable composition without a SELECT_TRACK.
541
- const active = new Map(state.tracks.active);
542
- for (const period of msg.presentation.periods) {
543
- for (const track of period.tracks) {
544
- if ((track.contentType === 'video' || track.contentType === 'audio') &&
545
- !active.has(track.contentType)) {
546
- active.set(track.contentType, track.id);
547
- }
548
- }
549
- }
550
- const loaded = {
551
- ...state,
552
- lifecycle: { phase },
553
- presentation: msg.presentation,
554
- scheduling: { ...state.scheduling, inflight },
555
- tracks: { active, available },
556
- quality: bumped(state.quality),
557
- };
558
- // A live reload feeds a MANIFEST_LOADED per playlist; the track list
559
- // only changed if the ids did.
560
- const sameTracks = available.length === state.tracks.available.length &&
561
- available.every((id, index) => id === state.tracks.available[index]);
562
- const manifestEffects = sameTracks
563
- ? []
564
- : [{ kind: 'emit', event: 'tracks:changed', payload: { available } }];
565
- // The manifest DRM route: emit every track's protection schemes so
566
- // eme-core (if loaded) can open sessions. Serializable init data
567
- // rides the event; nothing DRM-specific enters the reducer.
568
- const schemes = msg.presentation.periods.flatMap((period) => period.tracks.flatMap((track) => track.protection?.schemes ?? []));
569
- if (schemes.length > 0) {
570
- manifestEffects.push({
571
- kind: 'emit',
572
- event: 'presentation:protection',
573
- payload: schemes,
574
- });
575
- }
576
- if (!msg.presentation.isLive && msg.presentation.duration !== undefined) {
577
- manifestEffects.push({ kind: 'setDuration', seconds: msg.presentation.duration });
578
- }
579
- return [loaded, manifestEffects];
722
+ const constraints = new Map(state.quality.constraints);
723
+ if (excluded.size > 0)
724
+ constraints.set(CODECS, { excludeIds: [...excluded] });
725
+ else
726
+ constraints.delete(CODECS);
727
+ return loadPresentation({ ...state, quality: { ...state.quality, constraints } }, msg.presentation, excluded);
580
728
  }
581
729
  case 'MANIFEST_FAILED':
582
730
  return failManifest(state, msg.error);
583
- case 'PLAYLIST_REFRESHED':
584
- // Merging a refreshed live playlist into the presentation belongs to
585
- // the protocol stages. Absorbed for the trace until they exist.
586
- return [state, []];
731
+ case 'PLAYLIST_REFRESHED': {
732
+ // Merged into the presentation held now, not a snapshot an adapter
733
+ // took earlier: another rendition may have merged in between.
734
+ const merged = state.presentation === null ? null : applyRefresh(state.presentation, msg);
735
+ if (merged === null)
736
+ return [state, []];
737
+ return loadPresentation(state, merged);
738
+ }
739
+ case 'MEDIA_ERROR': {
740
+ // The element gave up. An engine that already failed keeps its error.
741
+ if (state.lifecycle.phase === 'error')
742
+ return [state, []];
743
+ const [stopped, aborts] = abortInflight(state);
744
+ const [failed, report] = failManifest(stopped, { ...msg.error, fatal: true },
745
+ // The facade builds this context from the element's strings.
746
+ { context: msg.error.context });
747
+ return [failed, [...aborts, ...report]];
748
+ }
587
749
  case 'SEGMENT_LOADED': {
588
750
  let matched = null;
589
751
  if (msg.token !== undefined) {
@@ -619,6 +781,7 @@ function reduceFact(state, msg, cfg, hooks) {
619
781
  throughputFastEwma: ewma(state.stats.throughputFastEwma, sampleBps, cfg.ewmaFastAlpha),
620
782
  };
621
783
  let buffers = state.buffers;
784
+ let pendingInit = state.scheduling.pendingInit;
622
785
  let timeline = state.timeline;
623
786
  let quality = state.quality;
624
787
  let cues = state.cues;
@@ -687,6 +850,14 @@ function reduceFact(state, msg, cfg, hooks) {
687
850
  codecs: targetCodecs,
688
851
  });
689
852
  buffers = nextBuffers;
853
+ pendingInit = withoutPendingInit(pendingInit, matched.sbId);
854
+ }
855
+ else {
856
+ // The bytes beat the SOURCEBUFFER_CREATED fact: after a reload
857
+ // the media source has to reopen before the buffer exists. The
858
+ // controller holds the append until it does, so the init is
859
+ // recorded here and adopted on creation instead of refetched.
860
+ pendingInit = new Map(pendingInit ?? []).set(matched.sbId, matched.renditionId);
690
861
  }
691
862
  }
692
863
  // A media segment decodes only under its own rendition's init
@@ -702,7 +873,7 @@ function reduceFact(state, msg, cfg, hooks) {
702
873
  initFor !== matched.renditionId) {
703
874
  const next = {
704
875
  ...state,
705
- scheduling: { ...state.scheduling, inflight },
876
+ scheduling: withPendingInit({ ...state.scheduling, inflight }, pendingInit),
706
877
  stats,
707
878
  buffers,
708
879
  cues,
@@ -721,32 +892,67 @@ function reduceFact(state, msg, cfg, hooks) {
721
892
  ],
722
893
  ];
723
894
  }
724
- // The scheduler computed the epoch's offset at request time; apply
725
- // it ahead of the append when it differs from what the buffer has.
895
+ // The offset this append takes. The first media segment to land in
896
+ // an epoch settles it for every buffer: its presentation start minus
897
+ // the decode time the probe read from its bytes, or the manifest's
898
+ // prediction when nothing read one. Later segments of the epoch,
899
+ // on any buffer, apply the settled value, so audio and video keep
900
+ // the alignment their shared media clock gives them: one offset per
901
+ // timeline, as videojs-http-streaming takes it from its main loader.
726
902
  // Playlist discontinuities and period boundaries both land here.
727
- if (matched.timestampOffset !== undefined &&
728
- state.timeline.periodOffsets.get(matched.sbId) !== matched.timestampOffset) {
729
- effects.push({
730
- kind: 'setTimestampOffset',
731
- sbId: matched.sbId,
732
- offset: matched.timestampOffset,
733
- });
734
- const periodOffsets = new Map(state.timeline.periodOffsets);
735
- periodOffsets.set(matched.sbId, matched.timestampOffset);
736
- timeline = { ...state.timeline, periodOffsets };
903
+ let reconciled = state.timeline.reconciled;
904
+ let offset = matched.epoch === undefined ? undefined : reconciled.get(matched.epoch);
905
+ if (offset === undefined &&
906
+ matched.epoch !== undefined &&
907
+ matched.seq >= 0 &&
908
+ matched.segmentStart !== undefined) {
909
+ const settled = msg.mediaStart !== undefined
910
+ ? reconciledOffset(matched.segmentStart, msg.mediaStart)
911
+ : matched.timestampOffset;
912
+ if (settled !== undefined) {
913
+ offset = settled;
914
+ reconciled = new Map(reconciled).set(matched.epoch, settled);
915
+ }
737
916
  }
738
- effects.push({
739
- kind: 'append',
740
- sbId: matched.sbId,
741
- data: msg.bytes,
742
- ...(matched.segmentStart !== undefined ? { start: matched.segmentStart } : {}),
743
- ...(matched.renditionId !== undefined ? { renditionId: matched.renditionId } : {}),
744
- seq: matched.seq,
745
- });
917
+ if (offset === undefined)
918
+ offset = matched.timestampOffset;
919
+ let periodOffsets = state.timeline.periodOffsets;
920
+ if (offset !== undefined && periodOffsets.get(matched.sbId) !== offset) {
921
+ effects.push({ kind: 'setTimestampOffset', sbId: matched.sbId, offset });
922
+ periodOffsets = new Map(periodOffsets).set(matched.sbId, offset);
923
+ }
924
+ if (periodOffsets !== state.timeline.periodOffsets ||
925
+ reconciled !== state.timeline.reconciled) {
926
+ timeline = { ...state.timeline, periodOffsets, reconciled };
927
+ }
928
+ effects.push({ kind: 'append', sbId: matched.sbId, data: msg.bytes });
746
929
  const buffer = buffers.get(matched.sbId);
747
930
  if (buffer !== undefined) {
748
931
  const nextBuffers = new Map(buffers);
749
- nextBuffers.set(matched.sbId, { ...buffer, pendingAppends: buffer.pendingAppends + 1 });
932
+ // What the buffer receives, so the scheduler never asks for it
933
+ // twice. Media only, and with the span it lands at, so a removal
934
+ // there can forget it.
935
+ let appended = buffer.appended;
936
+ const { renditionId, seq, segmentStart } = matched;
937
+ if (seq >= 0 && renditionId !== undefined && segmentStart !== undefined) {
938
+ const entry = {
939
+ renditionId,
940
+ seq,
941
+ start: segmentStart,
942
+ end: segmentStart + (matched.segmentDuration ?? 0),
943
+ };
944
+ appended = [
945
+ ...(appended ?? [])
946
+ .filter((seg) => seg.seq !== seq || seg.renditionId !== renditionId)
947
+ .slice(1 - APPENDED_MEMORY),
948
+ entry,
949
+ ];
950
+ }
951
+ nextBuffers.set(matched.sbId, {
952
+ ...buffer,
953
+ pendingAppends: buffer.pendingAppends + 1,
954
+ ...(appended !== undefined ? { appended } : {}),
955
+ });
750
956
  buffers = nextBuffers;
751
957
  }
752
958
  if (matched.sbId === sbIdFor('video') &&
@@ -779,7 +985,7 @@ function reduceFact(state, msg, cfg, hooks) {
779
985
  timeline,
780
986
  quality,
781
987
  cues,
782
- scheduling: { ...state.scheduling, inflight },
988
+ scheduling: withPendingInit({ ...state.scheduling, inflight }, pendingInit),
783
989
  stats,
784
990
  },
785
991
  effects,
@@ -854,8 +1060,18 @@ function reduceFact(state, msg, cfg, hooks) {
854
1060
  }
855
1061
  case 'SOURCEBUFFER_CREATED': {
856
1062
  const buffers = new Map(state.buffers);
857
- buffers.set(msg.sbId, { codecs: msg.codecs, ranges: [], pendingAppends: 0 });
858
- return [{ ...state, buffers }, []];
1063
+ // An init that arrived before the buffer existed is held by the
1064
+ // controller and appended on creation, so the buffer opens already
1065
+ // initialized for that rendition.
1066
+ const held = state.scheduling.pendingInit?.get(msg.sbId);
1067
+ buffers.set(msg.sbId, {
1068
+ codecs: msg.codecs,
1069
+ ranges: [],
1070
+ pendingAppends: 0,
1071
+ ...(held !== undefined ? { initFor: held } : {}),
1072
+ });
1073
+ const scheduling = withPendingInit(state.scheduling, withoutPendingInit(state.scheduling.pendingInit, msg.sbId));
1074
+ return [{ ...state, buffers, scheduling }, []];
859
1075
  }
860
1076
  case 'SOURCEBUFFER_UPDATEEND': {
861
1077
  const buffer = state.buffers.get(msg.sbId);
@@ -863,10 +1079,23 @@ function reduceFact(state, msg, cfg, hooks) {
863
1079
  // The buffer was removed by a concurrent detach. Absorb and ignore.
864
1080
  return [state, []];
865
1081
  }
1082
+ // Content the buffer lost takes the memory of its segments with it.
1083
+ // Every removal reports here: a switch's flush, the evictor dropping
1084
+ // forward buffer under quota, the browser's own eviction during an
1085
+ // append. Those segments are gone and a fetch restores them, where a
1086
+ // segment that never left a usable range stays remembered.
1087
+ let appended = buffer.appended;
1088
+ if (appended !== undefined && msg.ranges !== undefined) {
1089
+ const lost = lostSpans(buffer.ranges, msg.ranges);
1090
+ if (lost.length > 0) {
1091
+ appended = appended.filter((seg) => !lost.some((span) => span.start <= seg.end && span.end >= seg.start));
1092
+ }
1093
+ }
866
1094
  const buffers = new Map(state.buffers);
867
1095
  buffers.set(msg.sbId, {
868
1096
  ...buffer,
869
1097
  ...(msg.ranges !== undefined ? { ranges: msg.ranges } : {}),
1098
+ ...(appended !== undefined ? { appended } : {}),
870
1099
  pendingAppends: Math.max(0, buffer.pendingAppends - 1),
871
1100
  });
872
1101
  // A successful append proves the buffer works: the breaker resets.
@@ -887,8 +1116,30 @@ function reduceFact(state, msg, cfg, hooks) {
887
1116
  const count = (state.bufferErrors.get(msg.sbId) ?? 0) + 1;
888
1117
  const bufferErrors = new Map(state.bufferErrors);
889
1118
  bufferErrors.set(msg.sbId, count);
1119
+ // The buffer never opened, so nothing holds its init any more: the
1120
+ // next decision fetches it again.
1121
+ const scheduling = withPendingInit(state.scheduling, withoutPendingInit(state.scheduling.pendingInit, msg.sbId));
1122
+ // The buffer did not keep what it was handed, or never got it: a
1123
+ // failed append, or a transform that threw before the append. The
1124
+ // parser also starts over (MSE append error algorithm, reset parser
1125
+ // state), so what the buffer received before says nothing about the
1126
+ // next append. The failed segment is fetched again, and the breaker
1127
+ // above counts it.
1128
+ let buffers = forgetAppended(state.buffers, msg.sbId);
890
1129
  const fatal = msg.error.fatal || count >= cfg.bufferErrorLimit;
891
1130
  const phase = fatal ? 'error' : state.lifecycle.phase;
1131
+ // A transform that threw never reached the buffer, so no updateend
1132
+ // reports for that append: this fact does. Without it the track waits
1133
+ // on the append and never schedules again. A parser error is followed
1134
+ // by its updateend (MSE append error algorithm), which reports.
1135
+ const neverAppended = msg.error.code === 'MEDIA_CONTAINER_INVALID';
1136
+ const waiting = buffers.get(msg.sbId);
1137
+ if (neverAppended && waiting !== undefined && waiting.pendingAppends > 0) {
1138
+ buffers = new Map(buffers).set(msg.sbId, {
1139
+ ...waiting,
1140
+ pendingAppends: waiting.pendingAppends - 1,
1141
+ });
1142
+ }
892
1143
  const effects = [
893
1144
  {
894
1145
  kind: 'emit',
@@ -903,6 +1154,17 @@ function reduceFact(state, msg, cfg, hooks) {
903
1154
  },
904
1155
  },
905
1156
  ];
1157
+ if (neverAppended && !fatal) {
1158
+ // Nothing else re-drives: the refetch waits the same backoff a
1159
+ // failed fetch does, so recovery can change the decision first.
1160
+ effects.push({
1161
+ kind: 'schedule',
1162
+ token: 'kernel:retry',
1163
+ delayMs: cfg.baseRetryDelayMs,
1164
+ // biome-ignore lint/suspicious/noThenProperty: `then` is the schedule effect's field name from the message taxonomy
1165
+ then: { type: 'TICK', token: 'kernel:retry' },
1166
+ });
1167
+ }
906
1168
  let inflight = state.scheduling.inflight;
907
1169
  if (fatal) {
908
1170
  // Stop the world for this buffer: whatever is in flight will only
@@ -919,9 +1181,10 @@ function reduceFact(state, msg, cfg, hooks) {
919
1181
  return [
920
1182
  {
921
1183
  ...state,
1184
+ buffers,
922
1185
  bufferErrors,
923
1186
  lifecycle: { phase },
924
- scheduling: { ...state.scheduling, inflight },
1187
+ scheduling: { ...scheduling, inflight },
925
1188
  },
926
1189
  effects,
927
1190
  ];
@@ -944,10 +1207,13 @@ function reduceFact(state, msg, cfg, hooks) {
944
1207
  case 'SEEKING': {
945
1208
  // Seeking out of the ended phase resumes an ordinary ready state.
946
1209
  const phase = state.lifecycle.phase === 'ended' ? 'ready' : state.lifecycle.phase;
1210
+ // A seek starts the decisions over: what the buffers last received
1211
+ // no longer says anything about what the playhead needs.
947
1212
  return [
948
1213
  {
949
1214
  ...state,
950
1215
  lifecycle: { phase },
1216
+ buffers: forgetAppended(state.buffers),
951
1217
  playback: { ...state.playback, currentTime: msg.to, seeking: true },
952
1218
  },
953
1219
  [],
@@ -1127,9 +1393,15 @@ function driveScheduling(state, hooks, cfg) {
1127
1393
  if (rendition.init !== undefined &&
1128
1394
  state.buffers.get(sbId)?.initFor !== rendition.id &&
1129
1395
  inflight.length === 0) {
1130
- initFetches.push({ trackId, sbId, rendition: rendition.id, init: rendition.init });
1396
+ // Unless its bytes already arrived and wait for the buffer to open.
1397
+ // Fetching them again is the wasted request, and a slow open would
1398
+ // repeat it until the scheduling breaker called it a loop.
1399
+ if (state.scheduling.pendingInit?.get(sbId) !== rendition.id) {
1400
+ initFetches.push({ trackId, sbId, rendition: rendition.id, init: rendition.init });
1401
+ }
1131
1402
  continue;
1132
1403
  }
1404
+ const appended = state.buffers.get(sbId)?.appended;
1133
1405
  tracks.push({
1134
1406
  trackId,
1135
1407
  period: found.period,
@@ -1137,6 +1409,7 @@ function driveScheduling(state, hooks, cfg) {
1137
1409
  ranges: state.buffers.get(sbId)?.ranges ?? [],
1138
1410
  sbId,
1139
1411
  inflight,
1412
+ ...(appended !== undefined ? { appended } : {}),
1140
1413
  });
1141
1414
  }
1142
1415
  // Cue pipelines schedule like media, minus everything SourceBuffer:
@@ -1163,13 +1436,23 @@ function driveScheduling(state, hooks, cfg) {
1163
1436
  inflight,
1164
1437
  });
1165
1438
  }
1439
+ // The lead buffer settles each epoch's offset: video when the
1440
+ // presentation has it, else audio. Its init and media requests count as
1441
+ // pending, so a companion track cannot settle the epoch from its own
1442
+ // bytes while the lead is still on its way there.
1443
+ const leadSbId = sbIdFor(state.tracks.active.has('video') ? 'video' : 'audio');
1444
+ const leadPending = initFetches.some((pending) => pending.sbId === leadSbId) ||
1445
+ [...state.scheduling.inflight.values()].some((request) => request.sbId === leadSbId);
1166
1446
  const result = schedule({
1167
1447
  currentTime: state.playback.currentTime,
1168
1448
  bufferGoal: state.scheduling.bufferGoal,
1169
1449
  tokenSeq: state.scheduling.tokenSeq + initFetches.length,
1170
1450
  tracks,
1171
1451
  liveWindow: state.presentation.isLive ? (state.live?.span ?? null) : null,
1172
- mediaTimeNormalized: cfg.mediaTimeNormalized,
1452
+ reconciles: hooks.timeProbe != null,
1453
+ leadSbId,
1454
+ reconciled: state.timeline.reconciled,
1455
+ leadPending,
1173
1456
  });
1174
1457
  // The scheduling breaker: an identical decision repeated past the limit
1175
1458
  // means appends report success but nothing ever progresses, and the
@@ -1278,6 +1561,8 @@ const COMMAND_TYPES = {
1278
1561
  DETACH: true,
1279
1562
  LOAD: true,
1280
1563
  UNLOAD: true,
1564
+ SUSPEND: true,
1565
+ RESUME: true,
1281
1566
  SEEK: true,
1282
1567
  SEEK_TO_LIVE_EDGE: true,
1283
1568
  DESELECT_TRACK: true,
@@ -1304,7 +1589,11 @@ export function createReducer(slices, config, hooks = {}) {
1304
1589
  const cfg = resolveConfig(config);
1305
1590
  const DRIVING_FACTS = new Set([
1306
1591
  'MANIFEST_LOADED',
1592
+ 'PLAYLIST_REFRESHED',
1307
1593
  'SEGMENT_LOADED',
1594
+ // A buffer that opens holding an init unblocks media scheduling, and
1595
+ // nothing else would drive it on a paused element.
1596
+ 'SOURCEBUFFER_CREATED',
1308
1597
  'SOURCEBUFFER_UPDATEEND',
1309
1598
  'SEEKING',
1310
1599
  'SEEKED',
@@ -1320,11 +1609,22 @@ export function createReducer(slices, config, hooks = {}) {
1320
1609
  let [next, effects] = isCommand(msg)
1321
1610
  ? reduceCommand(state, msg, cfg, hooks)
1322
1611
  : reduceFact(state, msg, cfg, hooks);
1612
+ // A rejected command stops here. Acceptance is decided once, in the
1613
+ // kernel branch; a slice that saw the refused command would act on an
1614
+ // intent the kernel did not, and every slice would have to read the
1615
+ // phase to tell the two apart. `reject` is the only producer of this
1616
+ // event inside the reducer, and it never changes state.
1617
+ if (isCommand(msg) &&
1618
+ effects.some((effect) => effect.kind === 'emit' && effect.event === 'command:rejected')) {
1619
+ return [next, effects];
1620
+ }
1323
1621
  // The buffer-goal loop runs on every fact that can change what to
1324
1622
  // fetch next. TIME_UPDATE drives inside its own reduction; the others
1325
1623
  // drive here, which is what makes startup work on a paused element
1326
1624
  // that fires no timeupdate.
1327
- if (!isCommand(msg) && DRIVING_FACTS.has(msg.type)) {
1625
+ // A refresh that merged nothing changes nothing to drive.
1626
+ const merged = msg.type !== 'PLAYLIST_REFRESHED' || next.presentation !== state.presentation;
1627
+ if (!isCommand(msg) && DRIVING_FACTS.has(msg.type) && merged) {
1328
1628
  const [driven, driveEffects] = driveScheduling(next, hooks, cfg);
1329
1629
  next = driven;
1330
1630
  if (driveEffects.length > 0)
@@ -1361,6 +1661,17 @@ export function createReducer(slices, config, hooks = {}) {
1361
1661
  next = failed;
1362
1662
  effects = [...effects, ...failEffects];
1363
1663
  }
1664
+ // After the slices: a stage flushes too, recovery for one.
1665
+ const buffers = forgetFlushed(next.buffers, effects);
1666
+ if (buffers !== next.buffers)
1667
+ next = { ...next, buffers };
1668
+ // A failed engine starts nothing: no fetch, no timer, no append, from
1669
+ // the kernel or from any stage. Reports and aborts still go out. A
1670
+ // response or a timer already on its way lands here and ends here, so
1671
+ // every loop (playlist reloads, steering, retries) stops on its own.
1672
+ if (next.lifecycle.phase === 'error') {
1673
+ effects = effects.filter((effect) => effect.kind === 'emit' || effect.kind === 'abort');
1674
+ }
1364
1675
  return [next, effects];
1365
1676
  };
1366
1677
  }