@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
@@ -12,7 +12,12 @@
12
12
  * @packageDocumentation
13
13
  */
14
14
 
15
- import { parseMMTPHeader } from "@blockcast/mmt-base";
15
+ import {
16
+ MMTP_SIGNALING_PACKET_ID,
17
+ parseMMTPHeader,
18
+ parseMoqRepairFrameWithHeader,
19
+ type MMTPHeader,
20
+ } from "@blockcast/mmt-base";
16
21
  import { isMfuReassemblyError } from "./mfu-reassembler.js";
17
22
  import type {
18
23
  MfuReassemblerBackend,
@@ -25,7 +30,6 @@ import { scaleAuthoredTiming, type AuthoredTiming } from "./authored-timing.js";
25
30
  import {
26
31
  processFecBlock,
27
32
  processFecSymbol,
28
- parseRepairPacket,
29
33
  FecBlockMapper,
30
34
  type ProcessFecBlockResult,
31
35
  } from "@blockcast/mmt-fec";
@@ -34,7 +38,11 @@ import {
34
38
  type BlockAssemblerConfig,
35
39
  type CmafBlockSample,
36
40
  } from "./cmaf-block-assembler.js";
37
- import { MmtpContainerParser, isMfuKeyframeMetadata } from "./mmtp-container-parser.js";
41
+ import {
42
+ MmtpContainerParser,
43
+ isMfuKeyframeMetadata,
44
+ type ParsedMmtpPacket,
45
+ } from "./mmtp-container-parser.js";
38
46
  import { type TrackRole } from "./carp-catalog.js";
39
47
  import type {
40
48
  ManifestAuthMode,
@@ -128,17 +136,67 @@ export interface MmtpIngressContext {
128
136
  tracks: readonly Readonly<{ name: string; packetId: number }>[];
129
137
  }
130
138
 
139
+ /** What one ingress track list says about one packet ID. */
140
+ interface IngressPacketEntry {
141
+ /** The one non-empty catalog name the list gives the packet ID, if exactly one. */
142
+ readonly name?: string;
143
+ /** More than one non-empty catalog name claims the packet ID. */
144
+ readonly ambiguous: boolean;
145
+ }
146
+
147
+ function indexIngressTracks(
148
+ tracks: MmtpIngressContext["tracks"],
149
+ ): ReadonlyMap<number, IngressPacketEntry> {
150
+ const names = new Map<number, Set<string>>();
151
+ for (const track of tracks) {
152
+ let packetNames = names.get(track.packetId);
153
+ if (!packetNames) {
154
+ packetNames = new Set();
155
+ names.set(track.packetId, packetNames);
156
+ }
157
+ if (track.name.length > 0) packetNames.add(track.name);
158
+ }
159
+ const index = new Map<number, IngressPacketEntry>();
160
+ for (const [packetId, packetNames] of names) {
161
+ index.set(
162
+ packetId,
163
+ packetNames.size === 1
164
+ ? { name: packetNames.values().next().value, ambiguous: false }
165
+ : { ambiguous: packetNames.size > 1 },
166
+ );
167
+ }
168
+ return index;
169
+ }
170
+
171
+ /**
172
+ * Index of each frozen ingress track list (BLO-36599). MulticastManager.join
173
+ * freezes the list it hands the transport, which passes that same list with
174
+ * every packet, so the packetId -> name mapping is derived once per join
175
+ * rather than filtered up to four times per packet. A list that is not frozen
176
+ * may still change, so it is indexed afresh on every packet as before.
177
+ */
178
+ const frozenIngressIndexes = new WeakMap<object, ReadonlyMap<number, IngressPacketEntry>>();
179
+
180
+ function ingressEntry(
181
+ ingress: MmtpIngressContext,
182
+ packetId: number,
183
+ ): IngressPacketEntry | undefined {
184
+ const tracks = ingress.tracks;
185
+ if (!Object.isFrozen(tracks)) return indexIngressTracks(tracks).get(packetId);
186
+ let index = frozenIngressIndexes.get(tracks);
187
+ if (!index) {
188
+ index = indexIngressTracks(tracks);
189
+ frozenIngressIndexes.set(tracks, index);
190
+ }
191
+ return index.get(packetId);
192
+ }
193
+
131
194
  function catalogTrackNameForPacket(
132
195
  ingress: MmtpIngressContext | undefined,
133
196
  packetId: number,
134
197
  ): string | undefined {
135
198
  if (!ingress) return undefined;
136
- const names = new Set(
137
- ingress.tracks
138
- .filter((track) => track.packetId === packetId && track.name.length > 0)
139
- .map((track) => track.name),
140
- );
141
- return names.size === 1 ? names.values().next().value : undefined;
199
+ return ingressEntry(ingress, packetId)?.name;
142
200
  }
143
201
 
144
202
  function hasAmbiguousCatalogTrackName(
@@ -146,21 +204,18 @@ function hasAmbiguousCatalogTrackName(
146
204
  packetId: number,
147
205
  ): boolean {
148
206
  if (!ingress) return false;
149
- const names = new Set(
150
- ingress.tracks
151
- .filter((track) => track.packetId === packetId && track.name.length > 0)
152
- .map((track) => track.name),
153
- );
154
- return names.size > 1;
207
+ return ingressEntry(ingress, packetId)?.ambiguous === true;
155
208
  }
156
209
 
157
210
  function ingressHasPacketId(
158
211
  ingress: MmtpIngressContext | undefined,
159
212
  packetId: number,
160
213
  ): boolean {
214
+ // packet_id 0 is the MMTP signaling flow, never a track's, whatever the ingress.
215
+ if (packetId === MMTP_SIGNALING_PACKET_ID) return false;
161
216
  // Direct/legacy callers have no catalog-backed ingress policy to enforce.
162
217
  // MulticastManager supplies a populated context whenever packetIds are selected.
163
- return ingress === undefined || ingress.tracks.some((track) => track.packetId === packetId);
218
+ return ingress === undefined || ingressEntry(ingress, packetId) !== undefined;
164
219
  }
165
220
 
166
221
  /** Callback for decoded video/audio frames. */
@@ -202,6 +257,49 @@ type DirectAudioCursor = {
202
257
  sequenceNumber: number;
203
258
  };
204
259
 
260
+ /**
261
+ * Per-stream duplicate ledgers, keyed by wire numbers rather than strings.
262
+ */
263
+ interface StreamLedgers {
264
+ /** JSON tuple naming the stream; see #mediaStreamKey. */
265
+ readonly key: string;
266
+ /**
267
+ * packet_sequence_numbers already received on the direct source path.
268
+ * Recovered FEC blocks contain all K source symbols, so skip direct-path
269
+ * duplicates even when the source frame is still buffered by parser
270
+ * reordering.
271
+ */
272
+ readonly sourceSeqs: Set<number>;
273
+ /** packet_sequence_numbers already handed to the track packet callback. */
274
+ readonly routedSeqs: Set<number>;
275
+ /**
276
+ * Source FEC Payload IDs (SS_ID) already parsed for playback. An overlap
277
+ * copy and its multicast twin carry the same symbol, and the copy never
278
+ * feeds FEC, so FEC's first-arrival check cannot dedup the pair.
279
+ */
280
+ readonly parsedSymbols: Set<number>;
281
+ }
282
+
283
+ // Each ledger keeps its newest PACKET_LEDGER_RETAINED entries once it passes
284
+ // PACKET_LEDGER_HIGH_WATER (covers ~62 blocks at K=32/30fps). FEC recovery
285
+ // completes within the catalog-derived holdback window, so older entries
286
+ // cannot be useful for duplicate suppression. These are the values the
287
+ // router-wide string ledgers used; they now apply per stream.
288
+ const PACKET_LEDGER_HIGH_WATER = 4000;
289
+ const PACKET_LEDGER_RETAINED = 2000;
290
+
291
+ /** Add `value`, keeping the newest PACKET_LEDGER_RETAINED past the high water. */
292
+ function rememberInLedger(ledger: Set<number>, value: number): void {
293
+ ledger.add(value);
294
+ if (ledger.size <= PACKET_LEDGER_HIGH_WATER) return;
295
+ // Set iteration is insertion order: delete the oldest in place.
296
+ let excess = ledger.size - PACKET_LEDGER_RETAINED;
297
+ for (const oldest of ledger) {
298
+ if (excess-- <= 0) break;
299
+ ledger.delete(oldest);
300
+ }
301
+ }
302
+
205
303
  const DIRECT_RECOVERED_VIDEO_QUEUE_LIMIT = 512;
206
304
  const DIRECT_RECOVERED_AUDIO_QUEUE_LIMIT = 512;
207
305
 
@@ -237,6 +335,10 @@ export interface FECManagerLike {
237
335
  /** Feed a source symbol to the FEC decoder for a given track.
238
336
  * Returns recovered block bytes if recovery completes, else null.
239
337
  *
338
+ * `symbolData` is the complete MMTP packet without its Source FEC Payload
339
+ * ID, unpadded and possibly a view into the received packet. The manager
340
+ * zero-pads it to the packet's own symbol size T.
341
+ *
240
342
  * Optional `alta` carries the detached ALTA authenticator extracted from
241
343
  * the MMTP header-extension trailer (08-07 Path 2) — present on signed
242
344
  * source packets, absent on relay-reassembled / unsigned streams. When
@@ -432,11 +534,13 @@ export class MmtpRouter {
432
534
  #trackSynced = new Set<string>();
433
535
  #droppedPreSyncVideo = new Set<string>();
434
536
 
435
- // Dedup: packetId-scoped packetSequenceNumbers already received via direct source path.
436
- // Recovered FEC blocks contain all K source symbols, so skip direct-path
437
- // duplicates even when the source frame is still buffered by parser reordering.
438
- #sourcePktSeqs = new Set<string>();
439
- #routedPacketSeqs = new Set<string>();
537
+ // One entry per physical stream (packetId, catalog track name): its stable
538
+ // JSON key and its per-packet duplicate ledgers. The ledgers used to be
539
+ // three router-wide Sets of "<streamKey>:<coordinates>" strings, so every
540
+ // packet built and hashed up to three strings, and resetTrack() scanned
541
+ // every retained key by prefix (BLO-36599). They now hold the wire numbers
542
+ // themselves, and a reset clears one stream's Sets.
543
+ #streams = new Map<number, Map<string | undefined, StreamLedgers>>();
440
544
 
441
545
  // Live WebCodecs callbacks cannot accept late recovered inter-frame video.
442
546
  // MSE recovery routes through CmafBlockAssembler and can reorder by block; the
@@ -745,7 +849,17 @@ export class MmtpRouter {
745
849
 
746
850
  getDiagnostics(): Record<number, ParserDiagnostics> {
747
851
  const out: Record<number, ParserDiagnostics> = {};
852
+ // The reassembler is shared by every stream; its occupancy is one reading
853
+ // taken now, not a per-packet snapshot (BLO-36599).
854
+ const status = this.#parserDiagnostics.size > 0
855
+ ? this.#parser.reassembler.getStatus()
856
+ : null;
748
857
  for (const [key, diag] of this.#parserDiagnostics) {
858
+ if (status) {
859
+ diag.pendingBuffers = status.bufferedMFUs;
860
+ diag.pendingFragments = status.pendingFragments;
861
+ diag.pendingSamples = status.pendingSamples;
862
+ }
749
863
  const packetId = this.#packetIdFromStreamKey(key);
750
864
  const existing = out[packetId];
751
865
  if (!existing) {
@@ -1110,6 +1224,40 @@ export class MmtpRouter {
1110
1224
  this.#processMMTP(packet, source, manifestIdentity, false, ingress);
1111
1225
  }
1112
1226
 
1227
+ /**
1228
+ * Feed a reliable MoQ duplicate of a source packet that the multicast leg
1229
+ * also carries, during make-before-break overlap.
1230
+ *
1231
+ * The copy is parsed for playback (attributed to "moq") so a pending
1232
+ * multicast decoder can warm. For an FEC-tagged packet the router keeps a
1233
+ * per-symbol (SBN/ESI) parse ledger, so whichever of it and its multicast
1234
+ * twin arrives first is parsed and the second is not. The MFU reassembler
1235
+ * cannot be that dedup: complete (FI=0) MFUs bypass its #emitted set.
1236
+ *
1237
+ * The ledger exists only where a symbol coordinate does: a packet with no
1238
+ * FEC payload ID, or a router with no FEC manager, has none, so it and its
1239
+ * twin are BOTH parsed. On an audio track that delivers the sample twice
1240
+ * (#emitDirectSourceAudio counts the regression and still emits). The
1241
+ * intended deployment is safe because the multicast leg is FEC-protected,
1242
+ * so its media packets carry the ID; the untagged timing packets
1243
+ * (init/moof) take this path too, where a re-parse is benign. Do not feed
1244
+ * untagged media through here.
1245
+ *
1246
+ * The copy never enters FEC
1247
+ * accounting: no `feedSymbolFromSource`, `trackBlock` or
1248
+ * `feedSourceSymbol`. Block completion and the repair deadline therefore
1249
+ * follow the multicast leg alone, and a multicast erasure still starves its
1250
+ * block and requests repair. Feeding the copy through `feedPacket` instead
1251
+ * would let it close the block, hiding exactly the loss repair exists for.
1252
+ *
1253
+ * MoQ unicast fallback is not an overlap copy: it is the only source, so it
1254
+ * uses `feedPacket(packet, "moq")` and counts toward completion.
1255
+ */
1256
+ feedOverlapCopy(packet: Uint8Array, ingress?: MmtpIngressContext): void {
1257
+ if (this.#disposed) return;
1258
+ this.#processMMTP(packet, "moq", undefined, false, ingress, true);
1259
+ }
1260
+
1113
1261
  /**
1114
1262
  * Feed a repair packet from MoQ (reliable QUIC) — parses MMTP repair
1115
1263
  * header and delegates to FECManager for FEC recovery.
@@ -1121,14 +1269,20 @@ export class MmtpRouter {
1121
1269
  ): void {
1122
1270
  if (this.#disposed) return;
1123
1271
 
1124
- const parsed = parseRepairPacket(packet);
1272
+ // One header parse per packet, as on the multicast repair branch: mmt-fec's
1273
+ // parseRepairPacket() parsed it once more before this parse (BLO-36599).
1274
+ let header: MMTPHeader;
1275
+ try {
1276
+ header = parseMMTPHeader(packet);
1277
+ } catch {
1278
+ return;
1279
+ }
1280
+ const parsed = parseMoqRepairFrameWithHeader(packet, header);
1125
1281
  if (!parsed) return;
1126
1282
 
1127
1283
  // A dedicated repair track can carry a packet ID that differs from the
1128
1284
  // media packet ID. The subscribing track supplies the authoritative owner.
1129
- const header = packet.length >= 4 ? parseMMTPHeader(packet) : null;
1130
- const repairPacketId = header?.packetId;
1131
- if (repairPacketId == null) return;
1285
+ const repairPacketId = header.packetId;
1132
1286
 
1133
1287
  const hintedOwner =
1134
1288
  ownerPacketIdHint != null && this.#classifyPacketId(ownerPacketIdHint) !== null
@@ -1166,7 +1320,7 @@ export class MmtpRouter {
1166
1320
  ownerPacketId,
1167
1321
  repairSbn,
1168
1322
  repairEsi,
1169
- parsed.repairData,
1323
+ parsed.symbolData,
1170
1324
  "moq",
1171
1325
  catalogTrackName,
1172
1326
  )
@@ -1179,14 +1333,14 @@ export class MmtpRouter {
1179
1333
  parsed.ssStart,
1180
1334
  parsed.ssbLength,
1181
1335
  parsed.rsId,
1182
- parsed.repairData,
1336
+ parsed.symbolData,
1183
1337
  )
1184
1338
  : this.#fecManager.feedRepairSymbol(
1185
1339
  ownerPacketId,
1186
1340
  parsed.ssStart,
1187
1341
  parsed.ssbLength,
1188
1342
  parsed.rsId,
1189
- parsed.repairData,
1343
+ parsed.symbolData,
1190
1344
  catalogTrackName,
1191
1345
  );
1192
1346
  if (recovered) {
@@ -1347,19 +1501,10 @@ export class MmtpRouter {
1347
1501
  this.#lastDirectEmittedAudioCursorByStream.delete(streamKey);
1348
1502
  this.#pendingDirectRecoveredAudioByStream.delete(streamKey);
1349
1503
  this.#manifestRecoveryQueues.delete(streamKey);
1350
- for (const packetSeqs of [this.#sourcePktSeqs, this.#routedPacketSeqs]) {
1351
- for (const key of packetSeqs) {
1352
- try {
1353
- const [keyPacketId, keyTrackName] = JSON.parse(key);
1354
- if (keyPacketId === packetId && keyTrackName === catalogTrackName) {
1355
- packetSeqs.delete(key);
1356
- }
1357
- } catch {
1358
- // Internal keys are JSON tuples; malformed legacy keys do not belong
1359
- // to a named physical stream and are left untouched.
1360
- }
1361
- }
1362
- }
1504
+ const ledgers = this.#stream(packetId, catalogTrackName);
1505
+ ledgers.sourceSeqs.clear();
1506
+ ledgers.routedSeqs.clear();
1507
+ ledgers.parsedSymbols.clear();
1363
1508
  const assemblersToReset = new Set<CmafBlockAssembler>();
1364
1509
  const exactAssembler = this.#mseAssemblers.get(streamKey);
1365
1510
  if (exactAssembler) assemblersToReset.add(exactAssembler);
@@ -1376,8 +1521,7 @@ export class MmtpRouter {
1376
1521
  this.#disposed = true;
1377
1522
  this.cancelKeyframeLostTimer();
1378
1523
  this.#parser.dispose();
1379
- this.#sourcePktSeqs.clear();
1380
- this.#routedPacketSeqs.clear();
1524
+ this.#streams.clear();
1381
1525
  this.#trackPacketCallbacks.clear();
1382
1526
  this.#latestVideoSeqByStream.clear();
1383
1527
  this.#lastDirectSourceVideoTsByStream.clear();
@@ -1499,9 +1643,13 @@ export class MmtpRouter {
1499
1643
  manifestIdentity?: ManifestObjectIdentity,
1500
1644
  manifestAdmitted = false,
1501
1645
  ingress?: MmtpIngressContext,
1646
+ overlapCopy = false,
1502
1647
  ): void {
1503
- const info = this.#parser.parseHeader(packet);
1504
- if (!info) return;
1648
+ // One header parse per packet: the parser reuses it in feedParsed()
1649
+ // below instead of parsing the same header again (BLO-36599).
1650
+ const parsed = this.#parser.parsePacket(packet);
1651
+ if (!parsed) return;
1652
+ const info = parsed.info;
1505
1653
  if (source === "multicast" && !ingressHasPacketId(ingress, info.packetId)) {
1506
1654
  debugRouter(
1507
1655
  `[MmtpRouter] Dropping multicast packet pid=${info.packetId}: absent from ingress tracks`,
@@ -1552,7 +1700,7 @@ export class MmtpRouter {
1552
1700
  };
1553
1701
  const authenticated = info.fecPayloadId ? packet.subarray(0, packet.length - 4) : packet;
1554
1702
  this.#manifestVerifier.admitObject(identity, authenticated, () => {
1555
- if (!this.#disposed) this.#processMMTP(packet, source, identity, true, ingress);
1703
+ if (!this.#disposed) this.#processMMTP(packet, source, identity, true, ingress, overlapCopy);
1556
1704
  });
1557
1705
  return;
1558
1706
  }
@@ -1567,8 +1715,10 @@ export class MmtpRouter {
1567
1715
 
1568
1716
  if (info.isRepair) {
1569
1717
  // Repair packet — per ISO 23008-1 §C.5.3, carries (SS_Start, SSB_length, RS_ID).
1570
- const parsed = parseRepairPacket(packet);
1571
- if (!parsed) return;
1718
+ // Read from the header parsed above rather than parsing it again
1719
+ // (BLO-36599).
1720
+ const repair = parseMoqRepairFrameWithHeader(packet, parsed.header);
1721
+ if (!repair) return;
1572
1722
 
1573
1723
  const ownerPacketId = this.#resolveRepairOwnerPacketId(info.packetId, ingress);
1574
1724
  if (ownerPacketId != null && this.#fecManager) {
@@ -1577,23 +1727,23 @@ export class MmtpRouter {
1577
1727
  const count = this.#repairPidCounts[info.packetId]!;
1578
1728
  if (count <= 2 || count % 500 === 0) {
1579
1729
  console.log(
1580
- `[MC-PKT] pid=${info.packetId} repairOwner=${ownerPacketId} type=${info.packetType} count=${count} ssbLength=${parsed.ssbLength} len=${packet.length}`,
1730
+ `[MC-PKT] pid=${info.packetId} repairOwner=${ownerPacketId} type=${info.packetType} count=${count} ssbLength=${repair.ssbLength} len=${packet.length}`,
1581
1731
  );
1582
1732
  }
1583
1733
 
1584
1734
  // NOTE: Do NOT call trackBlock for repair packets. Only source symbols
1585
1735
  // should count toward block completion — repair inflates blocksClean stats
1586
1736
  // and masks blocks that actually needed FEC recovery.
1587
- const repairSbn = this.#deriveRepairSbn(parsed.ssStart, parsed.ssbLength, ownerPacketId);
1737
+ const repairSbn = this.#deriveRepairSbn(repair.ssStart, repair.ssbLength, ownerPacketId);
1588
1738
  if (repairSbn === null) return;
1589
- const repairEsi = this.#kForPacket(ownerPacketId) + parsed.rsId;
1739
+ const repairEsi = this.#kForPacket(ownerPacketId) + repair.rsId;
1590
1740
 
1591
1741
  if (
1592
1742
  !this.#feedFecTransportSymbol(
1593
1743
  ownerPacketId,
1594
1744
  repairSbn,
1595
1745
  repairEsi,
1596
- parsed.repairData,
1746
+ repair.symbolData,
1597
1747
  source,
1598
1748
  catalogTrackNameForPacket(ingress, ownerPacketId),
1599
1749
  )
@@ -1615,17 +1765,17 @@ export class MmtpRouter {
1615
1765
  const recovered = repairCatalogTrackName === undefined
1616
1766
  ? this.#fecManager.feedRepairSymbol(
1617
1767
  ownerPacketId,
1618
- parsed.ssStart,
1619
- parsed.ssbLength,
1620
- parsed.rsId,
1621
- parsed.repairData,
1768
+ repair.ssStart,
1769
+ repair.ssbLength,
1770
+ repair.rsId,
1771
+ repair.symbolData,
1622
1772
  )
1623
1773
  : this.#fecManager.feedRepairSymbol(
1624
1774
  ownerPacketId,
1625
- parsed.ssStart,
1626
- parsed.ssbLength,
1627
- parsed.rsId,
1628
- parsed.repairData,
1775
+ repair.ssStart,
1776
+ repair.ssbLength,
1777
+ repair.rsId,
1778
+ repair.symbolData,
1629
1779
  repairCatalogTrackName,
1630
1780
  );
1631
1781
  if (recovered) {
@@ -1695,6 +1845,7 @@ export class MmtpRouter {
1695
1845
  | null = null;
1696
1846
  let sourceSymbolAccepted = false;
1697
1847
  let sourceSymbolTrackable = false;
1848
+ let parseSourceSymbol = false;
1698
1849
  const catalogTrackName = catalogTrackNameForPacket(ingress, info.packetId);
1699
1850
  if (catalogTrackName !== undefined) {
1700
1851
  const names = this.#catalogTrackNamesByPacketId.get(info.packetId) ?? new Set();
@@ -1726,7 +1877,21 @@ export class MmtpRouter {
1726
1877
  // Complete-packet symbols larger than T cannot be decoded but still
1727
1878
  // represent a source-symbol arrival, so trackBlock counts them below.
1728
1879
 
1729
- if (oversized) {
1880
+ let overlapBlockCompleted = false;
1881
+ if (overlapCopy) {
1882
+ // Playback only. The multicast twin still feeds FEC when it
1883
+ // arrives. The per-symbol parse ledger below parses whichever copy
1884
+ // arrives first and drops the second; the MFU reassembler cannot,
1885
+ // because complete (FI=0) MFUs bypass its #emitted set. A completed
1886
+ // block stays authoritative, as it does for FEC input.
1887
+ overlapBlockCompleted = catalogTrackName === undefined
1888
+ ? this.#fecManager.isBlockCompleted(coords.sbn, info.packetId)
1889
+ : this.#fecManager.isBlockCompleted(
1890
+ coords.sbn,
1891
+ info.packetId,
1892
+ catalogTrackName,
1893
+ );
1894
+ } else if (oversized) {
1730
1895
  // Oversized packet — not FEC-encoded by FFmpeg, skip FEC feed.
1731
1896
  // Still emitted via parser.feed() below (direct path).
1732
1897
  sourceSymbolAccepted = this.#feedFecTransportSymbol(
@@ -1739,13 +1904,11 @@ export class MmtpRouter {
1739
1904
  );
1740
1905
  sourceSymbolTrackable = sourceSymbolAccepted;
1741
1906
  } else {
1742
- let symbolData: Uint8Array;
1743
- if (symbolSize > 0 && rawSymbol.length < symbolSize) {
1744
- symbolData = new Uint8Array(symbolSize);
1745
- symbolData.set(rawSymbol);
1746
- } else {
1747
- symbolData = rawSymbol;
1748
- }
1907
+ // FECManager zero-pads a short symbol to T itself and then owns that
1908
+ // buffer outright, so it can transfer it to the FEC Worker without
1909
+ // copying it again. Padding here as well cost a second T-byte
1910
+ // allocation and copy per short packet (BLO-36599).
1911
+ const symbolData = rawSymbol;
1749
1912
 
1750
1913
  sourceSymbolAccepted = this.#feedFecTransportSymbol(
1751
1914
  info.packetId,
@@ -1761,6 +1924,11 @@ export class MmtpRouter {
1761
1924
  }
1762
1925
  }
1763
1926
 
1927
+ // First copy wins per symbol, in either arrival order.
1928
+ parseSourceSymbol =
1929
+ (overlapCopy ? !overlapBlockCompleted : sourceSymbolAccepted) &&
1930
+ !this.#stream(info.packetId, catalogTrackName).parsedSymbols.has(fecId.ssId);
1931
+
1764
1932
  // Compute FEC block info for the MSE assembler.
1765
1933
  fecInfo = { sbn: coords.sbn, esi: coords.esi, oversized };
1766
1934
  }
@@ -1769,7 +1937,13 @@ export class MmtpRouter {
1769
1937
  // of a worker-recovered fragment has the same SBN/ESI and fragment
1770
1938
  // counter; feeding it again can make the MFU buffer non-contiguous even
1771
1939
  // when FI=1..3 were already complete. Non-FEC packets still always flow.
1772
- if (!this.#fecManager || !info.fecPayloadId || sourceSymbolAccepted) {
1940
+ if (!this.#fecManager || !info.fecPayloadId || parseSourceSymbol) {
1941
+ if (this.#fecManager && info.fecPayloadId) {
1942
+ rememberInLedger(
1943
+ this.#stream(info.packetId, catalogTrackName).parsedSymbols,
1944
+ info.fecPayloadId.ssId,
1945
+ );
1946
+ }
1773
1947
  this.#noteSourcePacketSeq(
1774
1948
  info.packetId,
1775
1949
  info.sequenceNumber,
@@ -1783,7 +1957,7 @@ export class MmtpRouter {
1783
1957
  this.#feedViaParser(packet, info, fecInfo, {
1784
1958
  source,
1785
1959
  catalogTrackName,
1786
- });
1960
+ }, parsed);
1787
1961
  }
1788
1962
 
1789
1963
  // Deferred trackBlock (BLO-3035 layer 4 race fix). Fire AFTER
@@ -1900,9 +2074,14 @@ export class MmtpRouter {
1900
2074
  deliveryProvenance?: MmtpDeliveryProvenance;
1901
2075
  catalogTrackName?: string;
1902
2076
  },
2077
+ parsed?: ParsedMmtpPacket,
1903
2078
  ): void {
1904
2079
  const diag = this.#diagFor(info.packetId, parserOptions?.catalogTrackName);
1905
- const before = this.#parser.reassembler.getStatus();
2080
+ // Plain parser counters, not reassembler.getStatus(): on the wasm backend
2081
+ // each status read is a stats() crossing, and this runs for every packet
2082
+ // (BLO-36599). Buffer occupancy is read once, in getDiagnostics().
2083
+ const fragmentsBefore = this.#parser.reassemblerFragmentsFed;
2084
+ const reassembledBefore = this.#parser.reassemblerDataUnitsReturned;
1906
2085
  diag.packets++;
1907
2086
  diag.lastPacketLength = packet.byteLength;
1908
2087
  diag.lastSequenceNumber = info.sequenceNumber;
@@ -1910,25 +2089,24 @@ export class MmtpRouter {
1910
2089
  this.#currentFecInfo = fecInfo;
1911
2090
  this.#currentSeqNum = info.sequenceNumber;
1912
2091
  try {
1913
- this.#parser.feed(packet, {
2092
+ const feedOptions = {
1914
2093
  skipFecPayloadId: parserOptions?.skipFecPayloadId,
1915
2094
  recovered: parserOptions?.recovered,
1916
2095
  source: parserOptions?.source,
1917
2096
  deliveryProvenance: parserOptions?.deliveryProvenance,
1918
2097
  catalogTrackName: parserOptions?.catalogTrackName,
1919
- });
2098
+ };
2099
+ if (parsed) this.#parser.feedParsed(packet, parsed, feedOptions);
2100
+ else this.#parser.feed(packet, feedOptions);
1920
2101
  } finally {
1921
2102
  this.#currentFecInfo = undefined;
1922
2103
  }
1923
- const after = this.#parser.reassembler.getStatus();
1924
- const fragmentDelta = after.stats.totalFragments - before.stats.totalFragments;
1925
- const reassembledDelta = after.stats.reassembledMFUs - before.stats.reassembledMFUs;
2104
+ const fragmentDelta = this.#parser.reassemblerFragmentsFed - fragmentsBefore;
2105
+ const reassembledDelta =
2106
+ this.#parser.reassemblerDataUnitsReturned - reassembledBefore;
1926
2107
  if (fragmentDelta > 0) diag.fragments += fragmentDelta;
1927
2108
  else diag.noFragment++;
1928
2109
  if (reassembledDelta > 0) diag.reassembled += reassembledDelta;
1929
- diag.pendingBuffers = after.bufferedMFUs;
1930
- diag.pendingFragments = after.pendingFragments;
1931
- diag.pendingSamples = after.pendingSamples;
1932
2110
  }
1933
2111
 
1934
2112
  #feedFecTransportSymbol(
@@ -2024,19 +2202,18 @@ export class MmtpRouter {
2024
2202
  catalogTrackName?: string,
2025
2203
  ): void {
2026
2204
  if (packetSequenceNumber === undefined || !Number.isFinite(packetSequenceNumber)) return;
2027
- this.#sourcePktSeqs.add(
2028
- this.#packetSeqKey(packetId, packetSequenceNumber, catalogTrackName),
2205
+ rememberInLedger(
2206
+ this.#stream(packetId, catalogTrackName).sourceSeqs,
2207
+ packetSequenceNumber,
2029
2208
  );
2030
- // Eviction: keep the most recent 2000 entries (covers ~62 blocks at K=32/30fps).
2031
- // FEC recovery completes within the catalog-derived holdback window, so older
2032
- // sequence numbers cannot be useful for duplicate suppression.
2033
- if (this.#sourcePktSeqs.size > 4000) {
2034
- const iter = this.#sourcePktSeqs.values();
2035
- for (let i = 0; i < 2000; i++) iter.next();
2036
- const keep = new Set<string>();
2037
- for (const v of iter) keep.add(v);
2038
- this.#sourcePktSeqs = keep;
2039
- }
2209
+ }
2210
+
2211
+ #sourceSeqReceived(
2212
+ packetId: number,
2213
+ packetSequenceNumber: number,
2214
+ catalogTrackName?: string,
2215
+ ): boolean {
2216
+ return this.#stream(packetId, catalogTrackName).sourceSeqs.has(packetSequenceNumber);
2040
2217
  }
2041
2218
 
2042
2219
  #routeTrackPacket(
@@ -2051,16 +2228,9 @@ export class MmtpRouter {
2051
2228
  if (!Number.isFinite(packetSequenceNumber)) return;
2052
2229
  const callback = this.#trackPacketCallbacks.get(packetId);
2053
2230
  if (!callback) return;
2054
- const key = this.#packetSeqKey(packetId, packetSequenceNumber, meta.catalogTrackName);
2055
- if (this.#routedPacketSeqs.has(key)) return;
2056
- this.#routedPacketSeqs.add(key);
2057
- if (this.#routedPacketSeqs.size > 4000) {
2058
- const iter = this.#routedPacketSeqs.values();
2059
- for (let i = 0; i < 2000; i++) iter.next();
2060
- const keep = new Set<string>();
2061
- for (const value of iter) keep.add(value);
2062
- this.#routedPacketSeqs = keep;
2063
- }
2231
+ const routedSeqs = this.#stream(packetId, meta.catalogTrackName).routedSeqs;
2232
+ if (routedSeqs.has(packetSequenceNumber)) return;
2233
+ rememberInLedger(routedSeqs, packetSequenceNumber);
2064
2234
  callback(packet, {
2065
2235
  packetId,
2066
2236
  packetSequenceNumber,
@@ -2086,8 +2256,33 @@ export class MmtpRouter {
2086
2256
  return latest !== undefined && packetSequenceNumber <= latest;
2087
2257
  }
2088
2258
 
2259
+ /**
2260
+ * JSON tuple naming one physical stream. Built several times per packet, so
2261
+ * each (packetId, catalog name) pair is serialized once and reused; the set
2262
+ * of pairs is bounded by the catalog (BLO-36599).
2263
+ */
2089
2264
  #mediaStreamKey(packetId: number, catalogTrackName?: string): string {
2090
- return JSON.stringify([packetId, catalogTrackName ?? null]);
2265
+ return this.#stream(packetId, catalogTrackName).key;
2266
+ }
2267
+
2268
+ /** The (packetId, catalog name) stream's key and duplicate ledgers. */
2269
+ #stream(packetId: number, catalogTrackName?: string): StreamLedgers {
2270
+ let byName = this.#streams.get(packetId);
2271
+ if (!byName) {
2272
+ byName = new Map();
2273
+ this.#streams.set(packetId, byName);
2274
+ }
2275
+ let stream = byName.get(catalogTrackName);
2276
+ if (stream === undefined) {
2277
+ stream = {
2278
+ key: JSON.stringify([packetId, catalogTrackName ?? null]),
2279
+ sourceSeqs: new Set(),
2280
+ routedSeqs: new Set(),
2281
+ parsedSymbols: new Set(),
2282
+ };
2283
+ byName.set(catalogTrackName, stream);
2284
+ }
2285
+ return stream;
2091
2286
  }
2092
2287
 
2093
2288
  #packetIdFromStreamKey(key: string): number {
@@ -2162,14 +2357,6 @@ export class MmtpRouter {
2162
2357
  return { authoredTiming, timestamp: scaled.timestamp, mmtpTimestamp };
2163
2358
  }
2164
2359
 
2165
- #packetSeqKey(
2166
- packetId: number,
2167
- packetSequenceNumber: number,
2168
- catalogTrackName?: string,
2169
- ): string {
2170
- return JSON.stringify([packetId, catalogTrackName ?? null, packetSequenceNumber]);
2171
- }
2172
-
2173
2360
  #pendingRecoveredKey(meta: RoutedFrameMeta): string {
2174
2361
  return `${meta.timestamp}:${meta.packetSequenceNumber ?? ""}`;
2175
2362
  }
@@ -2687,9 +2874,7 @@ export class MmtpRouter {
2687
2874
  // Single-packet MFU. Dedup against source path so frames aren't
2688
2875
  // emitted twice. The direct source frame may still be buffered by the
2689
2876
  // parser reorder window, so use source-received sequence numbers.
2690
- if (this.#sourcePktSeqs.has(
2691
- this.#packetSeqKey(ownerPacketId, sym.packetSequenceNumber, catalogTrackName),
2692
- )) {
2877
+ if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {
2693
2878
  dedupedAgainstSource++;
2694
2879
  continue;
2695
2880
  }
@@ -2750,9 +2935,7 @@ export class MmtpRouter {
2750
2935
  // already accepted on the direct path. Re-feeding those fragments as
2751
2936
  // recovered would replace their original attribution in the shared
2752
2937
  // reassembler and overstate repairedPacketSequenceNumbers.
2753
- if (this.#sourcePktSeqs.has(
2754
- this.#packetSeqKey(ownerPacketId, sym.packetSequenceNumber, catalogTrackName),
2755
- )) {
2938
+ if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {
2756
2939
  dedupedAgainstSource++;
2757
2940
  continue;
2758
2941
  }
@@ -2922,9 +3105,7 @@ export class MmtpRouter {
2922
3105
  // FI=0 (single-packet MFU) bypasses it. Without this check, recovery
2923
3106
  // can re-emit a source frame that is only held in the reorder buffer,
2924
3107
  // producing duplicate timestamps when the source path later flushes.
2925
- if (this.#sourcePktSeqs.has(
2926
- this.#packetSeqKey(ownerPacketId, sym.packetSequenceNumber, catalogTrackName),
2927
- )) {
3108
+ if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {
2928
3109
  dedupedAgainstSource++;
2929
3110
  continue;
2930
3111
  }
@@ -2975,9 +3156,7 @@ export class MmtpRouter {
2975
3156
  });
2976
3157
  } else {
2977
3158
  // Fragment of a multi-packet MFU — must go through reassembler
2978
- if (this.#sourcePktSeqs.has(
2979
- this.#packetSeqKey(ownerPacketId, sym.packetSequenceNumber, catalogTrackName),
2980
- )) {
3159
+ if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {
2981
3160
  dedupedAgainstSource++;
2982
3161
  continue;
2983
3162
  }
@@ -3072,9 +3251,7 @@ export class MmtpRouter {
3072
3251
  // (parity with video FI=0 path at line 993). Prevents re-delivering audio frames
3073
3252
  // with duplicate timestamps — doubled samples in the FIFO ring buffer corrupt the
3074
3253
  // 1kHz test tone (pitch/energy instability in FFT spectrum).
3075
- if (this.#sourcePktSeqs.has(
3076
- this.#packetSeqKey(ownerPacketId, sym.packetSequenceNumber, catalogTrackName),
3077
- )) {
3254
+ if (this.#sourceSeqReceived(ownerPacketId, sym.packetSequenceNumber, catalogTrackName)) {
3078
3255
  dedupedAgainstSource++;
3079
3256
  continue;
3080
3257
  }