@blockcast/mmt-container 2.2.0-main.5da4e39e7fb8 → 2.2.0-main.5deae23da0f9

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 (129) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-beacon.d.ts +39 -0
  7. package/dist/ad-beacon.d.ts.map +1 -0
  8. package/dist/ad-beacon.js +21 -0
  9. package/dist/ad-beacon.js.map +7 -0
  10. package/dist/ad-creative-record.d.ts +65 -0
  11. package/dist/ad-creative-record.d.ts.map +1 -0
  12. package/dist/ad-creative-record.js +2281 -0
  13. package/dist/ad-creative-record.js.map +7 -0
  14. package/dist/ad-creative-timeline.d.ts +103 -0
  15. package/dist/ad-creative-timeline.d.ts.map +1 -0
  16. package/dist/ad-creative-timeline.js +2548 -0
  17. package/dist/ad-creative-timeline.js.map +7 -0
  18. package/dist/block-policy.d.ts +128 -14
  19. package/dist/block-policy.d.ts.map +1 -1
  20. package/dist/block-policy.js +472 -27
  21. package/dist/block-policy.js.map +2 -2
  22. package/dist/browser-runtime.js +1024 -117
  23. package/dist/browser-runtime.js.map +4 -4
  24. package/dist/carp-catalog.d.ts +1 -0
  25. package/dist/carp-catalog.d.ts.map +1 -1
  26. package/dist/carp-catalog.js +34 -0
  27. package/dist/carp-catalog.js.map +4 -4
  28. package/dist/catalog-fec-params.js.map +1 -1
  29. package/dist/catalog-network-source.d.ts +1 -17
  30. package/dist/catalog-network-source.d.ts.map +1 -1
  31. package/dist/catalog-network-source.js +25 -19
  32. package/dist/catalog-network-source.js.map +3 -3
  33. package/dist/cmaf-block-assembler.d.ts +10 -2
  34. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  35. package/dist/cmaf-block-assembler.js +30 -8
  36. package/dist/cmaf-block-assembler.js.map +3 -3
  37. package/dist/codec-utils.d.ts.map +1 -1
  38. package/dist/codec-utils.js +16 -3
  39. package/dist/codec-utils.js.map +2 -2
  40. package/dist/conceal-timeline.d.ts +24 -1
  41. package/dist/conceal-timeline.d.ts.map +1 -1
  42. package/dist/conceal-timeline.js +201 -4
  43. package/dist/conceal-timeline.js.map +3 -3
  44. package/dist/datagram-leg-deadline.d.ts +4 -0
  45. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  46. package/dist/datagram-leg-deadline.js.map +2 -2
  47. package/dist/event-timeline-mmtp.d.ts +17 -0
  48. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  49. package/dist/event-timeline-mmtp.js +3117 -0
  50. package/dist/event-timeline-mmtp.js.map +7 -0
  51. package/dist/fec-manager.d.ts +24 -3
  52. package/dist/fec-manager.d.ts.map +1 -1
  53. package/dist/fec-manager.js +531 -38
  54. package/dist/fec-manager.js.map +2 -2
  55. package/dist/feed-gate.d.ts +114 -0
  56. package/dist/feed-gate.d.ts.map +1 -0
  57. package/dist/feed-gate.js +175 -0
  58. package/dist/feed-gate.js.map +7 -0
  59. package/dist/index.d.ts +3 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +13 -1
  62. package/dist/index.js.map +2 -2
  63. package/dist/iso-bmff-timing.d.ts +16 -0
  64. package/dist/iso-bmff-timing.d.ts.map +1 -1
  65. package/dist/iso-bmff-timing.js +28 -0
  66. package/dist/iso-bmff-timing.js.map +2 -2
  67. package/dist/mfu-reassembler.d.ts +2 -0
  68. package/dist/mfu-reassembler.d.ts.map +1 -1
  69. package/dist/mfu-reassembler.js +4 -2
  70. package/dist/mfu-reassembler.js.map +2 -2
  71. package/dist/mmtp-container-parser.d.ts +12 -0
  72. package/dist/mmtp-container-parser.d.ts.map +1 -1
  73. package/dist/mmtp-container-parser.js +73 -3
  74. package/dist/mmtp-container-parser.js.map +2 -2
  75. package/dist/mmtp-container-parser.no-modules.js +103 -25
  76. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  77. package/dist/mmtp-decode-pipeline.js +73 -3
  78. package/dist/mmtp-decode-pipeline.js.map +2 -2
  79. package/dist/mmtp-router.d.ts +20 -2
  80. package/dist/mmtp-router.d.ts.map +1 -1
  81. package/dist/mmtp-router.js +150 -23
  82. package/dist/mmtp-router.js.map +3 -3
  83. package/dist/multicast-auth-catalog.js.map +1 -1
  84. package/dist/multicast-input.js.map +1 -1
  85. package/dist/multicast-manager.d.ts +23 -2
  86. package/dist/multicast-manager.d.ts.map +1 -1
  87. package/dist/multicast-manager.js +737 -86
  88. package/dist/multicast-manager.js.map +3 -3
  89. package/dist/multicast-transport.js +44 -22
  90. package/dist/multicast-transport.js.map +2 -2
  91. package/dist/no-modules.js +98 -22
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/repair-fetch.d.ts +10 -3
  94. package/dist/repair-fetch.d.ts.map +1 -1
  95. package/dist/repair-fetch.js +31 -5
  96. package/dist/repair-fetch.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +73 -3
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +17 -5
  101. package/schemas/catalog.schema.json +7 -2
  102. package/src/ad-beacon.ts +51 -0
  103. package/src/ad-creative-record.ts +276 -0
  104. package/src/ad-creative-timeline.ts +410 -0
  105. package/src/block-policy.ts +673 -42
  106. package/src/carp-catalog.ts +9 -0
  107. package/src/catalog-network-source.ts +3 -37
  108. package/src/cmaf-block-assembler.ts +17 -0
  109. package/src/codec-utils.ts +19 -3
  110. package/src/conceal-timeline.ts +60 -5
  111. package/src/datagram-leg-deadline.ts +4 -0
  112. package/src/event-timeline-mmtp.ts +55 -0
  113. package/src/fec-manager.ts +84 -12
  114. package/src/feed-gate.ts +295 -0
  115. package/src/index.ts +21 -0
  116. package/src/iso-bmff-timing.ts +33 -0
  117. package/src/mfu-reassembler.ts +4 -0
  118. package/src/mmtp-container-parser.ts +51 -5
  119. package/src/mmtp-router.ts +116 -4
  120. package/src/multicast-manager.ts +31 -0
  121. package/src/repair-fetch.ts +53 -8
  122. package/test-vectors/catalog/README.md +1 -0
  123. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  124. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  125. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  126. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  127. package/test-vectors/catalog/section-codes.json +1 -0
  128. package/test-vectors/frame-needs-v1.json +295 -0
  129. package/test-vectors/repair-policy-v1.json +36 -3
@@ -1181,3 +1181,12 @@ export function validateSwitchingSetTiming(
1181
1181
  if (mismatches.length === 0) return { ok: true };
1182
1182
  return { ok: false, expectedTicks, mismatches };
1183
1183
  }
1184
+
1185
+ // Re-exported here, not from index.ts: index's bundle keeps `./*.js` external,
1186
+ // so a direct mmt-base re-export there leaves a dangling `./mmtp.js` import.
1187
+ export {
1188
+ catalogEventTimelineTracks,
1189
+ type EventTimelineTrack,
1190
+ type EventTimelineTrackIssue,
1191
+ type EventTimelineTrackIssueCode,
1192
+ } from '@blockcast/mmt-base'
@@ -77,40 +77,6 @@ export function catalogAmtNetworkSource(networkSource: unknown): AmtNetworkSourc
77
77
  return undefined;
78
78
  }
79
79
 
80
- /** Resolved ATSC 3.0 tuning (draft -01 4.2.2/4.2.3). Only `frequency` is REQUIRED. */
81
- export type Atsc3NetworkSource = {
82
- /** RF centre frequency in kHz. */
83
- frequency: number;
84
- plpId?: number;
85
- serviceId?: number;
86
- /** SLS of the MMTP service; libmmt does not fetch it. */
87
- slsUri?: string;
88
- };
89
-
90
- function intIn(value: unknown, min: number, max: number): value is number {
91
- return Number.isInteger(value) && (value as number) >= min && (value as number) <= max;
92
- }
93
-
94
- /**
95
- * Resolve ATSC 3.0 tuning from a catalog `networkSource` (array or bare-object
96
- * form): the first `type: "atsc3"` entry with a positive integer `frequency`
97
- * (kHz). Optional fields are carried only when in range; an entry with no
98
- * usable frequency is skipped, since it names nothing a tuner can lock to.
99
- * Draft -01 3 puts the tuner first, so callers prefer this over AMT.
100
- */
101
- export function catalogAtsc3NetworkSource(networkSource: unknown): Atsc3NetworkSource | undefined {
102
- const entries = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
103
- for (const raw of entries) {
104
- if (!raw || typeof raw !== "object") continue;
105
- const ns = raw as CatalogNetworkSource;
106
- if (ns.type !== "atsc3" || !intIn(ns.frequency, 1, Number.MAX_SAFE_INTEGER)) continue;
107
- const slsUri = typeof ns.slsUri === "string" ? ns.slsUri.trim() : "";
108
- return {
109
- frequency: ns.frequency,
110
- ...(intIn(ns.plpId, 0, 63) ? { plpId: ns.plpId } : {}),
111
- ...(intIn(ns.serviceId, 0, 65535) ? { serviceId: ns.serviceId } : {}),
112
- ...(slsUri ? { slsUri } : {}),
113
- };
114
- }
115
- return undefined;
116
- }
80
+ // ATSC 3.0 tuning (draft -01 4.2.2/4.2.3) is read in `@blockcast/mmt-base`, so
81
+ // the transport's `endpointToMulticastConfig` shares this one reader.
82
+ export { catalogAtsc3NetworkSource, type Atsc3NetworkSource } from "@blockcast/mmt-base";
@@ -20,6 +20,7 @@ import {
20
20
  } from './mmtp-to-cmaf.js'
21
21
  import { AudioGapConcealer } from './conceal-timeline.js'
22
22
  import type { FrameGapDecision } from './block-policy.js'
23
+ import type { FrameNeeds } from './feed-gate.js'
23
24
  import {
24
25
  classifyH264Keyframe,
25
26
  detectH264Keyframe,
@@ -74,6 +75,8 @@ interface BlockFrame {
74
75
  deliveryProvenance?: MmtpDeliveryProvenance
75
76
  /** libmmt's stall/conceal decision for the gap before this frame. */
76
77
  gapBefore?: FrameGapDecision
78
+ /** The frame's dependency statement (`RoutedFrameMeta.needs`). */
79
+ needs?: FrameNeeds
77
80
  }
78
81
 
79
82
  export interface CmafBlockSample {
@@ -125,6 +128,11 @@ export interface CmafBlockSample {
125
128
  * (`RoutedFrameMeta.gapBefore`). MSE sinks feed it to HoldLastTimeline.
126
129
  */
127
130
  gapBefore?: FrameGapDecision
131
+ /**
132
+ * The sample's dependency statement (`RoutedFrameMeta.needs`). MSE sinks
133
+ * feed it to HoldLastTimeline beside `gapBefore`.
134
+ */
135
+ needs?: FrameNeeds
128
136
  }
129
137
 
130
138
  export type CmafSampleOrderPolicy =
@@ -474,6 +482,8 @@ export class CmafBlockAssembler {
474
482
  synthetic: boolean | undefined,
475
483
  /** libmmt's decision for the gap before this sample, carried to sinks. */
476
484
  gapBefore: FrameGapDecision | undefined,
485
+ /** The sample's dependency statement, carried to sinks. */
486
+ needs: FrameNeeds | undefined,
477
487
  ): void {
478
488
  // Authored-timing admission — the rollback switch the BLO-30397 removal
479
489
  // gate names. Refuse the sample outright rather than stripping its offset:
@@ -539,6 +549,7 @@ export class CmafBlockAssembler {
539
549
  ...(deliveryProvenance === undefined ? {} : { deliveryProvenance }),
540
550
  ...(synthetic === undefined ? {} : { synthetic }),
541
551
  ...(gapBefore === undefined ? {} : { gapBefore }),
552
+ ...(needs === undefined ? {} : { needs }),
542
553
  })
543
554
  if (sample === null) return
544
555
  if (advancesHorizon && unwrappedTimestamp > this.#lastSourceTs) {
@@ -805,6 +816,7 @@ export class CmafBlockAssembler {
805
816
  f.sampleNumber,
806
817
  f.synthetic,
807
818
  f.gapBefore,
819
+ f.needs,
808
820
  )
809
821
  }
810
822
  }
@@ -965,6 +977,7 @@ export class CmafBlockAssembler {
965
977
  movieFragmentSequenceNumber?: number,
966
978
  sampleNumber?: number,
967
979
  gapBefore?: FrameGapDecision,
980
+ needs?: FrameNeeds,
968
981
  ): void {
969
982
  void sbn; void esi
970
983
  this.#emitStats.addedFrames++
@@ -992,6 +1005,7 @@ export class CmafBlockAssembler {
992
1005
  sampleNumber,
993
1006
  undefined,
994
1007
  gapBefore,
1008
+ needs,
995
1009
  )
996
1010
 
997
1011
  this.#countEmit([{ keyframe }])
@@ -1060,6 +1074,7 @@ export class CmafBlockAssembler {
1060
1074
  movieFragmentSequenceNumber?: number,
1061
1075
  sampleNumber?: number,
1062
1076
  gapBefore?: FrameGapDecision,
1077
+ needs?: FrameNeeds,
1063
1078
  ): void {
1064
1079
  if (!this.#ordersSamples()) this.#drainRecoveredUpTo(timestamp)
1065
1080
  this.#emitSample(
@@ -1080,6 +1095,7 @@ export class CmafBlockAssembler {
1080
1095
  sampleNumber,
1081
1096
  undefined,
1082
1097
  gapBefore,
1098
+ needs,
1083
1099
  )
1084
1100
  }
1085
1101
 
@@ -1204,6 +1220,7 @@ export class CmafBlockAssembler {
1204
1220
  frame.sampleNumber,
1205
1221
  frame.synthetic,
1206
1222
  frame.gapBefore,
1223
+ frame.needs,
1207
1224
  )
1208
1225
  this.#countEmit([frame])
1209
1226
  }
@@ -799,7 +799,7 @@ export function splitH264SampleNalUnits(
799
799
  * framing — FFmpeg LOC delivers the latter.
800
800
  */
801
801
  export function extractHevcParameterSets(keyframe: Uint8Array): HevcParameterSets {
802
- const nals = isAnnexB(keyframe) ? splitAnnexBNalUnits(keyframe) : splitAvccNalUnits(keyframe)
802
+ const nals = splitHevcSample(keyframe)?.nals ?? splitAvccNalUnits(keyframe)
803
803
  const out: HevcParameterSets = {}
804
804
  for (const nal of nals) {
805
805
  if (nal.length === 0) continue
@@ -897,9 +897,10 @@ export function extractHevcCodecDescription(keyframe: Uint8Array): Uint8Array |
897
897
  * unchanged if it already contains only VCL NALs (cheap no-op for delta frames).
898
898
  */
899
899
  export function hevcVclOnly(data: Uint8Array): Uint8Array {
900
- const nals = isAnnexB(data) ? splitAnnexBNalUnits(data) : splitAvccNalUnits(data)
900
+ // Neither framing: keep the tolerant length-prefixed split, which returns a sample with no NAL unchanged.
901
+ const { nals, lengthPrefixed } = splitHevcSample(data) ?? { nals: splitAvccNalUnits(data), lengthPrefixed: true }
901
902
  const vcl = nals.filter((n) => n.length > 0 && hevcNalType(n) <= 31)
902
- if (vcl.length === nals.length && !isAnnexB(data)) return data
903
+ if (vcl.length === nals.length && lengthPrefixed) return data
903
904
  let size = 0
904
905
  for (const n of vcl) size += 4 + n.length
905
906
  const out = new Uint8Array(size)
@@ -2099,6 +2100,21 @@ if (import.meta.vitest) {
2099
2100
  const vclOnly = lp(idr)
2100
2101
  expect(hevcVclOnly(vclOnly)).toBe(vclOnly)
2101
2102
  })
2103
+
2104
+ test('a first NAL of 256 to 511 bytes is length-prefixed, not an Annex-B start code', () => {
2105
+ // A 4-byte length of 256..511 is 00 00 01 xx on the wire.
2106
+ for (const nalLength of [255, 256, 511, 512]) {
2107
+ const sei = new Uint8Array(nalLength).fill(0xff)
2108
+ sei.set([39 << 1, 0x01]) // PREFIX_SEI
2109
+ const keyframe = lp(sei, vps, sps, pps, idr)
2110
+ expect(extractHevcParameterSets(keyframe), `${nalLength}`).toEqual({ vps, sps, pps })
2111
+ expect(hevcVclOnly(keyframe), `${nalLength}`).toEqual(lp(idr))
2112
+ const slice = new Uint8Array(nalLength).fill(0xff)
2113
+ slice.set([1 << 1, 0x01]) // TRAIL_R
2114
+ const vclOnly = lp(slice)
2115
+ expect(hevcVclOnly(vclOnly), `${nalLength}`).toBe(vclOnly)
2116
+ }
2117
+ })
2102
2118
  })
2103
2119
  })
2104
2120
  }
@@ -10,12 +10,22 @@
10
10
  * - {@link videoConcealModeForCodec} says whether a video decoder can be fed
11
11
  * straight through a delta gap (H.264 conceals missing references itself)
12
12
  * or must hold until the next RAP.
13
- * - {@link HoldLastTimeline} gives MSE sinks gapless per-sample durations.
13
+ * - {@link HoldLastTimeline} gives MSE sinks gapless per-sample durations. It
14
+ * owns a {@link VideoFeedGate}, so a stream that states what each frame
15
+ * needs holds only the frames a loss reaches.
14
16
  * - {@link AudioGapConcealer} sizes audio concealment exactly: repeat the last
15
17
  * good access unit (MSE) or insert PCM silence (WebCodecs).
16
18
  */
17
19
 
18
20
  import type { FrameGapDecision } from './block-policy.js'
21
+ import {
22
+ VideoFeedGate,
23
+ decoderTolerance,
24
+ type DecoderTolerance,
25
+ type FrameNeeds,
26
+ type GateAnswer,
27
+ type VideoFeedGateStats,
28
+ } from './feed-gate.js'
19
29
 
20
30
  // ─── Video conceal mode ─────────────────────────────────────────────
21
31
 
@@ -31,11 +41,10 @@ export type VideoConcealMode = 'feed-through' | 'hold-to-rap'
31
41
  * AVC decoders conceal a missing reference and resynchronise on their own;
32
42
  * HEVC, AV1 and VP9 decoders error or freeze on a broken reference chain.
33
43
  * Any codec not known to conceal is held to the next RAP (fail-closed).
44
+ * The codec table itself is {@link decoderTolerance}.
34
45
  */
35
46
  export function videoConcealModeForCodec(codec: string): VideoConcealMode {
36
- const lower = codec.toLowerCase()
37
- if (lower.startsWith('avc1') || lower.startsWith('avc3')) return 'feed-through'
38
- return 'hold-to-rap'
47
+ return decoderTolerance(codec) === 'conceals' ? 'feed-through' : 'hold-to-rap'
39
48
  }
40
49
 
41
50
  // ─── HoldLastTimeline ───────────────────────────────────────────────
@@ -52,6 +61,8 @@ export interface TimelineSample<T> {
52
61
  readonly mpu?: number
53
62
  /** Decision attached by libmmt to the first frame released after a gap. */
54
63
  readonly gapBefore?: FrameGapDecision
64
+ /** The frame's dependency statement (`RoutedFrameMeta.needs`), forwarded as is. */
65
+ readonly needs?: FrameNeeds
55
66
  }
56
67
 
57
68
  /** A sample ready to append, with an explicit per-sample duration. */
@@ -65,6 +76,8 @@ export interface TimelineEmit<T> {
65
76
 
66
77
  export interface HoldLastTimelineOptions {
67
78
  readonly concealMode: VideoConcealMode
79
+ /** `decoderTolerance(codec)`. Omitted, no statement is read. */
80
+ readonly tolerance?: DecoderTolerance
68
81
  }
69
82
 
70
83
  export interface HoldLastTimelineStats {
@@ -90,22 +103,47 @@ const U32_MAX = 0xffff_ffffn
90
103
  * stream shows composition offsets (dts ≠ pts), samples pass straight
91
104
  * through with their authored durations and MSE starves until the RAP is
92
105
  * appended — the one documented case where the element also waits on audio.
106
+ *
107
+ * Inside a GOP the feed gate reads, a sample whose anchor was not fed is
108
+ * withheld alone: the held frame stays held and the next fed sample sizes it.
109
+ * With composition offsets there is no stretch, so a withheld sample holds to
110
+ * the next RAP. So does the first sample with an offset when it follows a
111
+ * withheld one.
93
112
  */
94
113
  export class HoldLastTimeline<T> {
95
114
  readonly #concealMode: VideoConcealMode
115
+ readonly #gate: VideoFeedGate
96
116
  #held: TimelineSample<T> | null = null
97
117
  #dropping = false
98
118
  #compositionOffsets = false
119
+ /** A sample was withheld and the held frame has not yet been stretched over it. */
120
+ #skipped = false
99
121
  readonly #stats: HoldLastTimelineStats = { droppedFrames: 0, extendedHolds: 0 }
100
122
 
101
123
  constructor(options: HoldLastTimelineOptions) {
102
124
  this.#concealMode = options.concealMode
125
+ this.#gate = new VideoFeedGate({ tolerance: options.tolerance ?? 'conceals' })
103
126
  }
104
127
 
105
128
  get stats(): Readonly<HoldLastTimelineStats> {
106
129
  return { ...this.#stats }
107
130
  }
108
131
 
132
+ /** What the feed gate withheld and fed across a gap. */
133
+ get gateStats(): Readonly<VideoFeedGateStats> {
134
+ return this.#gate.stats
135
+ }
136
+
137
+ /**
138
+ * The sink's decoder failed. True when a frame had been fed across a gap: the gate then
139
+ * reads no statement on this track again. The rest of a GOP in which the gate withheld a
140
+ * sample or fed one across a gap is not appended. Nothing else changes; to start over,
141
+ * call {@link reset}.
142
+ */
143
+ onDecoderFailure(): boolean {
144
+ return this.#gate.onDecoderFailure()
145
+ }
146
+
109
147
  push(sample: TimelineSample<T>): TimelineEmit<T>[] {
110
148
  if (sample.dts !== sample.pts) this.#compositionOffsets = true
111
149
 
@@ -118,7 +156,20 @@ export class HoldLastTimeline<T> {
118
156
  return this.#accept(sample)
119
157
  }
120
158
 
121
- if (this.#dropsUntilRap(sample)) {
159
+ const gap = sample.gapBefore
160
+ // The timeline's own stall test comes first: the gate is not asked about a frame that stalls.
161
+ const stalls = !sample.keyframe && gap?.trackKind === 'video' && gap.action === 'stall'
162
+ const answer: GateAnswer = stalls ? 'unread' : this.#gate.admit(sample)
163
+ // Without the stretch a withheld sample would leave a hole, so offsets keep the hold to the RAP.
164
+ const selective = answer !== 'unread' && !this.#compositionOffsets
165
+ if (selective && answer === 'withhold') {
166
+ // The held frame stays held: the next fed sample sizes it.
167
+ this.#skipped = true
168
+ return []
169
+ }
170
+ // Offsets end the stretch, so a sample after a skipped one would be appended behind a hole.
171
+ const holed = this.#skipped && this.#compositionOffsets && !sample.keyframe
172
+ if (answer === 'withhold' || holed || (!selective && this.#dropsUntilRap(sample))) {
122
173
  this.#dropping = true
123
174
  this.#stats.droppedFrames++
124
175
  // The held frame stays held: the RAP's #accept sizes it exactly.
@@ -138,9 +189,13 @@ export class HoldLastTimeline<T> {
138
189
  this.#held = null
139
190
  this.#dropping = false
140
191
  this.#compositionOffsets = false
192
+ this.#skipped = false
193
+ this.#gate.requireKeyframe()
141
194
  }
142
195
 
143
196
  #accept(sample: TimelineSample<T>): TimelineEmit<T>[] {
197
+ this.#gate.fed(sample)
198
+ this.#skipped = false
144
199
  if (this.#compositionOffsets) {
145
200
  const out = this.#releaseHeld()
146
201
  out.push(this.#emit(sample, sample.duration))
@@ -362,6 +362,10 @@ const wholeCount = (value: unknown): number =>
362
362
  * finite number >= 0 counts as 0 (a fraction is floored), a `rand` outside
363
363
  * [0, 1) counts as 0. A `joinDarkMs` that is not a finite number > 0 has no
364
364
  * leg to return to: undefined. A very large `n` yields Infinity, never a wrap.
365
+ *
366
+ * Not a `setTimeout` delay as it stands. A delay above 2147483647 ms
367
+ * (2^31 - 1) fires early, and Infinity at once: arm no timer for Infinity,
368
+ * and clamp the rest.
365
369
  */
366
370
  export function datagramLegRetryDelayMs(joinDarkMs: number, n: number, rand: number): number | undefined {
367
371
  if (!positive(joinDarkMs)) return undefined
@@ -0,0 +1,55 @@
1
+ // Event Timeline Objects from MMTP (vectors/event-timeline-mmtp-00/README.md): the admitted packets
2
+ // of one data packet id (MmtpRouter.onTrackData), reassembled from non-timed MFU items into whole
3
+ // MoQ Object payloads with their Location. Never throws into the router.
4
+ import { extractMFUPayloadWithHeader, type MMTPHeader } from '@blockcast/mmt-base'
5
+ import type { AdObjectLocation } from './ad-creative-timeline.js'
6
+ import { MFUReassembler, isMfuReassemblyError, type MfuReassemblyErrorCode, type ReassembledMFU } from './mfu-reassembler.js'
7
+
8
+ export class EventTimelineMmtpReader {
9
+ /** Distinct, counted drop reasons, reassembly ones by code (CLAUDE.md, "Diagnostics Preserve Drop Reasons"). */
10
+ readonly drops: { notItem: number; reassembly: Partial<Record<MfuReassemblyErrorCode, number>> } = { notItem: 0, reassembly: {} }
11
+ readonly #onObject: (bytes: Uint8Array, location: AdObjectLocation) => void
12
+ // Clock-free on multicast too, the exception CLAUDE.md records for this track: it declares no group
13
+ // duration to derive a deadline from. A stranded item costs memory only, until maxBuffered releases it
14
+ // (counted in `evicted`) and the next Group's Object 0 replaces it.
15
+ readonly #reassembler: MFUReassembler
16
+
17
+ constructor(onObject: (bytes: Uint8Array, location: AdObjectLocation) => void, maxBuffered = 4) {
18
+ this.#onObject = onObject
19
+ this.#reassembler = new MFUReassembler({ timeoutMs: null, maxBuffered })
20
+ }
21
+
22
+ /** Fragment-lost items the maxBuffered bound released: read it first when Objects go missing. */
23
+ get evicted(): number {
24
+ return this.#reassembler.stats.evictedMemoryLimit
25
+ }
26
+
27
+ /** Pass as the router callback: `router.onTrackData(packetId, (p, h) => reader.feed(p, h))`. */
28
+ feed(packet: Uint8Array, header: MMTPHeader): void {
29
+ // The header the router parsed once is reused (CLAUDE.md, "Parse Each Packet Once").
30
+ const mfu = extractMFUPayloadWithHeader(packet, header)
31
+ if (mfu === null || mfu.fragmentType !== 2 || mfu.mpu.timedFlag !== 0) {
32
+ this.drops.notItem++
33
+ return
34
+ }
35
+ let item: ReassembledMFU | null
36
+ try {
37
+ item = this.#reassembler.addFragment({
38
+ fragmentationIndicator: mfu.mpu.fragmentationIndicator,
39
+ mpuSequenceNumber: mfu.mpu.mpuSequenceNumber,
40
+ fragmentCounter: mfu.mpu.fragmentCounter,
41
+ data: mfu.data,
42
+ timestamp: header.timestamp,
43
+ rapFlag: header.rapFlag,
44
+ ...(mfu.itemId === null ? {} : { itemId: mfu.itemId }),
45
+ packetSequenceNumber: header.sequenceNumber,
46
+ packetId: header.packetId,
47
+ })
48
+ } catch (error) {
49
+ if (!isMfuReassemblyError(error)) throw error
50
+ this.drops.reassembly[error.code] = (this.drops.reassembly[error.code] ?? 0) + 1
51
+ return
52
+ }
53
+ if (item?.itemId !== undefined) this.#onObject(item.data, { groupId: item.mpuSequenceNumber, objectId: item.itemId })
54
+ }
55
+ }
@@ -48,6 +48,7 @@ import {
48
48
  type ClassifierChange,
49
49
  type ClassifierMode,
50
50
  type ClassifierReason,
51
+ type MpuRuleOffReason,
51
52
  type ReclassificationEvidence,
52
53
  type SourceSymbolEvidence,
53
54
  type TrackKind,
@@ -1715,6 +1716,40 @@ export class FECManager {
1715
1716
  }
1716
1717
  }
1717
1718
 
1719
+ /**
1720
+ * The DU header of a source packet that a decode rebuilt in block `sbn`.
1721
+ * It can class the blocks around that block (the MPU rule reads the DU
1722
+ * headers the receiver holds); the rebuilt block itself is resolved.
1723
+ */
1724
+ noteRecoveredSource(
1725
+ sbn: number,
1726
+ packetId: number,
1727
+ catalogTrackName: string | undefined,
1728
+ evidence: SourceSymbolEvidence,
1729
+ ): void {
1730
+ const trackConfig = this.#trackConfigs.get(packetId)
1731
+ if (trackConfig === undefined || !FECManager.#hasCatalogTiming(trackConfig)) return
1732
+ this.#applyClassifierChanges(
1733
+ packetId,
1734
+ catalogTrackName,
1735
+ this.#classifierFor(packetId, catalogTrackName).observeRecovered(sbn, evidence),
1736
+ )
1737
+ }
1738
+
1739
+ /**
1740
+ * Tell the classifier of a block no source symbol of which is held, so the
1741
+ * DU headers around it can class it (the MPU rule reads the headers held
1742
+ * before and after a block's missing symbols; here every one is missing).
1743
+ * A block the classifier has no record of is never classed.
1744
+ */
1745
+ #registerSourcelessBlock(sbn: number, packetId: number, catalogTrackName: string | undefined): void {
1746
+ this.#applyClassifierChanges(
1747
+ packetId,
1748
+ catalogTrackName,
1749
+ this.#classifierFor(packetId, catalogTrackName).touch(sbn),
1750
+ )
1751
+ }
1752
+
1718
1753
  /**
1719
1754
  * Freeze a block's class at resolution and drop its classifier state. The
1720
1755
  * frozen class answers every later query (a recovery counted after the
@@ -1937,7 +1972,7 @@ export class FECManager {
1937
1972
  if (this.#blockResolutionFor(key) !== 'untracked') return
1938
1973
  this.#materializedBlocks.add(key)
1939
1974
  if (this.#hasCatalogTimingForPacket(packetId)) {
1940
- this.#classifierFor(packetId, catalogTrackName).touch(sbn)
1975
+ this.#registerSourcelessBlock(sbn, packetId, catalogTrackName)
1941
1976
  }
1942
1977
  this.onBlockVanished?.(sbn, packetId, catalogTrackName)
1943
1978
  if (repairable) {
@@ -3991,6 +4026,17 @@ export class FECManager {
3991
4026
  return { mode: classifier.mode, reason: classifier.reason }
3992
4027
  }
3993
4028
 
4029
+ /**
4030
+ * Why the MPU rule classes no block on a video stream now
4031
+ * (`BlockClassifier.mpuRuleOff`): what its catalog does not state, or what
4032
+ * the stream showed. Null while the rule can class a block. Undefined for a
4033
+ * stream with no classifier: one not heard yet, or without catalog timing.
4034
+ */
4035
+ mpuRuleOffFor(packetId: number, catalogTrackName?: string): MpuRuleOffReason | null | undefined {
4036
+ const classifier = this.#classifiers.get(this.#streamKey(packetId, catalogTrackName))
4037
+ return classifier?.geometry.trackKind === 'video' ? classifier.mpuRuleOff : undefined
4038
+ }
4039
+
3994
4040
  /**
3995
4041
  * Whether an MPU boundary still bounds this stream's RAPs (see
3996
4042
  * `BlockClassifier.mpuBoundsRaps`). Gap decisions drop MPU evidence once
@@ -4093,6 +4139,29 @@ export class FECManager {
4093
4139
  )
4094
4140
  }
4095
4141
 
4142
+ /**
4143
+ * Decode times of the first and last sample that one held movie fragment's
4144
+ * metadata times, in MPU `mpu`. On a video stream the classifier looks
4145
+ * among them for an MPU longer than the catalog keyframe interval, where
4146
+ * the MPU rule stops (`BlockClassifier.noteDecodeTimes`).
4147
+ */
4148
+ noteSampleDecodeTimes(
4149
+ packetId: number,
4150
+ catalogTrackName: string | undefined,
4151
+ mpu: number,
4152
+ first: bigint,
4153
+ last: bigint,
4154
+ mediaTimescale: number,
4155
+ ): void {
4156
+ // A track never configured, or with no catalog span, has no classifier to tell.
4157
+ if (!this.#hasCatalogTimingForPacket(packetId)) return
4158
+ this.#applyClassifierChanges(
4159
+ packetId,
4160
+ catalogTrackName,
4161
+ this.#classifierFor(packetId, catalogTrackName).noteDecodeTimes(mpu, first, last, mediaTimescale),
4162
+ )
4163
+ }
4164
+
4096
4165
  // -----------------------------------------------------------------------
4097
4166
  // Configuration
4098
4167
  // -----------------------------------------------------------------------
@@ -5013,6 +5082,11 @@ export class FECManager {
5013
5082
  if (!repairIds) {
5014
5083
  repairIds = new Set()
5015
5084
  this.#blockRepairRsIds.set(blockKey, repairIds)
5085
+ // Its first repair, and no source of it arrived (a burst took the whole
5086
+ // frame): only this tells the classifier the block exists.
5087
+ if (!this.#blockSourceCounts.has(blockKey) && this.#hasCatalogTimingForPacket(packetId)) {
5088
+ this.#registerSourcelessBlock(sbn, packetId, catalogTrackName)
5089
+ }
5016
5090
  }
5017
5091
  repairIds.add(rsId)
5018
5092
  if (this.#repairRequestedBlocks.has(blockKey)) {
@@ -5325,7 +5399,8 @@ export class FECManager {
5325
5399
  * classification evidence, and marks the block clean when all of its
5326
5400
  * authored source symbols arrived: the SSB_length a repair symbol declared,
5327
5401
  * otherwise K. `held` marks a source held unplaced since it arrived and
5328
- * placed only now (see #noteSbnSeen).
5402
+ * placed only now (see #noteSbnSeen); `inSpan` one placed in a repair-less
5403
+ * span, which the classifier reads as no block (BLO-57323).
5329
5404
  *
5330
5405
  * Throws for a packetId that was never configured, so a classified block
5331
5406
  * never reads the manager-global K or timeout.
@@ -5337,6 +5412,7 @@ export class FECManager {
5337
5412
  esi: number,
5338
5413
  evidence: SourceSymbolEvidence,
5339
5414
  held = false,
5415
+ inSpan = false,
5340
5416
  ): void {
5341
5417
  const trackConfig = this.#trackConfigs.get(packetId)
5342
5418
  if (trackConfig === undefined) {
@@ -5351,15 +5427,9 @@ export class FECManager {
5351
5427
  // Skip blocks already recovered — late source symbols must not restart timeouts
5352
5428
  if (this.#completedBlocks.has(key)) return
5353
5429
 
5354
- this.#noteSbnSeen(
5355
- sbn,
5356
- packetId,
5357
- catalogTrackName,
5358
- 'source',
5359
- evidence.packetSequenceNumber,
5360
- Number.isInteger(esi) ? (sbn + esi) >>> 0 : sbn,
5361
- held,
5362
- )
5430
+ // The symbol's SS_ID: the block's SS_Start plus its ESI (ISO/IEC 23008-1 C.5.2).
5431
+ const ssId = Number.isInteger(esi) ? (sbn + esi) >>> 0 : undefined
5432
+ this.#noteSbnSeen(sbn, packetId, catalogTrackName, 'source', evidence.packetSequenceNumber, ssId, held)
5363
5433
 
5364
5434
  // A source ESI at or past the block's authored SSB_length contradicts it;
5365
5435
  // its geometry can no longer be trusted, so fail it closed.
@@ -5373,7 +5443,9 @@ export class FECManager {
5373
5443
  this.#applyClassifierChanges(
5374
5444
  packetId,
5375
5445
  catalogTrackName,
5376
- this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence),
5446
+ inSpan
5447
+ ? this.#classifierFor(packetId, catalogTrackName).observeInSpan(evidence)
5448
+ : this.#classifierFor(packetId, catalogTrackName).observe(sbn, evidence, ssId),
5377
5449
  )
5378
5450
  }
5379
5451