@blockcast/mmt-container 0.1.0-main.c71423b8a4e4 → 0.1.0-main.ce3c8aeb7f68

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 (148) hide show
  1. package/dist/align.d.ts +6 -2
  2. package/dist/align.d.ts.map +1 -1
  3. package/dist/align.js.map +2 -2
  4. package/dist/audio-ring-buffer.js +23 -36
  5. package/dist/audio-ring-buffer.js.map +1 -1
  6. package/dist/browser-runtime.js +6865 -6485
  7. package/dist/browser-runtime.js.map +4 -4
  8. package/dist/carp-catalog.d.ts +3 -1
  9. package/dist/carp-catalog.d.ts.map +1 -1
  10. package/dist/carp-catalog.js +21 -2
  11. package/dist/carp-catalog.js.map +4 -4
  12. package/dist/catalog-fec-params.js +10 -0
  13. package/dist/catalog-fec-params.js.map +4 -4
  14. package/dist/cmaf-block-assembler.d.ts +42 -0
  15. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  16. package/dist/cmaf-block-assembler.js +542 -535
  17. package/dist/cmaf-block-assembler.js.map +2 -2
  18. package/dist/cmaf-group-batcher.js +27 -46
  19. package/dist/cmaf-group-batcher.js.map +2 -2
  20. package/dist/cmcd-producer.js +45 -66
  21. package/dist/cmcd-producer.js.map +1 -1
  22. package/dist/fec-manager.d.ts +13 -1
  23. package/dist/fec-manager.d.ts.map +1 -1
  24. package/dist/fec-manager.js +1151 -871
  25. package/dist/fec-manager.js.map +2 -2
  26. package/dist/fec-starvation-detector.js +25 -40
  27. package/dist/fec-starvation-detector.js.map +1 -1
  28. package/dist/fec-worker-setup.js +242 -225
  29. package/dist/fec-worker-setup.js.map +3 -3
  30. package/dist/index.d.ts +3 -3
  31. package/dist/index.d.ts.map +1 -1
  32. package/dist/index.js.map +2 -2
  33. package/dist/iso-bmff-timing.js +63 -88
  34. package/dist/iso-bmff-timing.js.map +1 -1
  35. package/dist/loc.js +7 -4
  36. package/dist/loc.js.map +1 -1
  37. package/dist/manifest-auth-plan.js +292 -311
  38. package/dist/manifest-auth-plan.js.map +1 -1
  39. package/dist/media-router.d.ts +0 -99
  40. package/dist/media-router.d.ts.map +1 -1
  41. package/dist/media-router.js +270 -504
  42. package/dist/media-router.js.map +3 -3
  43. package/dist/mfu-reassembler.js +597 -607
  44. package/dist/mfu-reassembler.js.map +3 -3
  45. package/dist/mmtp-container-parser.d.ts +37 -0
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +1531 -1522
  48. package/dist/mmtp-container-parser.js.map +3 -3
  49. package/dist/mmtp-container-parser.no-modules.js +179 -102
  50. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  51. package/dist/mmtp-decode-pipeline.js +1641 -1651
  52. package/dist/mmtp-decode-pipeline.js.map +3 -3
  53. package/dist/mmtp-router.d.ts +34 -0
  54. package/dist/mmtp-router.d.ts.map +1 -1
  55. package/dist/mmtp-router.js +3676 -3390
  56. package/dist/mmtp-router.js.map +3 -3
  57. package/dist/mmtp-to-cmaf.d.ts +7 -1
  58. package/dist/mmtp-to-cmaf.d.ts.map +1 -1
  59. package/dist/mmtp-to-cmaf.js +109 -134
  60. package/dist/mmtp-to-cmaf.js.map +2 -2
  61. package/dist/multicast-input.d.ts +7 -35
  62. package/dist/multicast-input.d.ts.map +1 -1
  63. package/dist/multicast-input.js +21 -2
  64. package/dist/multicast-input.js.map +4 -4
  65. package/dist/multicast-manager.d.ts +10 -1
  66. package/dist/multicast-manager.d.ts.map +1 -1
  67. package/dist/multicast-manager.js +5584 -4961
  68. package/dist/multicast-manager.js.map +4 -4
  69. package/dist/multicast-transport.d.ts +7 -0
  70. package/dist/multicast-transport.d.ts.map +1 -1
  71. package/dist/multicast-transport.js +369 -421
  72. package/dist/multicast-transport.js.map +4 -4
  73. package/dist/multicast-unwrap.js +53 -30
  74. package/dist/multicast-unwrap.js.map +2 -2
  75. package/dist/no-modules.js +2096 -2097
  76. package/dist/no-modules.js.map +3 -3
  77. package/dist/sample-combiner.js +118 -139
  78. package/dist/sample-combiner.js.map +1 -1
  79. package/dist/signaling.js.map +2 -2
  80. package/dist/source-auth.js +353 -382
  81. package/dist/source-auth.js.map +1 -1
  82. package/dist/switching-set-alignment.js +14 -29
  83. package/dist/switching-set-alignment.js.map +1 -1
  84. package/dist/timestamp-codec.js +17 -11
  85. package/dist/timestamp-codec.js.map +2 -2
  86. package/dist/track-pipeline-setup.js +105 -125
  87. package/dist/track-pipeline-setup.js.map +1 -1
  88. package/dist/track-pipeline.js +107 -127
  89. package/dist/track-pipeline.js.map +1 -1
  90. package/dist/track-session.d.ts +16 -0
  91. package/dist/track-session.d.ts.map +1 -1
  92. package/dist/track-session.js +230 -243
  93. package/dist/track-session.js.map +2 -2
  94. package/dist/transport-pool.js +24 -38
  95. package/dist/transport-pool.js.map +1 -1
  96. package/dist/wasm-mfu-reassembler.d.ts +6 -1
  97. package/dist/wasm-mfu-reassembler.d.ts.map +1 -1
  98. package/dist/wasm-mfu-reassembler.js +127 -144
  99. package/dist/wasm-mfu-reassembler.js.map +2 -2
  100. package/dist/wasm-mmtp-container-parser.js +1659 -1650
  101. package/dist/wasm-mmtp-container-parser.js.map +3 -3
  102. package/node_modules/@blockcast/fec-worker/README.md +5 -1
  103. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts +8 -2
  104. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.d.ts.map +1 -1
  105. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js +89 -16
  106. package/node_modules/@blockcast/fec-worker/dist/fec-worker-client.js.map +1 -1
  107. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts +48 -3
  108. package/node_modules/@blockcast/fec-worker/dist/fec-worker-types.d.ts.map +1 -1
  109. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js +55 -8
  110. package/node_modules/@blockcast/fec-worker/dist/fec-worker.js.map +2 -2
  111. package/node_modules/@blockcast/fec-worker/dist/index.d.ts +1 -1
  112. package/node_modules/@blockcast/fec-worker/dist/index.d.ts.map +1 -1
  113. package/node_modules/@blockcast/fec-worker/dist/index.js.map +1 -1
  114. package/node_modules/@blockcast/fec-worker/src/fec-worker-client.ts +97 -17
  115. package/node_modules/@blockcast/fec-worker/src/fec-worker-types.ts +46 -2
  116. package/node_modules/@blockcast/fec-worker/src/fec-worker.ts +78 -10
  117. package/node_modules/@blockcast/fec-worker/src/index.ts +2 -0
  118. package/node_modules/@blockcast/mmt-base/README.md +1 -0
  119. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  120. package/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  121. package/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  122. package/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  123. package/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  124. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/README.md +1 -0
  125. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts +52 -0
  126. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.d.ts.map +1 -1
  127. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js +142 -37
  128. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/dist/mmtp.js.map +1 -1
  129. package/node_modules/@blockcast/mmt-fec/node_modules/@blockcast/mmt-base/src/mmtp.ts +158 -37
  130. package/package.json +7 -6
  131. package/schemas/catalog.schema.json +1 -1
  132. package/src/align.ts +6 -2
  133. package/src/carp-catalog.ts +13 -3
  134. package/src/cmaf-block-assembler.ts +90 -81
  135. package/src/fec-manager.ts +530 -146
  136. package/src/index.ts +2 -2
  137. package/src/media-router.ts +0 -397
  138. package/src/mmtp-container-parser.ts +97 -21
  139. package/src/mmtp-router.ts +302 -125
  140. package/src/mmtp-to-cmaf.ts +21 -7
  141. package/src/multicast-input.ts +23 -3
  142. package/src/multicast-manager.ts +83 -11
  143. package/src/multicast-transport.ts +56 -17
  144. package/src/track-session.ts +16 -0
  145. package/src/wasm-mfu-reassembler.ts +40 -24
  146. package/test-vectors/catalog/README.md +2 -0
  147. package/test-vectors/catalog/negative/multicast-packet-id-signaling.json +26 -0
  148. package/test-vectors/catalog-validation.json +11 -0
package/src/index.ts CHANGED
@@ -200,6 +200,7 @@ export {
200
200
  type CmafBlockSample,
201
201
  type CmafSampleOrderPolicy,
202
202
  type CmafSampleOrderStats,
203
+ type CmafEmitStats,
203
204
  type BlockAssemblerConfig,
204
205
  } from './cmaf-block-assembler.js'
205
206
 
@@ -245,6 +246,7 @@ export {
245
246
  type MmtpReorderStreamDiagnostics,
246
247
  type FrameMeta as ParserFrameMeta,
247
248
  type PacketInfo,
249
+ type ParsedMmtpPacket,
248
250
  } from './mmtp-container-parser.js'
249
251
 
250
252
  export {
@@ -325,8 +327,6 @@ export {
325
327
  type FrameMeta as RouterFrameMeta,
326
328
  type FrameKind,
327
329
  type SourceKind,
328
- type GroupDriftEvent,
329
- type GroupBoundaryTicks,
330
330
  } from './media-router.js'
331
331
 
332
332
  // Group-alignment primitive — shared with Go sender + Rust relay.
@@ -13,15 +13,8 @@
13
13
  * Per-track setTrackSource() allows individual tracks to be wired to a
14
14
  * specific transport source (video=multicast, audio=moq, overlay=amt) without
15
15
  * changing the binary MoQ↔multicast switching for other tracks.
16
- *
17
- * notifyGroupBoundary() is an observer hook: callers report the
18
- * packet-stamped groupId + media time for each group, and the router
19
- * cross-checks against the shared `align.ts` formula. Drift is emitted via
20
- * onGroupDrift so the player can bump the CMCD `x-bc-switch-drift-us` /
21
- * `x-bc-switch-miscount` counters. Observation only — does NOT alter routing.
22
16
  */
23
17
 
24
- import { groupIdForTicks, driftCheck } from './align.js'
25
18
  import { computeFecDeliveryWindowMs } from './track-session.js'
26
19
 
27
20
  export type FrameMeta = {
@@ -48,118 +41,6 @@ export type FrameMeta = {
48
41
  export type FrameKind = 'video' | 'audio'
49
42
  export type SourceKind = 'moq' | 'multicast'
50
43
 
51
- /**
52
- * Tick-space timing for one group boundary — the exact, authoritative form.
53
- *
54
- * These are the integers the catalog already carries (`groupDurationTicks`,
55
- * `timescale`) plus the packet's raw timestamp in the same units. Passing
56
- * them straight through keeps the whole drift check in integer math.
57
- *
58
- * Prefer this over the seconds overload: `groupDurationTicks / timescale`
59
- * is not exactly representable for the common non-integer-second cadences
60
- * (33333@90k, 1001@30k, 1024@44.1k), and the seconds path has to quantize
61
- * to whole nanoseconds — which shifts `expected` by a whole group from the
62
- * second boundary onward and reports drift on a perfectly aligned stream.
63
- */
64
- export interface GroupBoundaryTicks {
65
- /** Packet media timestamp in `timescale` units. Integer; negatives clamp to 0. */
66
- readonly mediaTimeTicks: number
67
- /** Group duration in `timescale` units. Positive integer. */
68
- readonly groupDurationTicks: number
69
- /**
70
- * Catalog timescale in Hz. Positive integer — **validated, and a hard gate**:
71
- * a non-integer or non-positive value skips the drift check entirely rather
72
- * than reporting against it. It does not feed the groupId computation (that
73
- * is `mediaTimeTicks / groupDurationTicks` alone), but it does derive the
74
- * `mediaTimeSec` / `groupDurationSec` on every GroupDriftEvent — so letting a
75
- * bad value through would push NaN/Infinity into CMCD `x-bc-switch-drift-us`,
76
- * which is worse than skipping.
77
- */
78
- readonly timescale: number
79
- }
80
-
81
- /** Payload emitted by MediaRouter.onGroupDrift when a packet-stamped groupId
82
- * disagrees with the shared `align.ts` formula. */
83
- export interface GroupDriftEvent {
84
- trackName: string
85
- expectedGroupId: number
86
- actualGroupId: number
87
- /** `actual - expected` (positive = ahead, negative = behind). */
88
- deltaGroups: number
89
- /** Seconds view, kept for CMCD consumers. Derived when the caller used ticks. */
90
- mediaTimeSec: number
91
- groupDurationSec: number
92
- /** Exact tick-space inputs. Present only when the caller used the ticks form. */
93
- timing?: GroupBoundaryTicks
94
- }
95
-
96
- /** Normalized output of the two notifyGroupBoundary input forms. */
97
- type ResolvedBoundary = {
98
- readonly expected: number
99
- readonly mediaTimeSec: number
100
- readonly groupDurationSec: number
101
- readonly timing?: GroupBoundaryTicks
102
- }
103
-
104
- /**
105
- * Distinct failure modes on the notifyGroupBoundary drift path. Each gets its
106
- * own bounded warn budget (see `#skipWithWarning`), so a stream that trips one
107
- * cannot permanently silence the diagnostic for a genuinely different one.
108
- *
109
- * Deliberately a closed union rather than `string`: the tag is the dedup key,
110
- * and a typo would silently mint a second budget for an existing reason.
111
- */
112
- type GroupAlignSkipReason =
113
- | 'invalid-tick-inputs'
114
- // Currently UNREACHABLE, kept as defence in depth — see the catch in
115
- // #resolveTicks. Do not write a test chasing it.
116
- | 'ticks-formula-threw'
117
- | 'invalid-seconds-inputs'
118
- | 'sub-nanosecond-duration'
119
- | 'media-time-overflow'
120
- | 'seconds-formula-threw'
121
- | 'callback-threw'
122
-
123
- /**
124
- * Warns allowed per `GroupAlignSkipReason` for the lifetime of a router.
125
- *
126
- * Not a single flat number (PCL-2211, #329 review). The six resolver reasons
127
- * are closed, deterministic conditions: once you have seen
128
- * `sub-nanosecond-duration` on this router, the second occurrence carries no
129
- * new information, so one slot is the right budget and repeated malformed
130
- * catalog input stays silent.
131
- *
132
- * `callback-threw` is the opposite. It wraps arbitrary downstream consumer
133
- * code and interpolates `err.message` *because the error varies*. Under one
134
- * slot, a consumer that throws at startup permanently hides an unrelated
135
- * exception later — including one from a *replacement* consumer registered
136
- * through `onGroupDrift()`, which is a public setter with no budget reset.
137
- * That is the same argument `#skipWithWarning` makes against a single shared
138
- * boolean, one level down. A small cap bounds the flood, at the cost of
139
- * silencing distinct errors past the cap: three throws at startup exhaust
140
- * `callback-threw`, and a replacement consumer's unrelated exception is then
141
- * silenced permanently — the same failure as the one-slot budget, moved from
142
- * the 1st throw to the 4th. That residual is the inherent price of a bounded
143
- * budget and is accepted deliberately; the alternative is an unbounded warn.
144
- *
145
- * Deliberately NOT a reset on `onGroupDrift()` re-registration: that setter is
146
- * public and unthrottled, so a caller re-registering per boundary would
147
- * refresh the budget every time and restore the exact flood this prevents.
148
- *
149
- * A total `Record` rather than a lookup with a default: the union is closed, so
150
- * a new reason that forgets to declare its budget is a compile error — the
151
- * same typo-safety rationale that makes the union closed in the first place.
152
- */
153
- const GROUP_ALIGN_WARN_BUDGET: Record<GroupAlignSkipReason, number> = {
154
- 'invalid-tick-inputs': 1,
155
- 'ticks-formula-threw': 1,
156
- 'invalid-seconds-inputs': 1,
157
- 'sub-nanosecond-duration': 1,
158
- 'media-time-overflow': 1,
159
- 'seconds-formula-threw': 1,
160
- 'callback-threw': 3,
161
- }
162
-
163
44
  type FrameCb = (data: Uint8Array, meta: FrameMeta) => void
164
45
  type SwitchCb = (source: SourceKind) => void | Promise<void>
165
46
 
@@ -352,284 +233,6 @@ export class MediaRouter {
352
233
  onOverlayFrame(cb: FrameCb) { this.#onOverlayFrame = cb }
353
234
  onSourceSwitch(cb: SwitchCb) { this.#onSourceSwitch = cb }
354
235
 
355
- // ── Group-alignment observer (align.ts formula) ──────────────────
356
- // Observation only — does NOT alter routing. Producers are wired in
357
- // follow-up PRs; when they land they will call
358
- // CmcdProducer.incrementSwitchMiscount() + emitSwitchDrift() from the
359
- // onGroupDrift callback so divergence between packet-stamped groupIds
360
- // and the shared formula surfaces on `x-bc-switch-drift-us` /
361
- // `x-bc-switch-miscount`. Canonical Go impl: Blockcast/multicast
362
- // cmd/caddy/sender/group_align.go (commit 104eeff). Canonical Rust impl:
363
- // moqtail/moqtail apps/relay/src/server/abr.rs (branch
364
- // experimental/server-side-abr, commit 39accbf).
365
- #onGroupDrift: ((evt: GroupDriftEvent) => void) | null = null
366
- #groupAlignWarnCounts = new Map<GroupAlignSkipReason, number>()
367
- onGroupDrift(cb: (evt: GroupDriftEvent) => void): void {
368
- this.#onGroupDrift = cb
369
- }
370
-
371
- /**
372
- * Report a group boundary observed on an incoming track. Cross-checks the
373
- * packet-stamped groupId against the shared `align.ts` formula and fires
374
- * the onGroupDrift callback when they disagree.
375
- *
376
- * Two input forms:
377
- * - **Ticks (preferred).** `notifyGroupBoundary(track, id, { mediaTimeTicks,
378
- * groupDurationTicks, timescale })` — pure integer math via
379
- * `align.groupIdForTicks`, no rounding anywhere.
380
- * - **Seconds (deprecated).** The 4-argument form. Quantizes both operands
381
- * to whole nanoseconds, which is exact only when `groupDurationSec` is a
382
- * whole number of nanoseconds. It is not for 33333@90k, 1001@30k or
383
- * 1024@44.1k, and there `expected` diverges by a whole group from the
384
- * second boundary onward — a false drift event on every subsequent
385
- * group, and a systematically wrong CMCD `x-bc-switch-drift-us`.
386
- *
387
- * No-op when no onGroupDrift callback is registered (avoid unnecessary work
388
- * on hot paths).
389
- *
390
- * Hot-path robustness (does NOT throw on bad inputs — the ingest stream
391
- * must not be torn down by a malformed catalog or a disposed producer):
392
- * - Invalid duration (NaN / <=0) or non-finite media time → warn + early
393
- * return (same convention as audioFallbackMs).
394
- * - Any throw out of the align formula (e.g. the safe-integer overflow
395
- * guard at ~104 days of media time on the seconds path) is caught +
396
- * logged so an unusually long-running stream cannot tear down ingest.
397
- * - Callback throws are caught + logged; ingest continues.
398
- * - Skip warnings are coalesced **per failure mode** for the lifetime
399
- * of the router (never reset, including across `dispose()`), so a hot
400
- * path cannot flood the log while a genuinely new failure mode still
401
- * gets heard. Deterministic modes get one line; a throwing consumer
402
- * callback gets a small budget because its error varies. See
403
- * `#skipWithWarning` and `GROUP_ALIGN_WARN_BUDGET`.
404
- *
405
- * Init-track filter: media time === 0 with a non-zero stamped groupId is
406
- * treated as an init/ambient track emitting pre-PTS-zero packets and is
407
- * skipped (matches Go's base-clamp intent without producing spurious
408
- * drift).
409
- *
410
- * NOTE: do NOT call from the repair path (feedRepair). Repair frames carry
411
- * the groupId they are recovering for, not a freshly-stamped one.
412
- */
413
- notifyGroupBoundary(
414
- trackName: string,
415
- packetGroupId: number,
416
- timing: GroupBoundaryTicks,
417
- ): void
418
- /**
419
- * @deprecated Pass a {@link GroupBoundaryTicks} instead. The seconds form
420
- * rounds to whole nanoseconds and reports phantom drift on catalogs whose
421
- * `groupDurationTicks / timescale` is not ns-exact.
422
- */
423
- notifyGroupBoundary(
424
- trackName: string,
425
- packetGroupId: number,
426
- mediaTimeSec: number,
427
- groupDurationSec: number,
428
- ): void
429
- notifyGroupBoundary(
430
- trackName: string,
431
- packetGroupId: number,
432
- timingOrMediaTimeSec: GroupBoundaryTicks | number,
433
- groupDurationSec?: number,
434
- ): void {
435
- if (!this.#onGroupDrift) return
436
-
437
- const resolved =
438
- typeof timingOrMediaTimeSec === 'object' && timingOrMediaTimeSec !== null
439
- ? this.#resolveTicks(trackName, timingOrMediaTimeSec)
440
- : this.#resolveSeconds(
441
- trackName,
442
- timingOrMediaTimeSec as number,
443
- groupDurationSec as number,
444
- )
445
- if (!resolved) return
446
-
447
- // Init/ambient track heuristic: mediaTime=0 with stamped groupId !== 0
448
- // is a signaling packet pre-PTS-zero, not a real drift. Skipping here
449
- // avoids every stream opening with a false drift event.
450
- if (resolved.mediaTimeSec === 0 && packetGroupId !== 0) return
451
-
452
- const expected = resolved.expected
453
- const result = driftCheck(expected, packetGroupId)
454
- if (result.kind === 'aligned') return
455
-
456
- try {
457
- this.#onGroupDrift({
458
- trackName,
459
- expectedGroupId: expected,
460
- actualGroupId: packetGroupId,
461
- deltaGroups: result.deltaGroups,
462
- mediaTimeSec: resolved.mediaTimeSec,
463
- groupDurationSec: resolved.groupDurationSec,
464
- ...(resolved.timing ? { timing: resolved.timing } : {}),
465
- })
466
- } catch (err) {
467
- // A disposed CmcdProducer (or any downstream consumer) throwing here
468
- // must NOT tear down the MoQ ingest stream. Log and continue.
469
- //
470
- // Routed through the same per-reason budget as the resolver skips: this
471
- // fires once per DRIFT EVENT, so a consumer that throws on every
472
- // boundary would otherwise flood at boundary rate — exactly the failure
473
- // mode #skipWithWarning exists to prevent, and exactly the disposed-
474
- // producer scenario this comment already cites (#329 review).
475
- this.#skipWithWarning(
476
- 'callback-threw',
477
- `[MediaRouter] onGroupDrift callback threw (track=${trackName} expected=${expected} actual=${packetGroupId}); continuing: ${(err as Error)?.message ?? err}`,
478
- )
479
- }
480
- }
481
-
482
- /**
483
- * Warn at most `GROUP_ALIGN_WARN_BUDGET[reason]` times **per reason**, across
484
- * every skip and post-emit failure on the drift path.
485
- *
486
- * Note the two call shapes: the resolvers call this *instead of* computing a
487
- * groupId, and return its `null` to skip the drift check; the `onGroupDrift`
488
- * catch calls it after the check already ran and the event was already
489
- * emitted, so there only the warn is coalesced and the `null` is discarded.
490
- *
491
- * Keyed on a short stable `reason` tag, NOT on the formatted message: the
492
- * messages interpolate track name and operand values, so message-keying
493
- * would hand a malformed stream a fresh warn slot on every boundary — the
494
- * log flood this coalescing exists to prevent.
495
- *
496
- * Per-reason rather than one shared boolean (PCL-2211, #329 review): the
497
- * budget is never reset — not by `dispose()`, not on source switch — so a
498
- * single flag means the FIRST malformed boundary of a long-running stream
499
- * permanently silences every later, genuinely different failure mode. The
500
- * throw/overflow diagnostics carry the operand values (`ticks=`, `durTicks=`,
501
- * `err.message`) an incident responder actually needs, and under one shared
502
- * flag those are precisely the ones most likely to be already spent by an
503
- * unrelated NaN at catalog load.
504
- *
505
- * A closed, bounded set of reasons times a small per-reason budget is still
506
- * bounded, so this cannot flood. See `GROUP_ALIGN_WARN_BUDGET` for why the
507
- * budget is not uniform.
508
- */
509
- #skipWithWarning(reason: GroupAlignSkipReason, message: string): null {
510
- const seen = this.#groupAlignWarnCounts.get(reason) ?? 0
511
- if (seen < GROUP_ALIGN_WARN_BUDGET[reason]) {
512
- this.#groupAlignWarnCounts.set(reason, seen + 1)
513
- console.warn(message)
514
- }
515
- return null
516
- }
517
-
518
- /**
519
- * Exact path: integers straight from the catalog, no rounding. `mediaTimeSec`
520
- * / `groupDurationSec` are derived for reporting only and never feed the
521
- * groupId computation.
522
- */
523
- #resolveTicks(
524
- trackName: string,
525
- timing: GroupBoundaryTicks,
526
- ): ResolvedBoundary | null {
527
- const { mediaTimeTicks, groupDurationTicks, timescale } = timing
528
- if (
529
- !Number.isInteger(mediaTimeTicks) ||
530
- !Number.isInteger(groupDurationTicks) ||
531
- groupDurationTicks <= 0 ||
532
- !Number.isInteger(timescale) ||
533
- timescale <= 0
534
- ) {
535
- return this.#skipWithWarning(
536
- 'invalid-tick-inputs',
537
- `[MediaRouter] notifyGroupBoundary invalid tick inputs (track=${trackName} mediaTimeTicks=${mediaTimeTicks} groupDurationTicks=${groupDurationTicks} timescale=${timescale}); skipping drift check. Pre-validate at catalog load time.`,
538
- )
539
- }
540
- try {
541
- return {
542
- expected: groupIdForTicks(mediaTimeTicks, groupDurationTicks),
543
- mediaTimeSec: mediaTimeTicks / timescale,
544
- groupDurationSec: groupDurationTicks / timescale,
545
- // Snapshot, not the caller's reference: a producer that reuses one
546
- // scratch object per boundary would otherwise retroactively mutate
547
- // every GroupDriftEvent it has already emitted. Three integers.
548
- timing: { mediaTimeTicks, groupDurationTicks, timescale },
549
- }
550
- } catch (err) {
551
- // UNREACHABLE as of today, and deliberately kept. groupIdForTicks throws
552
- // on exactly two conditions — !Number.isInteger(ticks) and
553
- // !Number.isInteger(groupDurationTicks) || groupDurationTicks <= 0 — and
554
- // the guard above pre-rejects both; Math.floor(a / b) does not throw.
555
- //
556
- // Kept because align.ts is a separate module that can grow a new
557
- // precondition (a safe-integer check, say) without this file changing,
558
- // and the no-throw contract must hold on that day too. Nobody should
559
- // write a test chasing this branch — see BLO-21176 note.
560
- //
561
- // NOTE the asymmetry this implies: the seconds path is the only one that
562
- // can actually reach its catch, because durTicks <= 0 cannot catch
563
- // Infinity and Number.isSafeInteger guards only `ticks`. That is the real
564
- // shape of the AC#5a bug, not an oversight in this resolver.
565
- return this.#skipWithWarning(
566
- 'ticks-formula-threw',
567
- `[MediaRouter] notifyGroupBoundary: groupIdForTicks threw (track=${trackName} mediaTimeTicks=${mediaTimeTicks} groupDurationTicks=${groupDurationTicks}); skipping drift check: ${(err as Error)?.message ?? err}`,
568
- )
569
- }
570
- }
571
-
572
- /**
573
- * Legacy seconds path. Quantizes to a synthetic 1e9 Hz timescale — the exact
574
- * behaviour the deprecated `align.groupIdFor` wrapper had, reproduced here so
575
- * that wrapper has no non-test callers left and can be deleted (BLO-21176).
576
- *
577
- * Inherits that wrapper's ns-rounding error; see the `@deprecated` overload.
578
- * Delete this branch once every caller passes ticks.
579
- */
580
- #resolveSeconds(
581
- trackName: string,
582
- mediaTimeSec: number,
583
- groupDurationSec: number,
584
- ): ResolvedBoundary | null {
585
- if (
586
- !Number.isFinite(groupDurationSec) ||
587
- groupDurationSec <= 0 ||
588
- !Number.isFinite(mediaTimeSec)
589
- ) {
590
- return this.#skipWithWarning(
591
- 'invalid-seconds-inputs',
592
- `[MediaRouter] notifyGroupBoundary invalid inputs (track=${trackName} mediaTimeSec=${mediaTimeSec} groupDurationSec=${groupDurationSec}); skipping drift check. Pre-validate at catalog load time.`,
593
- )
594
- }
595
- // 1e9 Hz keeps both operands inside MAX_SAFE_INTEGER for ~104 days of
596
- // media time. Past that Math.round yields a non-safe integer that
597
- // Number.isInteger still accepts, so bail explicitly rather than
598
- // silently quantizing — ingest must survive either way.
599
- const TS = 1_000_000_000
600
- const ticks = mediaTimeSec < 0 ? 0 : Math.round(mediaTimeSec * TS)
601
- const durTicks = Math.round(groupDurationSec * TS)
602
- if (durTicks <= 0) {
603
- return this.#skipWithWarning(
604
- 'sub-nanosecond-duration',
605
- `[MediaRouter] notifyGroupBoundary: groupDurationSec=${groupDurationSec} rounds to <1 tick at 1e9 Hz (track=${trackName}); skipping drift check. Pass GroupBoundaryTicks for sub-nanosecond durations.`,
606
- )
607
- }
608
- if (!Number.isSafeInteger(ticks)) {
609
- return this.#skipWithWarning(
610
- 'media-time-overflow',
611
- `[MediaRouter] notifyGroupBoundary: mediaTimeSec=${mediaTimeSec} overflows safe-integer ticks at 1e9 Hz (>~104 days, track=${trackName}); skipping drift check. Pass GroupBoundaryTicks with the catalog timescale.`,
612
- )
613
- }
614
- // Same try as #resolveTicks: a finite groupDurationSec can still overflow
615
- // the * 1e9 multiply to Infinity, which clears the durTicks <= 0 bail above
616
- // but fails Number.isInteger inside groupIdForTicks. Without this catch the
617
- // throw escapes notifyGroupBoundary and breaks its documented no-throw
618
- // contract — the one path #resolveTicks already guards and this did not.
619
- try {
620
- return {
621
- expected: groupIdForTicks(ticks, durTicks),
622
- mediaTimeSec,
623
- groupDurationSec,
624
- }
625
- } catch (err) {
626
- return this.#skipWithWarning(
627
- 'seconds-formula-threw',
628
- `[MediaRouter] notifyGroupBoundary: groupIdForTicks threw (track=${trackName} mediaTimeSec=${mediaTimeSec} groupDurationSec=${groupDurationSec} ticks=${ticks} durTicks=${durTicks}); skipping drift check: ${(err as Error)?.message ?? err}`,
629
- )
630
- }
631
- }
632
-
633
236
  get activeSource(): SourceKind { return this.#active }
634
237
 
635
238
  // ── Keyframe repair API ──────────────────────────────────────────
@@ -1,11 +1,11 @@
1
1
  import {
2
2
  parseMMTPHeader,
3
- extractMFUPayload,
4
- extractFecPayloadId,
5
- hasSourceFecPayloadId,
3
+ extractMFUPayloadWithHeader,
4
+ sourceFecPayloadIdOf,
6
5
  extractAltaTrailer,
7
6
  PACKET_TYPE_MPU,
8
7
  PACKET_TYPE_REPAIR,
8
+ type MMTPHeader,
9
9
  } from '@blockcast/mmt-base'
10
10
  import {
11
11
  MFUReassembler,
@@ -101,6 +101,19 @@ export interface PacketInfo {
101
101
  isRepair: boolean
102
102
  }
103
103
 
104
+ /**
105
+ * One parse of an MMTP packet's header, as returned by
106
+ * MmtpContainerParser.parsePacket(). Hand it back to feedParsed() so the same
107
+ * packet's header is not parsed again (BLO-36599).
108
+ */
109
+ export interface ParsedMmtpPacket {
110
+ readonly info: PacketInfo
111
+ /** parseMMTPHeader() of the packet this was parsed from. */
112
+ readonly header: MMTPHeader
113
+ /** The skipFecPayloadId option `info.fecPayloadId` was resolved under. */
114
+ readonly skipFecPayloadId: boolean
115
+ }
116
+
104
117
  export interface FrameMeta {
105
118
  /** Authored ISO-BMFF presentation time converted to microseconds. */
106
119
  timestamp: number
@@ -671,6 +684,8 @@ export class MmtpContainerParser {
671
684
  #reliableMoqStartupGate = new Map<string, number>()
672
685
  #disposed = false
673
686
  #fedObjects = 0
687
+ #reassemblerFragmentsFed = 0
688
+ #reassemblerDataUnitsReturned = 0
674
689
  #feedOutcomes = new Map<MmtpFeedOutcomeKey, number>()
675
690
  #deferredFeedOutcomes = new Map<MmtpFeedDropReason, number>()
676
691
  #lastOutcome: MmtpFeedOutcomeKey | null = null
@@ -895,6 +910,21 @@ export class MmtpContainerParser {
895
910
  return this.#lastOutcomeCount
896
911
  }
897
912
 
913
+ /**
914
+ * MFU fragments feed() handed to the reassembler, including rejected ones.
915
+ * A plain scalar a per-packet caller can difference; reading the
916
+ * reassembler's own stats is a wasm crossing on the Rust backend
917
+ * (BLO-36599).
918
+ */
919
+ get reassemblerFragmentsFed(): number {
920
+ return this.#reassemblerFragmentsFed
921
+ }
922
+
923
+ /** Data units the reassembler returned complete to feed(). */
924
+ get reassemblerDataUnitsReturned(): number {
925
+ return this.#reassemblerDataUnitsReturned
926
+ }
927
+
898
928
  #countOutcome(token: MmtpFeedOutcomeKey): void {
899
929
  const count = (this.#feedOutcomes.get(token) ?? 0) + 1
900
930
  this.#feedOutcomes.set(token, count)
@@ -949,24 +979,37 @@ export class MmtpContainerParser {
949
979
  * Returns null for malformed packets.
950
980
  */
951
981
  parseHeader(packet: Uint8Array, options?: ParseHeaderOptions): PacketInfo | null {
982
+ return this.parsePacket(packet, options)?.info ?? null
983
+ }
984
+
985
+ /**
986
+ * parseHeader() that also keeps the parsed MMTP header, so a caller that
987
+ * goes on to feedParsed() the same packet parses its header exactly once.
988
+ * The MMTP header is parsed once here and the Source FEC Payload ID is read
989
+ * from it; parseHeader() used to parse the header three times for an FEC
990
+ * source packet, and feed() repeated all of it (BLO-36599).
991
+ */
992
+ parsePacket(packet: Uint8Array, options?: ParseHeaderOptions): ParsedMmtpPacket | null {
952
993
  try {
953
994
  const header = parseMMTPHeader(packet)
954
995
  const isRepair = header.packetType === PACKET_TYPE_REPAIR
996
+ const skipFecPayloadId = options?.skipFecPayloadId === true
955
997
  const fecPayloadId =
956
- !options?.skipFecPayloadId &&
957
- !isRepair && hasSourceFecPayloadId(packet)
958
- ? extractFecPayloadId(packet)
959
- : null
998
+ !skipFecPayloadId && !isRepair ? sourceFecPayloadIdOf(packet, header) : null
960
999
  return {
961
- packetId: header.packetId,
962
- packetType: header.packetType,
963
- timestamp: header.timestamp,
964
- timestampUs: mmtpTimestampToMicros(header.timestamp),
965
- sequenceNumber: header.sequenceNumber,
966
- rapFlag: header.rapFlag,
967
- fecType: header.fecType,
968
- fecPayloadId,
969
- isRepair,
1000
+ info: {
1001
+ packetId: header.packetId,
1002
+ packetType: header.packetType,
1003
+ timestamp: header.timestamp,
1004
+ timestampUs: mmtpTimestampToMicros(header.timestamp),
1005
+ sequenceNumber: header.sequenceNumber,
1006
+ rapFlag: header.rapFlag,
1007
+ fecType: header.fecType,
1008
+ fecPayloadId,
1009
+ isRepair,
1010
+ },
1011
+ header,
1012
+ skipFecPayloadId,
970
1013
  }
971
1014
  } catch {
972
1015
  return null
@@ -975,10 +1018,32 @@ export class MmtpContainerParser {
975
1018
 
976
1019
  /** Feed a complete MMTP packet. For two-phase use, call parseHeader() first. */
977
1020
  feed(packet: Uint8Array, options?: ParseHeaderOptions): MmtpParserRecord | null {
1021
+ return this.#feedCounted(packet, options, undefined)
1022
+ }
1023
+
1024
+ /**
1025
+ * feed() for a packet this caller already ran through parsePacket(): the
1026
+ * header parse is reused instead of repeated. `parsed` must come from
1027
+ * parsePacket() of this same, unmodified packet. If it was resolved under a
1028
+ * different skipFecPayloadId option, the packet is parsed again.
1029
+ */
1030
+ feedParsed(
1031
+ packet: Uint8Array,
1032
+ parsed: ParsedMmtpPacket,
1033
+ options?: ParseHeaderOptions,
1034
+ ): MmtpParserRecord | null {
1035
+ return this.#feedCounted(packet, options, parsed)
1036
+ }
1037
+
1038
+ #feedCounted(
1039
+ packet: Uint8Array,
1040
+ options: ParseHeaderOptions | undefined,
1041
+ parsed: ParsedMmtpPacket | undefined,
1042
+ ): MmtpParserRecord | null {
978
1043
  this.#fedObjects += 1
979
1044
  let record: MmtpParserRecord | null
980
1045
  try {
981
- record = this.#feed(packet, options)
1046
+ record = this.#feed(packet, options, parsed)
982
1047
  } catch (error) {
983
1048
  // Count before rethrowing: a throw is an outcome, and leaving it
984
1049
  // uncounted would silently break the sum-to-fedObjects invariant that
@@ -992,13 +1057,22 @@ export class MmtpContainerParser {
992
1057
  return record
993
1058
  }
994
1059
 
995
- #feed(packet: Uint8Array, options?: ParseHeaderOptions): MmtpParserRecord | null {
1060
+ #feed(
1061
+ packet: Uint8Array,
1062
+ options: ParseHeaderOptions | undefined,
1063
+ preParsed: ParsedMmtpPacket | undefined,
1064
+ ): MmtpParserRecord | null {
996
1065
  if (this.#disposed) return this.#drop('disposed')
997
1066
 
998
1067
  this.cleanupTimeouts()
999
1068
 
1000
- const info = this.parseHeader(packet, options)
1001
- if (!info) return this.#drop('header-parse-failed')
1069
+ const parsed =
1070
+ preParsed !== undefined &&
1071
+ preParsed.skipFecPayloadId === (options?.skipFecPayloadId === true)
1072
+ ? preParsed
1073
+ : this.parsePacket(packet, options)
1074
+ if (!parsed) return this.#drop('header-parse-failed')
1075
+ const info = parsed.info
1002
1076
 
1003
1077
  if (info.packetType !== PACKET_TYPE_MPU) {
1004
1078
  return {
@@ -1030,7 +1104,7 @@ export class MmtpContainerParser {
1030
1104
  }
1031
1105
  }
1032
1106
 
1033
- const extraction = extractMFUPayload(packet, {
1107
+ const extraction = extractMFUPayloadWithHeader(packet, parsed.header, {
1034
1108
  skipFecId: options?.skipFecPayloadId,
1035
1109
  })
1036
1110
  if (!extraction) return this.#drop('mfu-extract-failed')
@@ -1152,6 +1226,7 @@ export class MmtpContainerParser {
1152
1226
  }
1153
1227
 
1154
1228
  let assembled: ReassembledMFU | null
1229
+ this.#reassemblerFragmentsFed++
1155
1230
  try {
1156
1231
  assembled = this.#reassembler.addFragment({
1157
1232
  fragmentationIndicator: mpu.fragmentationIndicator,
@@ -1197,6 +1272,7 @@ export class MmtpContainerParser {
1197
1272
  fragmentCounter: mpu.fragmentCounter,
1198
1273
  }
1199
1274
  }
1275
+ this.#reassemblerDataUnitsReturned++
1200
1276
 
1201
1277
  const movieFragmentSequenceNumber = assembled.movieFragmentSequenceNumber
1202
1278
  const sampleNumber = assembled.sampleNumber