@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
@@ -526,12 +526,13 @@ export function buildAudioInitSegment(
526
526
  timescale?: number,
527
527
  trackId = 1,
528
528
  ): Uint8Array {
529
- // trackId only: this reaches the same uint32 tkhd/trex/mvhd fields as the
530
- // video builder. The audio *timescale* is deliberately left unchecked here —
531
- // wrapAudioSample branches on its exact value, so constraining it belongs
532
- // with that path rather than in this range fix.
529
+ // Validated here as well as in setAudioTimescale, for the same reason the
530
+ // video builder is: this function is exported from the package index, so a
531
+ // direct caller reaches the same uint32 tkhd / trex / mdhd / mvhd fields
532
+ // without passing through the class.
533
533
  assertTrackId(trackId, 'audio trackId')
534
534
  const ts = timescale ?? sampleRate
535
+ assertTimescale(ts, 'audio timescale')
535
536
 
536
537
  if (!asc) {
537
538
  const freqTable = [96000, 88200, 64000, 48000, 44100, 32000, 24000, 22050, 16000, 12000, 11025, 8000, 7350]
@@ -771,8 +772,12 @@ export class MmtpToCmaf {
771
772
 
772
773
  buildAudioInit(sampleRate: number, channels: number, asc?: Uint8Array, timescale?: number) {
773
774
  const ts = timescale ?? sampleRate
775
+ // Build first, then publish, as the video path does: buildAudioInitSegment
776
+ // validates, so assigning the field first would leave a rejected timescale
777
+ // latched on the instance with no init segment to match it.
778
+ const init = buildAudioInitSegment(sampleRate, channels, asc, ts)
774
779
  this.#audioTimescale = ts
775
- this.#audioInitSegment = buildAudioInitSegment(sampleRate, channels, asc, ts)
780
+ this.#audioInitSegment = init
776
781
  }
777
782
 
778
783
  get videoInitSegment(): Uint8Array | null { return this.#videoInitSegment }
@@ -878,8 +883,17 @@ export class MmtpToCmaf {
878
883
  #audioTimescale = 1_000_000
879
884
 
880
885
  /** Set audio timescale to match the init segment's mdhd timescale.
881
- * Call after appending the real encoder init (FT=0 ftyp+moov). */
882
- setAudioTimescale(timescale: number) { this.#audioTimescale = timescale }
886
+ * Call after appending the real encoder init (FT=0 ftyp+moov).
887
+ * Fails closed on a value the mdhd uint32 cannot hold, as the video paths
888
+ * already do. wrapAudioSample rescales the authored composition offset by
889
+ * this value, so the two failure modes are both silent: a 0 multiplies
890
+ * every authored offset to 0 — indistinguishable from a feed that authored
891
+ * none — while a value above uint32 scales the trun to a timescale the
892
+ * mdhd cannot declare, since it is emitted with setUint32 modulo 2^32. */
893
+ setAudioTimescale(timescale: number) {
894
+ assertTimescale(timescale, 'audio timescale')
895
+ this.#audioTimescale = timescale
896
+ }
883
897
 
884
898
  // Audio sample counter for drift-free baseMediaDecodeTime.
885
899
  // AAC frames are exactly 1024 samples at sampleRate. Using sequential
@@ -30,7 +30,12 @@ declare const process: { env: Record<string, string | undefined> } | undefined;
30
30
  * where the IPv6 form requires P=1 + T=1 (the `3` nibble) AND the
31
31
  * 16-bit reserved-zero second hextet per RFC 3306 §4 / RFC 4607.
32
32
  * - port in 1..65535
33
- * - tracks non-empty; per-track packetId in 0..65535
33
+ * - tracks non-empty; per-track packetId in 1..65535
34
+ * - packetId 0 (`MMTP_SIGNALING_PACKET_ID`) is the MMTP signaling flow
35
+ * (FFmpeg `moq_mmt` sends the AL-FEC message 0x0203 on it into the same
36
+ * multicast group) and is refused for a track with its own kind,
37
+ * `signaling_packet_id`. The kind string matches cast's
38
+ * `multicast_input.rs` so the two ports report the same reason.
34
39
  * - packetIds unique within an endpoint
35
40
  * - (sourceAddress, groupAddress, port) tuple unique across endpoints
36
41
  * - bandwidth (if present) > 0
@@ -40,6 +45,7 @@ declare const process: { env: Record<string, string | undefined> } | undefined;
40
45
  * @see .planning/drafts/blo-3323-multicast-catalog-source-of-truth.md
41
46
  */
42
47
 
48
+ import { MMTP_PACKET_ID_MAX, MMTP_SIGNALING_PACKET_ID } from "@blockcast/mmt-base";
43
49
  import {
44
50
  type AmtDiscovery,
45
51
  type MulticastCatalogConfig,
@@ -90,6 +96,12 @@ export type MulticastInputErrorKind =
90
96
  | "empty_tracks"
91
97
  | "invalid_track_name"
92
98
  | "invalid_packet_id"
99
+ /**
100
+ * A track advertised on `MMTP_SIGNALING_PACKET_ID` (0), the MMTP signaling
101
+ * flow. Distinct from `invalid_packet_id` so the reason is legible: 0 is a
102
+ * well-formed 16-bit value, it is just not a track's to claim.
103
+ */
104
+ | "signaling_packet_id"
93
105
  | "duplicate_packet_id"
94
106
  | "duplicate_endpoint_tuple"
95
107
  | "invalid_bandwidth"
@@ -200,11 +212,19 @@ function validateEndpoint(
200
212
  `endpoint[${idx}] track name must be a non-empty string`,
201
213
  );
202
214
  }
203
- if (!Number.isInteger(t.packetId) || t.packetId < 0 || t.packetId > 65535) {
215
+ if (t.packetId === MMTP_SIGNALING_PACKET_ID) {
216
+ throw new MulticastInputError(
217
+ "signaling_packet_id",
218
+ idx,
219
+ `endpoint[${idx}] track "${t.name}" packetId ${t.packetId} is the MMTP signaling flow ` +
220
+ `and must not be advertised for a track; packetId must be 1..${MMTP_PACKET_ID_MAX}`,
221
+ );
222
+ }
223
+ if (!Number.isInteger(t.packetId) || t.packetId < 1 || t.packetId > MMTP_PACKET_ID_MAX) {
204
224
  throw new MulticastInputError(
205
225
  "invalid_packet_id",
206
226
  idx,
207
- `endpoint[${idx}] track "${t.name}" packetId must be 0..65535; got ${t.packetId}`,
227
+ `endpoint[${idx}] track "${t.name}" packetId must be 1..${MMTP_PACKET_ID_MAX}; got ${t.packetId}`,
208
228
  );
209
229
  }
210
230
  if (seenPids.has(t.packetId)) {
@@ -26,7 +26,12 @@ import {
26
26
  import { MulticastTransport } from "./multicast-transport.js";
27
27
  import { computeFecDeliveryWindowMs } from "./track-session.js";
28
28
  import { deriveFecInterleaveDepth, FecBlockMapper } from "@blockcast/mmt-fec";
29
- import type { FecWorkerClient, FecTrackStats } from "@blockcast/fec-worker";
29
+ import type {
30
+ FecBlockSnapshot,
31
+ FecTrackConfig,
32
+ FecTrackStats,
33
+ FecWorkerClient,
34
+ } from "@blockcast/fec-worker";
30
35
  import type { MfuReassemblerBackend } from "./mfu-reassembler.js";
31
36
  import type { MfuReassemblyPolicy } from "./mfu-reassembly-policy.js";
32
37
  import type {
@@ -108,6 +113,14 @@ export interface MulticastManagerOptions {
108
113
  catalogTrackName?: string,
109
114
  ) => ManifestObjectIdentity | null;
110
115
  resolveManifestIdentityForRoute?: ManifestIdentityResolver;
116
+ /**
117
+ * Also write every repair lifecycle event to the console as one
118
+ * `REPAIR_LIFECYCLE_LOG_PREFIX` JSON line. Off unless asked for: the lines
119
+ * are serialized on the page thread for every failed block and repair step
120
+ * (and again for an attached inspector), and addRepairLifecycleObserver is
121
+ * the lifecycle API. Enable only for interactive debugging (BLO-36599).
122
+ */
123
+ logRepairLifecycle?: boolean;
111
124
  }
112
125
 
113
126
  export interface RepairStreamIdentity {
@@ -469,6 +482,62 @@ type FecDiagnosticsGateway = {
469
482
  reportFecDiagnostics?: (snapshot: unknown) => void;
470
483
  };
471
484
 
485
+ /** Active-block tail forwarded to the bridge; mirrors the IWA's bound. */
486
+ const FEC_DIAGNOSTIC_BLOCK_TAIL = 8;
487
+
488
+ /**
489
+ * Project a Worker block snapshot onto the bridge/IWA `subscription_diagnostics`
490
+ * contract. The contract names the per-block repair symbol count `t`; the
491
+ * Worker's `repairCount` is the same quantity (P) under its unambiguous name.
492
+ */
493
+ function projectFecDiagnosticBlock(block: FecBlockSnapshot) {
494
+ return {
495
+ sbn: block.sbn,
496
+ state: block.state,
497
+ sourceReceived: block.sourceReceived,
498
+ repairReceived: block.repairReceived,
499
+ k: block.k,
500
+ t: block.repairCount,
501
+ firstSymbolTs: block.firstSymbolTs,
502
+ lastSymbolTs: block.lastSymbolTs,
503
+ ...(block.completedTs === undefined ? {} : { completedTs: block.completedTs }),
504
+ deadlineTs: block.deadlineTs,
505
+ altaVerified: block.altaVerified,
506
+ relayBlockSigValid: block.relayBlockSigValid,
507
+ };
508
+ }
509
+
510
+ /**
511
+ * Project the Worker track config onto the bridge/IWA contract. Every key
512
+ * below is a named field of that contract (see pim-multicast-gateway
513
+ * `normalizeSubscriptionDiagnostics`); `k`/`t`/`symbolSize` are three
514
+ * independent axes there, so `repairCount` is emitted as `t` and never
515
+ * confused with the symbol size. Worker-internal fields such as
516
+ * `deliveryWindowMs` are not part of the contract and are not forwarded.
517
+ */
518
+ function projectFecDiagnosticConfig(config: FecTrackConfig) {
519
+ return {
520
+ codec: config.codec,
521
+ trackName: config.trackName,
522
+ trackType: config.trackType,
523
+ ...(config.resolution === undefined
524
+ ? {}
525
+ : { resolution: { w: config.resolution.w, h: config.resolution.h } }),
526
+ ...(config.framerate === undefined ? {} : { framerate: config.framerate }),
527
+ ...(config.sampleRate === undefined ? {} : { sampleRate: config.sampleRate }),
528
+ ...(config.algorithm === undefined ? {} : { algorithm: config.algorithm }),
529
+ k: config.k,
530
+ t: config.repairCount,
531
+ symbolSize: config.symbolSize,
532
+ interleaveDepth: config.interleaveDepth,
533
+ interleaveMs: config.interleaveMs,
534
+ fecMode: config.fecMode,
535
+ ...(config.repairTrack === undefined ? {} : { repairTrack: config.repairTrack }),
536
+ altaEnabled: config.altaEnabled,
537
+ relayBlockSigEnabled: config.relayBlockSigEnabled,
538
+ };
539
+ }
540
+
472
541
  function publishFecDiagnostics(packetId: number, stats: FecTrackStats): boolean {
473
542
  const gateway = (globalThis as typeof globalThis & {
474
543
  multicast?: FecDiagnosticsGateway;
@@ -478,17 +547,16 @@ function publishFecDiagnostics(packetId: number, stats: FecTrackStats): boolean
478
547
  // Keep the control-plane payload bounded and JSON-safe. The Worker snapshot
479
548
  // already bounds active blocks; the bridge needs only the current block tail
480
549
  // and stable counters, not decoder internals or authentication failure text.
550
+ // The shape is the IWA contract, not the Worker's internal types: spreading
551
+ // FecTrackConfig raw once shipped `repairCount` with no `t`, and the IWA
552
+ // discarded every report ("fec_track.stats.config.t must be a finite
553
+ // non-negative number").
481
554
  const snapshot = {
482
555
  version: 1,
483
556
  packetId,
484
557
  observedAt: Date.now(),
485
558
  stats: {
486
- config: {
487
- ...stats.config,
488
- resolution: stats.config.resolution
489
- ? { ...stats.config.resolution }
490
- : undefined,
491
- },
559
+ config: projectFecDiagnosticConfig(stats.config),
492
560
  sourceSymbols: stats.sourceSymbols,
493
561
  repairSymbols: stats.repairSymbols,
494
562
  blocksComplete: stats.blocksComplete,
@@ -497,7 +565,7 @@ function publishFecDiagnostics(packetId: number, stats: FecTrackStats): boolean
497
565
  greenFillFrames: stats.greenFillFrames,
498
566
  recoveryRate: stats.recoveryRate,
499
567
  liveSbn: stats.liveSbn,
500
- blocks: stats.blocks.slice(-8).map((block) => ({ ...block })),
568
+ blocks: stats.blocks.slice(-FEC_DIAGNOSTIC_BLOCK_TAIL).map(projectFecDiagnosticBlock),
501
569
  interleaveWindowBlocks: stats.interleaveWindowBlocks,
502
570
  avgRecoveryMs: stats.avgRecoveryMs,
503
571
  maxRecoveryMs: stats.maxRecoveryMs,
@@ -583,6 +651,7 @@ export class MulticastManager {
583
651
 
584
652
  /** Causal repair events; observers own any retention they require. */
585
653
  #repairLifecycleObservers = new Set<RepairLifecycleObserver>();
654
+ readonly #logRepairLifecycle: boolean;
586
655
 
587
656
  #trackResetObservers = new Set<
588
657
  (packetId: number, catalogTrackName: string) => void
@@ -594,6 +663,7 @@ export class MulticastManager {
594
663
  | null = null;
595
664
 
596
665
  constructor(options?: MulticastManagerOptions) {
666
+ this.#logRepairLifecycle = options?.logRepairLifecycle === true;
597
667
  this.#fec = new FECManager();
598
668
  this.#fec.addFecStatsObserver((packetId, stats) => {
599
669
  try {
@@ -1638,9 +1708,11 @@ export class MulticastManager {
1638
1708
  ) as RepairLifecycleEvent;
1639
1709
  // Serialize before invoking observers so a re-entrant observer cannot log
1640
1710
  // a resolution before the request that caused it.
1641
- console.info(
1642
- `${REPAIR_LIFECYCLE_LOG_PREFIX}${JSON.stringify(immutableEvent)}`,
1643
- );
1711
+ if (this.#logRepairLifecycle) {
1712
+ console.info(
1713
+ `${REPAIR_LIFECYCLE_LOG_PREFIX}${JSON.stringify(immutableEvent)}`,
1714
+ );
1715
+ }
1644
1716
  for (const observer of this.#repairLifecycleObservers) {
1645
1717
  try {
1646
1718
  observer(immutableEvent);
@@ -9,7 +9,7 @@ import {
9
9
  type WindowMulticastGateway,
10
10
  type WindowMulticastSubscription,
11
11
  } from '@blockcast/mmt-transport'
12
- import { parseMMTPHeader } from '@blockcast/mmt-base'
12
+ import { MMTP_SIGNALING_PACKET_ID, readMMTPPacketId } from '@blockcast/mmt-base'
13
13
 
14
14
  export interface MulticastTransportConfig {
15
15
  sourceAddress: string
@@ -42,6 +42,13 @@ export interface MulticastTransportStats {
42
42
  packetsDroppedUnregisteredPid: number
43
43
  /** MMTP header did not parse; the packet ID is unknown, so it cannot be attributed. */
44
44
  packetsDroppedUnparseable: number
45
+ /**
46
+ * packet_id 0, the MMTP signaling flow. Expected traffic on a protected
47
+ * session (moq_mmt sends the AL-FEC message on it), so it is counted apart
48
+ * from the unregistered-PID fault counter and never takes a
49
+ * `droppedPacketIds` slot.
50
+ */
51
+ packetsDroppedSignaling: number
45
52
  }
46
53
 
47
54
  /**
@@ -84,7 +91,11 @@ export class MulticastTransport<TPacketContext = never> {
84
91
  #resolvedTransport: ResolvedMulticastTransport | undefined
85
92
  #videoConfirmed = false
86
93
  #audioConfirmed = false
94
+ // One armed no-packets timer per silence window (BLO-36599). Packets only
95
+ // record #lastPacketAtMs; the timer re-arms for the remainder when it wakes
96
+ // inside the window, instead of a clear+set pair on every packet.
87
97
  #watchdog: ReturnType<typeof setTimeout> | null = null
98
+ #lastPacketAtMs = 0
88
99
  #failbackWindowMs: number | null = null
89
100
  #onTakeover: (() => void) | null = null
90
101
  #onFailback: (() => void) | null = null
@@ -94,6 +105,7 @@ export class MulticastTransport<TPacketContext = never> {
94
105
  bytesReceived: 0,
95
106
  packetsDroppedUnregisteredPid: 0,
96
107
  packetsDroppedUnparseable: 0,
108
+ packetsDroppedSignaling: 0,
97
109
  }
98
110
  #droppedPidCounts = new Map<number, number>()
99
111
  #packetIds: ReadonlySet<number> | null = null
@@ -218,6 +230,13 @@ export class MulticastTransport<TPacketContext = never> {
218
230
  )
219
231
  }
220
232
  this.#failbackWindowMs = windowMs
233
+ // An armed timer was scheduled against the previous window; re-derive its
234
+ // wake-up from the last packet so a narrower window is not enforced late.
235
+ if (this.#watchdog !== null) {
236
+ clearTimeout(this.#watchdog)
237
+ const silentMs = performance.now() - this.#lastPacketAtMs
238
+ this.#armWatchdog(Math.max(0, Math.ceil(windowMs - silentMs)))
239
+ }
221
240
  }
222
241
 
223
242
  get stats(): MulticastTransportStats {
@@ -259,17 +278,26 @@ export class MulticastTransport<TPacketContext = never> {
259
278
  }
260
279
 
261
280
  #acceptPacket(packet: Uint8Array): boolean {
262
- if (!this.#packetIds) return true
263
- let packetId: number
264
- try {
265
- // This early parse is intentional: rejected PIDs must not affect page
266
- // delivery, receive statistics, or the failback liveness watchdog.
267
- packetId = parseMMTPHeader(packet).packetId
268
- } catch {
281
+ // This early read is intentional: rejected PIDs must not affect page
282
+ // delivery, receive statistics, or the failback liveness watchdog. It
283
+ // refuses exactly what parseMMTPHeader refuses but builds no header
284
+ // object; the router parses the header once, later (BLO-36599).
285
+ const packetId = readMMTPPacketId(packet)
286
+ if (packetId === null) {
287
+ // Without an allow-list there is no filter to enforce, so an unparseable
288
+ // packet keeps flowing to the router as before.
289
+ if (!this.#packetIds) return true
269
290
  this.#stats.packetsDroppedUnparseable++
270
291
  return false
271
292
  }
272
- if (this.#packetIds.has(packetId)) return true
293
+ // packet_id 0 is the MMTP signaling flow and never a track's. Drop it even
294
+ // when the join carried no allow-list (a legacy catalog whose tracks omit
295
+ // packetId): the discard rule must not depend on how the catalog was written.
296
+ if (packetId === MMTP_SIGNALING_PACKET_ID) {
297
+ this.#stats.packetsDroppedSignaling++
298
+ return false
299
+ }
300
+ if (!this.#packetIds || this.#packetIds.has(packetId)) return true
273
301
  this.#recordUnregisteredPidDrop(packetId)
274
302
  return false
275
303
  }
@@ -288,7 +316,7 @@ export class MulticastTransport<TPacketContext = never> {
288
316
  // and it is silent in every downstream counter.
289
317
  console.warn(
290
318
  `[MulticastTransport] Dropping packetId=${packetId} (0x${packetId.toString(16)}): ` +
291
- `not in the advertised set [${[...this.#packetIds!].join(', ')}]. ` +
319
+ `not in the advertised set [${[...(this.#packetIds ?? [])].join(', ')}]. ` +
292
320
  `If this is an FEC repair leg, the catalog is not advertising its packetId.`,
293
321
  )
294
322
  }
@@ -301,21 +329,32 @@ export class MulticastTransport<TPacketContext = never> {
301
329
  }
302
330
  }
303
331
 
332
+ /** Note liveness now; arm the no-packets timer if none is armed. */
304
333
  #resetWatchdog(): void {
305
- if (this.#watchdog) clearTimeout(this.#watchdog)
334
+ this.#lastPacketAtMs = performance.now()
335
+ if (this.#watchdog !== null) return
306
336
  if (!this.#onFailback) return
307
337
  if (this.#failbackWindowMs === null) {
308
338
  throw new Error(
309
339
  '[MulticastTransport] Failback watchdog requires a catalog-derived window',
310
340
  )
311
341
  }
342
+ this.#armWatchdog(this.#failbackWindowMs)
343
+ }
344
+
345
+ #armWatchdog(delayMs: number): void {
312
346
  this.#watchdog = setTimeout(() => {
313
- if (!this.#disposed && this.#onFailback) {
314
- console.warn(
315
- `[MulticastTransport] No packets for ${this.#failbackWindowMs}ms; failing back to MoQ`,
316
- )
317
- this.#onFailback()
347
+ this.#watchdog = null
348
+ if (this.#disposed || !this.#onFailback || this.#failbackWindowMs === null) return
349
+ const silentMs = performance.now() - this.#lastPacketAtMs
350
+ if (silentMs < this.#failbackWindowMs) {
351
+ this.#armWatchdog(Math.ceil(this.#failbackWindowMs - silentMs))
352
+ return
318
353
  }
319
- }, this.#failbackWindowMs)
354
+ console.warn(
355
+ `[MulticastTransport] No packets for ${this.#failbackWindowMs}ms; failing back to MoQ`,
356
+ )
357
+ this.#onFailback()
358
+ }, delayMs)
320
359
  }
321
360
  }
@@ -719,6 +719,22 @@ export class SessionManager {
719
719
  * Under the documented usage -- false once at setup, true once the subscribe
720
720
  * settles -- the two coincide.
721
721
  *
722
+ * The gate is on the ENTRY into `joining`, and false cannot take back a
723
+ * deadline already running: the `true -> false` edge arms the warn below and
724
+ * clears nothing. So set it false BEFORE the `joining` entry it is meant to
725
+ * gate. A host that instead flipped it false after a `transportFailed()`
726
+ * failover had already entered `joining` would leave the full deadline
727
+ * counting against a subscribe that had not begun -- BLO-34289 again, on the
728
+ * failover edge. Clearing running deadlines on that edge is deliberately NOT
729
+ * done: this flag is manager-wide, so one transport's brief false would
730
+ * cancel an unrelated track's live deadline and then re-arm it at FULL length
731
+ * on the next activation (armDeferredJoinDeadline sees `joining` + a null
732
+ * timer and cannot tell a cleared deadline from a deferred one). Every
733
+ * unrelated transport blip would restart the whole budget, so under repeated
734
+ * failover a track that should have timed out is extended indefinitely and
735
+ * never advances. Only a false that never returns true loses the timer
736
+ * outright, and JOIN_DEFER_WARN_MS already covers that.
737
+ *
722
738
  * Leaving this false is not free: see JOIN_DEFER_WARN_MS.
723
739
  */
724
740
  get joinActive(): boolean {
@@ -110,11 +110,13 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
110
110
  #nextStreamIdentity = 1
111
111
  #streamIdentityByKey = new Map<string, number>()
112
112
  #streamNameByIdentity = new Map<number, string>()
113
- #coreTotalFragments = 0
114
- #rejectedBeforeCore = 0
113
+ // Every fragment handed to the core, including ones it rejected. This is
114
+ // what `coreTotal + rejectedBeforeCore` computed with a core stats() round
115
+ // trip before and after every fragment (BLO-36599).
116
+ #offeredFragments = 0
115
117
  #rejectedFragments = 0
116
118
 
117
- readonly stats: ReassemblerStats = {
119
+ readonly #stats: ReassemblerStats = {
118
120
  totalFragments: 0,
119
121
  reassembledMFUs: 0,
120
122
  rejectedFragments: 0,
@@ -143,6 +145,16 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
143
145
  return this.#timeoutMs
144
146
  }
145
147
 
148
+ /**
149
+ * Host-observable reassembly statistics, read from the core when asked.
150
+ * Reading them is a wasm crossing plus six counter getters, so neither
151
+ * addFragment nor the router's per-packet path refreshes them (BLO-36599).
152
+ */
153
+ get stats(): ReassemblerStats {
154
+ this.#refreshStats()
155
+ return this.#stats
156
+ }
157
+
146
158
  set timeoutMs(timeoutMs: number | null) {
147
159
  if (timeoutMs !== null && (!Number.isFinite(timeoutMs) || timeoutMs <= 0)) {
148
160
  throw new Error('[WasmMfuReassembler] timeoutMs must be a finite number > 0')
@@ -191,22 +203,18 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
191
203
  }
192
204
 
193
205
  let output: MmtWasmReassembledMfu | undefined
194
- const coreTotalBefore = this.#coreTotalFragments
195
206
  try {
196
207
  output = this.#core.add_fragment(this.#now(), wasmFragment)
197
208
  } catch (error) {
198
209
  const rejection = this.#asReassemblyError(error)
199
210
  if (rejection === null) throw error
200
- this.#refreshStats()
201
- if (this.#coreTotalFragments === coreTotalBefore) this.#rejectedBeforeCore++
211
+ this.#offeredFragments++
202
212
  this.#rejectedFragments++
203
- this.stats.totalFragments = this.#coreTotalFragments + this.#rejectedBeforeCore
204
- this.stats.rejectedFragments = this.#rejectedFragments
205
- this.#scheduleCleanup()
213
+ this.#ensureCleanupArmed()
206
214
  throw rejection
207
215
  }
208
- this.#refreshStats()
209
- this.#scheduleCleanup()
216
+ this.#offeredFragments++
217
+ this.#ensureCleanupArmed()
210
218
  if (!output) return null
211
219
 
212
220
  try {
@@ -272,7 +280,6 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
272
280
  if (streamIdentity === undefined) return
273
281
  this.#clearCleanupTimer()
274
282
  this.#core.reset_stream(streamIdentity)
275
- this.#refreshStats()
276
283
  this.#scheduleCleanup()
277
284
  }
278
285
 
@@ -282,10 +289,8 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
282
289
  this.#nextStreamIdentity = 1
283
290
  this.#streamIdentityByKey.clear()
284
291
  this.#streamNameByIdentity.clear()
285
- this.#coreTotalFragments = 0
286
- this.#rejectedBeforeCore = 0
292
+ this.#offeredFragments = 0
287
293
  this.#rejectedFragments = 0
288
- this.#refreshStats()
289
294
  }
290
295
 
291
296
  get pendingCount(): number {
@@ -305,25 +310,24 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
305
310
  // Detailed fragment coordinates remain internal to the Rust core. Counts
306
311
  // and health statistics stay available to MmtpRouter diagnostics.
307
312
  pendingSamples: [],
308
- stats: { ...this.stats },
313
+ stats: { ...this.#stats },
309
314
  }
310
315
  }
311
316
 
312
317
  #refreshStats(): void {
313
318
  const stats = this.#core.stats()
314
- this.#coreTotalFragments = asNumber(stats.total_fragments)
315
- this.stats.totalFragments = this.#coreTotalFragments + this.#rejectedBeforeCore
316
- this.stats.reassembledMFUs = asNumber(stats.reassembled_mfus)
317
- this.stats.rejectedFragments = this.#rejectedFragments
318
- this.stats.timedOutMFUs = asNumber(stats.timed_out_mfus)
319
+ this.#stats.totalFragments = this.#offeredFragments
320
+ this.#stats.reassembledMFUs = asNumber(stats.reassembled_mfus)
321
+ this.#stats.rejectedFragments = this.#rejectedFragments
322
+ this.#stats.timedOutMFUs = asNumber(stats.timed_out_mfus)
319
323
  // `evictedMemoryLimit` is documented as every incomplete MFU discarded to
320
324
  // enforce the memory bound, and the pure-TypeScript engine counts its
321
325
  // clock-free evictions there. The Rust core splits the same concept across
322
326
  // two counters, so both are summed here — otherwise the identical stat
323
327
  // would mean different things depending on which engine a host loaded.
324
- this.stats.evictedMemoryLimit =
328
+ this.#stats.evictedMemoryLimit =
325
329
  asNumber(stats.evicted_memory_limit) + asNumber(stats.evicted_data_units ?? 0)
326
- this.stats.outOfOrderFragments = asNumber(stats.out_of_order_fragments)
330
+ this.#stats.outOfOrderFragments = asNumber(stats.out_of_order_fragments)
327
331
  stats.free?.()
328
332
  }
329
333
 
@@ -355,6 +359,19 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
355
359
  )
356
360
  }
357
361
 
362
+ /**
363
+ * Arm the cleanup wake-up only when none is armed. A fragment can only add
364
+ * a data unit whose deadline is its own arrival plus the one configured
365
+ * timeout, which is never earlier than the deadline already armed; the
366
+ * armed wake-up re-reads the core's next deadline after cleanup. Only a
367
+ * timeout change can move the next deadline earlier, and the timeoutMs
368
+ * setter re-arms for that. This replaces a next_timeout_at() crossing and a
369
+ * clear+set timer pair on every fragment (BLO-36599).
370
+ */
371
+ #ensureCleanupArmed(): void {
372
+ if (this.#cleanupTimer === null) this.#scheduleCleanup()
373
+ }
374
+
358
375
  #scheduleCleanup(): void {
359
376
  this.#clearCleanupTimer()
360
377
  if (this.#timeoutMs === null) return
@@ -364,7 +381,6 @@ export class WasmMfuReassembler implements MfuReassemblerBackend {
364
381
  this.#cleanupTimer = setTimeout(() => {
365
382
  this.#cleanupTimer = null
366
383
  this.#core.cleanup_timeouts(this.#now())
367
- this.#refreshStats()
368
384
  this.#scheduleCleanup()
369
385
  }, delay)
370
386
  }
@@ -9,6 +9,8 @@ Negative fixtures are the migration worklist and MUST fail:
9
9
 
10
10
  - `legacy-selection-params.json`: rendition fields must be flat.
11
11
  - `missing-mmtp-fields.json`: MMTP tracks require mode, timescale, and duration.
12
+ - `multicast-packet-id-signaling.json`: an endpoint track's `packetId` is
13
+ 1..65535; `packetId` 0 is the MMTP signaling flow and is never a track's.
12
14
  - `network-source-object.json`: `networkSource` is always an array.
13
15
  - `repair-track-legacy-shape.json`: repair tracks use `packaging: "fec-repair"`.
14
16
  - `fec-enhancement-repair-removed.json`: `fec.enhancementRepair` does not exist;
@@ -0,0 +1,26 @@
1
+ {
2
+ "version": 1,
3
+ "streamingFormat": "mmtp",
4
+ "streamingFormatVersion": "draft-ramadan-moq-mmt-00",
5
+ "tracks": [
6
+ {
7
+ "name": "video",
8
+ "packaging": "mmtp",
9
+ "mmtpMode": "mfu",
10
+ "timescale": 90000,
11
+ "groupDurationMs": 1000
12
+ }
13
+ ],
14
+ "multicast": {
15
+ "endpoints": [
16
+ {
17
+ "protocol": "ssm",
18
+ "sourceAddress": "192.0.2.1",
19
+ "groupAddress": "232.1.1.1",
20
+ "port": 5000,
21
+ "tracks": [{ "name": "video", "packetId": 0 }]
22
+ }
23
+ ],
24
+ "networkSource": [{ "type": "amt", "discovery": "driad" }]
25
+ }
26
+ }
@@ -139,6 +139,17 @@
139
139
  "error_code": "multicast_packet_id",
140
140
  "catalog": {"version":1,"tracks":[{"name":"video","packaging":"cmaf","isLive":true,"codec":"avc1.640028"}],"multicast":{"endpoints":[{"sourceAddress":"192.0.2.1","groupAddress":"232.0.0.1","port":5004,"tracks":[{"name":"video","packetId":65536}]}]}}
141
141
  },
142
+ {
143
+ "name": "multicast packet ID 0 is the MMTP signaling flow",
144
+ "valid": false,
145
+ "error_code": "multicast_packet_id",
146
+ "catalog": {"version":1,"tracks":[{"name":"video","packaging":"cmaf","isLive":true,"codec":"avc1.640028"}],"multicast":{"endpoints":[{"sourceAddress":"192.0.2.1","groupAddress":"232.0.0.1","port":5004,"tracks":[{"name":"video","packetId":0}]}]}}
147
+ },
148
+ {
149
+ "name": "multicast packet ID at the 16-bit ceiling",
150
+ "valid": true,
151
+ "catalog": {"version":1,"tracks":[{"name":"video","packaging":"cmaf","isLive":true,"codec":"avc1.640028"}],"multicast":{"endpoints":[{"sourceAddress":"192.0.2.1","groupAddress":"232.0.0.1","port":5004,"tracks":[{"name":"video","packetId":65535}]}]}}
152
+ },
142
153
  {
143
154
  "name": "auth extension is preserved but not validated here",
144
155
  "valid": true,