mattebox 0.6.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 (158) 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 +34 -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 +27 -71
  41. package/dist/es2015/kernel/prepare.js +77 -0
  42. package/dist/es2015/kernel/reducer.js +233 -64
  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 +54 -14
  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 +191 -85
  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 +1 -1
  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 +31 -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 +20 -73
  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 +317 -82
  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 -57
  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 +55 -9
  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 -88
  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 +213 -82
  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/types/kernel.d.ts +39 -13
  151. package/dist/types/kernel.d.ts.map +1 -1
  152. package/dist/types/kernel.js +2 -1
  153. package/dist/types/kernel.js.map +1 -1
  154. package/dist/types/messages.d.ts +50 -10
  155. package/dist/types/messages.d.ts.map +1 -1
  156. package/dist/types/stage.d.ts +18 -0
  157. package/dist/types/stage.d.ts.map +1 -1
  158. 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(),
@@ -162,6 +163,63 @@ function mergeCoverage(coverage, added) {
162
163
  merged.push(pending);
163
164
  return merged.sort((a, b) => a.start - b.start);
164
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
+ }
165
223
  function findTrack(presentation, trackId) {
166
224
  if (presentation === null)
167
225
  return null;
@@ -354,6 +412,12 @@ function reduceCommand(state, msg, cfg, hooks) {
354
412
  if (track === null) {
355
413
  return reject(state, msg.type, `unknown track: ${msg.trackId}`);
356
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
+ }
357
421
  const previous = state.tracks.active.get(track.contentType);
358
422
  const active = new Map(state.tracks.active);
359
423
  active.set(track.contentType, track.id);
@@ -552,6 +616,89 @@ function reduceCommand(state, msg, cfg, hooks) {
552
616
  }
553
617
  }
554
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
+ }
555
702
  function reduceFact(state, msg, cfg, hooks) {
556
703
  switch (msg.type) {
557
704
  case 'ELEMENT_ATTACHED':
@@ -560,65 +707,45 @@ function reduceFact(state, msg, cfg, hooks) {
560
707
  // Lifecycle detail owned by the mse module. Absorbed for the trace.
561
708
  return [state, []];
562
709
  case 'MANIFEST_LOADED': {
563
- const available = [];
564
- for (const period of msg.presentation.periods) {
565
- for (const track of period.tracks)
566
- available.push(track.id);
567
- }
568
- const inflight = new Map(state.scheduling.inflight);
569
- for (const [token, request] of inflight) {
570
- if (request.trackId === 'manifest')
571
- inflight.delete(token);
572
- }
573
- const phase = state.lifecycle.phase === 'loading' ? 'ready' : state.lifecycle.phase;
574
- // Default activation: the first video and audio track, so a manifest
575
- // alone yields a playable composition without a SELECT_TRACK.
576
- const active = new Map(state.tracks.active);
577
- for (const period of msg.presentation.periods) {
578
- for (const track of period.tracks) {
579
- if ((track.contentType === 'video' || track.contentType === 'audio') &&
580
- !active.has(track.contentType)) {
581
- active.set(track.contentType, track.id);
582
- }
583
- }
584
- }
585
- const loaded = {
586
- ...state,
587
- lifecycle: { phase },
588
- presentation: msg.presentation,
589
- scheduling: { ...state.scheduling, inflight },
590
- tracks: { active, available },
591
- quality: bumped(state.quality),
592
- };
593
- // A live reload feeds a MANIFEST_LOADED per playlist; the track list
594
- // only changed if the ids did.
595
- const sameTracks = available.length === state.tracks.available.length &&
596
- available.every((id, index) => id === state.tracks.available[index]);
597
- const manifestEffects = sameTracks
598
- ? []
599
- : [{ kind: 'emit', event: 'tracks:changed', payload: { available } }];
600
- // The manifest DRM route: emit every track's protection schemes so
601
- // eme-core (if loaded) can open sessions. Serializable init data
602
- // rides the event; nothing DRM-specific enters the reducer.
603
- const schemes = msg.presentation.periods.flatMap((period) => period.tracks.flatMap((track) => track.protection?.schemes ?? []));
604
- if (schemes.length > 0) {
605
- manifestEffects.push({
606
- kind: 'emit',
607
- event: 'presentation:protection',
608
- payload: schemes,
609
- });
610
- }
611
- if (!msg.presentation.isLive && msg.presentation.duration !== undefined) {
612
- manifestEffects.push({ kind: 'setDuration', seconds: msg.presentation.duration });
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] });
613
721
  }
614
- 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);
615
728
  }
616
729
  case 'MANIFEST_FAILED':
617
730
  return failManifest(state, msg.error);
618
- case 'PLAYLIST_REFRESHED':
619
- // Merging a refreshed live playlist into the presentation belongs to
620
- // the protocol stages. Absorbed for the trace until they exist.
621
- 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
+ }
622
749
  case 'SEGMENT_LOADED': {
623
750
  let matched = null;
624
751
  if (msg.token !== undefined) {
@@ -765,32 +892,67 @@ function reduceFact(state, msg, cfg, hooks) {
765
892
  ],
766
893
  ];
767
894
  }
768
- // The scheduler computed the epoch's offset at request time; apply
769
- // 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.
770
902
  // Playlist discontinuities and period boundaries both land here.
771
- if (matched.timestampOffset !== undefined &&
772
- state.timeline.periodOffsets.get(matched.sbId) !== matched.timestampOffset) {
773
- effects.push({
774
- kind: 'setTimestampOffset',
775
- sbId: matched.sbId,
776
- offset: matched.timestampOffset,
777
- });
778
- const periodOffsets = new Map(state.timeline.periodOffsets);
779
- periodOffsets.set(matched.sbId, matched.timestampOffset);
780
- 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
+ }
781
916
  }
782
- effects.push({
783
- kind: 'append',
784
- sbId: matched.sbId,
785
- data: msg.bytes,
786
- ...(matched.segmentStart !== undefined ? { start: matched.segmentStart } : {}),
787
- ...(matched.renditionId !== undefined ? { renditionId: matched.renditionId } : {}),
788
- seq: matched.seq,
789
- });
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 });
790
929
  const buffer = buffers.get(matched.sbId);
791
930
  if (buffer !== undefined) {
792
931
  const nextBuffers = new Map(buffers);
793
- 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
+ });
794
956
  buffers = nextBuffers;
795
957
  }
796
958
  if (matched.sbId === sbIdFor('video') &&
@@ -917,10 +1079,23 @@ function reduceFact(state, msg, cfg, hooks) {
917
1079
  // The buffer was removed by a concurrent detach. Absorb and ignore.
918
1080
  return [state, []];
919
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
+ }
920
1094
  const buffers = new Map(state.buffers);
921
1095
  buffers.set(msg.sbId, {
922
1096
  ...buffer,
923
1097
  ...(msg.ranges !== undefined ? { ranges: msg.ranges } : {}),
1098
+ ...(appended !== undefined ? { appended } : {}),
924
1099
  pendingAppends: Math.max(0, buffer.pendingAppends - 1),
925
1100
  });
926
1101
  // A successful append proves the buffer works: the breaker resets.
@@ -944,8 +1119,27 @@ function reduceFact(state, msg, cfg, hooks) {
944
1119
  // The buffer never opened, so nothing holds its init any more: the
945
1120
  // next decision fetches it again.
946
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);
947
1129
  const fatal = msg.error.fatal || count >= cfg.bufferErrorLimit;
948
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
+ }
949
1143
  const effects = [
950
1144
  {
951
1145
  kind: 'emit',
@@ -960,6 +1154,17 @@ function reduceFact(state, msg, cfg, hooks) {
960
1154
  },
961
1155
  },
962
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
+ }
963
1168
  let inflight = state.scheduling.inflight;
964
1169
  if (fatal) {
965
1170
  // Stop the world for this buffer: whatever is in flight will only
@@ -976,6 +1181,7 @@ function reduceFact(state, msg, cfg, hooks) {
976
1181
  return [
977
1182
  {
978
1183
  ...state,
1184
+ buffers,
979
1185
  bufferErrors,
980
1186
  lifecycle: { phase },
981
1187
  scheduling: { ...scheduling, inflight },
@@ -1001,10 +1207,13 @@ function reduceFact(state, msg, cfg, hooks) {
1001
1207
  case 'SEEKING': {
1002
1208
  // Seeking out of the ended phase resumes an ordinary ready state.
1003
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.
1004
1212
  return [
1005
1213
  {
1006
1214
  ...state,
1007
1215
  lifecycle: { phase },
1216
+ buffers: forgetAppended(state.buffers),
1008
1217
  playback: { ...state.playback, currentTime: msg.to, seeking: true },
1009
1218
  },
1010
1219
  [],
@@ -1192,6 +1401,7 @@ function driveScheduling(state, hooks, cfg) {
1192
1401
  }
1193
1402
  continue;
1194
1403
  }
1404
+ const appended = state.buffers.get(sbId)?.appended;
1195
1405
  tracks.push({
1196
1406
  trackId,
1197
1407
  period: found.period,
@@ -1199,6 +1409,7 @@ function driveScheduling(state, hooks, cfg) {
1199
1409
  ranges: state.buffers.get(sbId)?.ranges ?? [],
1200
1410
  sbId,
1201
1411
  inflight,
1412
+ ...(appended !== undefined ? { appended } : {}),
1202
1413
  });
1203
1414
  }
1204
1415
  // Cue pipelines schedule like media, minus everything SourceBuffer:
@@ -1225,13 +1436,23 @@ function driveScheduling(state, hooks, cfg) {
1225
1436
  inflight,
1226
1437
  });
1227
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);
1228
1446
  const result = schedule({
1229
1447
  currentTime: state.playback.currentTime,
1230
1448
  bufferGoal: state.scheduling.bufferGoal,
1231
1449
  tokenSeq: state.scheduling.tokenSeq + initFetches.length,
1232
1450
  tracks,
1233
1451
  liveWindow: state.presentation.isLive ? (state.live?.span ?? null) : null,
1234
- mediaTimeNormalized: cfg.mediaTimeNormalized,
1452
+ reconciles: hooks.timeProbe != null,
1453
+ leadSbId,
1454
+ reconciled: state.timeline.reconciled,
1455
+ leadPending,
1235
1456
  });
1236
1457
  // The scheduling breaker: an identical decision repeated past the limit
1237
1458
  // means appends report success but nothing ever progresses, and the
@@ -1368,6 +1589,7 @@ export function createReducer(slices, config, hooks = {}) {
1368
1589
  const cfg = resolveConfig(config);
1369
1590
  const DRIVING_FACTS = new Set([
1370
1591
  'MANIFEST_LOADED',
1592
+ 'PLAYLIST_REFRESHED',
1371
1593
  'SEGMENT_LOADED',
1372
1594
  // A buffer that opens holding an init unblocks media scheduling, and
1373
1595
  // nothing else would drive it on a paused element.
@@ -1400,7 +1622,9 @@ export function createReducer(slices, config, hooks = {}) {
1400
1622
  // fetch next. TIME_UPDATE drives inside its own reduction; the others
1401
1623
  // drive here, which is what makes startup work on a paused element
1402
1624
  // that fires no timeupdate.
1403
- 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) {
1404
1628
  const [driven, driveEffects] = driveScheduling(next, hooks, cfg);
1405
1629
  next = driven;
1406
1630
  if (driveEffects.length > 0)
@@ -1437,6 +1661,17 @@ export function createReducer(slices, config, hooks = {}) {
1437
1661
  next = failed;
1438
1662
  effects = [...effects, ...failEffects];
1439
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
+ }
1440
1675
  return [next, effects];
1441
1676
  };
1442
1677
  }