@blockcast/mmt-container 2.2.0-main.da2e7cd1dd5d → 2.2.0-main.e1bebe787bc9

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 (97) hide show
  1. package/README.md +5 -2
  2. package/dist/block-policy.d.ts +55 -13
  3. package/dist/block-policy.d.ts.map +1 -1
  4. package/dist/block-policy.js +104 -32
  5. package/dist/block-policy.js.map +2 -2
  6. package/dist/browser-runtime.js +1573 -214
  7. package/dist/browser-runtime.js.map +3 -3
  8. package/dist/carp-catalog.js.map +2 -2
  9. package/dist/catalog-fec-params.d.ts +1 -1
  10. package/dist/catalog-fec-params.d.ts.map +1 -1
  11. package/dist/catalog-fec-params.js +14 -1
  12. package/dist/catalog-fec-params.js.map +2 -2
  13. package/dist/catalog-network-source.js.map +2 -2
  14. package/dist/cmaf-block-assembler.js +92 -1
  15. package/dist/cmaf-block-assembler.js.map +2 -2
  16. package/dist/codec-utils.d.ts.map +1 -1
  17. package/dist/codec-utils.js +92 -1
  18. package/dist/codec-utils.js.map +2 -2
  19. package/dist/delivery-catalog.js +2 -1
  20. package/dist/delivery-catalog.js.map +2 -2
  21. package/dist/delta-fallback-config.js +5 -1
  22. package/dist/delta-fallback-config.js.map +3 -3
  23. package/dist/fec-manager.d.ts +111 -14
  24. package/dist/fec-manager.d.ts.map +1 -1
  25. package/dist/fec-manager.js +613 -91
  26. package/dist/fec-manager.js.map +2 -2
  27. package/dist/fec-state.js +5 -1
  28. package/dist/fec-state.js.map +2 -2
  29. package/dist/fec-worker-setup.js.map +2 -2
  30. package/dist/held-layer-admission.js.map +2 -2
  31. package/dist/index.d.ts +3 -3
  32. package/dist/index.d.ts.map +1 -1
  33. package/dist/index.js +3 -1
  34. package/dist/index.js.map +2 -2
  35. package/dist/iso-block-locator.d.ts +48 -13
  36. package/dist/iso-block-locator.d.ts.map +1 -1
  37. package/dist/iso-block-locator.js +97 -25
  38. package/dist/iso-block-locator.js.map +2 -2
  39. package/dist/iso-bmff-timing.d.ts +10 -1
  40. package/dist/iso-bmff-timing.d.ts.map +1 -1
  41. package/dist/iso-bmff-timing.js +36 -2
  42. package/dist/iso-bmff-timing.js.map +2 -2
  43. package/dist/media-router.js.map +1 -1
  44. package/dist/mfu-reassembler.js.map +2 -2
  45. package/dist/mmtp-container-parser.d.ts +104 -12
  46. package/dist/mmtp-container-parser.d.ts.map +1 -1
  47. package/dist/mmtp-container-parser.js +308 -27
  48. package/dist/mmtp-container-parser.js.map +2 -2
  49. package/dist/mmtp-container-parser.no-modules.js +329 -32
  50. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  51. package/dist/mmtp-decode-pipeline.js +307 -27
  52. package/dist/mmtp-decode-pipeline.js.map +2 -2
  53. package/dist/mmtp-fec-session.js.map +2 -2
  54. package/dist/mmtp-router.d.ts +36 -8
  55. package/dist/mmtp-router.d.ts.map +1 -1
  56. package/dist/mmtp-router.js +676 -76
  57. package/dist/mmtp-router.js.map +3 -3
  58. package/dist/multicast-auth-catalog.js.map +2 -2
  59. package/dist/multicast-input.js.map +2 -2
  60. package/dist/multicast-manager.d.ts +26 -3
  61. package/dist/multicast-manager.d.ts.map +1 -1
  62. package/dist/multicast-manager.js +1384 -187
  63. package/dist/multicast-manager.js.map +3 -3
  64. package/dist/multicast-transport.js +4 -3
  65. package/dist/multicast-transport.js.map +2 -2
  66. package/dist/multicast-unwrap.js.map +2 -2
  67. package/dist/no-modules.d.ts +1 -0
  68. package/dist/no-modules.d.ts.map +1 -1
  69. package/dist/no-modules.js +329 -31
  70. package/dist/no-modules.js.map +4 -4
  71. package/dist/repair-fetch.d.ts +38 -8
  72. package/dist/repair-fetch.d.ts.map +1 -1
  73. package/dist/repair-fetch.js +286 -27
  74. package/dist/repair-fetch.js.map +3 -3
  75. package/dist/repair-layer-subscriptions.js.map +2 -2
  76. package/dist/signaling.js.map +2 -2
  77. package/dist/timestamp-codec.js.map +2 -2
  78. package/dist/track-session.d.ts.map +1 -1
  79. package/dist/track-session.js +1 -0
  80. package/dist/track-session.js.map +2 -2
  81. package/dist/wasm-mfu-reassembler.js.map +2 -2
  82. package/dist/wasm-mmtp-container-parser.js +307 -27
  83. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  84. package/package.json +5 -5
  85. package/src/block-policy.ts +216 -52
  86. package/src/catalog-fec-params.ts +1 -0
  87. package/src/codec-utils.ts +121 -1
  88. package/src/fec-manager.ts +593 -33
  89. package/src/index.ts +5 -0
  90. package/src/iso-block-locator.ts +133 -31
  91. package/src/iso-bmff-timing.ts +40 -1
  92. package/src/mmtp-container-parser.ts +341 -32
  93. package/src/mmtp-router.ts +614 -61
  94. package/src/multicast-manager.ts +136 -16
  95. package/src/no-modules.ts +3 -0
  96. package/src/repair-fetch.ts +366 -50
  97. package/src/track-session.ts +3 -0
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@blockcast/mmt-container",
3
- "version": "2.2.0-main.da2e7cd1dd5d",
3
+ "version": "2.2.0-main.e1bebe787bc9",
4
4
  "description": "MMTP/LOC container parsing for MMT over MoQ and SSM",
5
5
  "type": "module",
6
6
  "main": "dist/index.js",
@@ -169,10 +169,10 @@
169
169
  "test:watch": "vitest"
170
170
  },
171
171
  "dependencies": {
172
- "@blockcast/fec-worker": "2.2.0-main.da2e7cd1dd5d",
173
- "@blockcast/mmt-base": "2.2.0-main.da2e7cd1dd5d",
174
- "@blockcast/mmt-fec": "2.2.0-main.da2e7cd1dd5d",
175
- "@blockcast/mmt-manifest-verify": "2.2.0-main.da2e7cd1dd5d",
172
+ "@blockcast/fec-worker": "2.2.0-main.e1bebe787bc9",
173
+ "@blockcast/mmt-base": "2.2.0-main.e1bebe787bc9",
174
+ "@blockcast/mmt-fec": "2.2.0-main.e1bebe787bc9",
175
+ "@blockcast/mmt-manifest-verify": "2.2.0-main.e1bebe787bc9",
176
176
  "@noble/curves": "^1.9.7",
177
177
  "@noble/hashes": "^1.8.0",
178
178
  "ajv": "^8.17.1",
@@ -81,7 +81,17 @@ export type ClassifierReason =
81
81
  | 'rap-not-mpu-start'
82
82
  | 'mpu-longer-than-gop'
83
83
  | 'block-not-contiguous'
84
+ /**
85
+ * MPU-start RAPs are not exactly one keyframe interval apart per MPU:
86
+ * released RAPs in the media timescale, or, once each frame is its own
87
+ * movie fragment, RAP fragments G fragments apart per MPU (P3).
88
+ */
84
89
  | 'rap-spacing-mismatch'
90
+ /**
91
+ * An MPU of several movie fragments whose fragments hold several samples:
92
+ * neither sample_number nor the fragment number states a frame's MPU
93
+ * position (P3).
94
+ */
85
95
  | 'mpu-multiple-fragments'
86
96
  | 'block-wider-than-interleave'
87
97
 
@@ -237,13 +247,18 @@ export interface SourceSymbolEvidence {
237
247
  /** MPU_sequence_number, when parsed from this packet. */
238
248
  readonly mpu?: number
239
249
  /**
240
- * 0-based sample position within the MPU: the MFU DU-header
250
+ * 0-based sample position within its movie fragment: the MFU DU-header
241
251
  * `sample_number` minus one (ISO/IEC 23008-1 numbers samples from 1, and
242
252
  * the parser rejects `sample_number` 0). Present only when this packet
243
- * carried a DU header.
253
+ * carried a DU header. It is the MPU position only while the MPU is one
254
+ * movie fragment; BlockClassifier derives MPU positions (P3).
244
255
  */
245
256
  readonly idx?: number
246
- /** movie_fragment_sequence_number from the DU header, when present. */
257
+ /**
258
+ * movie_fragment_sequence_number from the DU header, when present. When
259
+ * each frame is its own fragment, it positions the frame from its MPU's
260
+ * RAP fragment (P3).
261
+ */
247
262
  readonly movieFragment?: number
248
263
  /**
249
264
  * DU-header `offset`: the data unit's authored byte position within its
@@ -279,8 +294,9 @@ export type ClassifierChange =
279
294
  interface BlockEvidence {
280
295
  rapSeen: boolean
281
296
  mpus: Set<number>
282
- idxMin?: number
283
- idxMax?: number
297
+ /** The lowest and highest MPU positions its DU headers proved (P3). */
298
+ positionMin?: number
299
+ positionMax?: number
284
300
  cls: BlockClass
285
301
  }
286
302
 
@@ -292,14 +308,40 @@ interface DataUnitStart {
292
308
  readonly sbn: number
293
309
  }
294
310
 
295
- /** Authored order of two data-unit starts of one MPU. */
311
+ /**
312
+ * Authored order of two data-unit starts of one MPU. Fragment numbers wrap
313
+ * at 2^32, so they compare in RFC 1982 serial order.
314
+ */
296
315
  function compareDataUnitStarts(
297
316
  a: Omit<DataUnitStart, 'sbn'>,
298
317
  b: Omit<DataUnitStart, 'sbn'>,
299
318
  ): number {
300
- return a.movieFragment - b.movieFragment || a.idx - b.idx || a.offset - b.offset
319
+ return ((a.movieFragment - b.movieFragment) | 0) || a.idx - b.idx || a.offset - b.offset
320
+ }
321
+
322
+ /** One MPU's movie fragments (P3). */
323
+ interface MpuLayout {
324
+ /** Serial-earliest movie_fragment_sequence_number of its DU headers. */
325
+ low: number
326
+ /** The fragment of its first RAP-flagged DU header: position 0. */
327
+ anchor?: number
301
328
  }
302
329
 
330
+ /** What one DU header proves about its MPU (BlockClassifier `#place`). */
331
+ interface Placement {
332
+ /** Its 0-based MPU position, when the wire proves it. */
333
+ readonly position?: number
334
+ /**
335
+ * It shows a RAP inside an MPU, or an MPU longer than G: MPU boundaries
336
+ * no longer bound the stream's RAPs (`rap-not-mpu-start`).
337
+ */
338
+ readonly rapNotMpuStart: boolean
339
+ /** A refuted layout premise. */
340
+ readonly violation?: ClassifierReason
341
+ }
342
+
343
+ const UNPLACED: Placement = { rapNotMpuStart: false }
344
+
303
345
  /**
304
346
  * Per-stream block classifier.
305
347
  *
@@ -322,14 +364,33 @@ function compareDataUnitStarts(
322
364
  * from the previous block (`block-wider-than-interleave`). The producer
323
365
  * counts a media-unit boundary only once the open block holds a symbol.
324
366
  * - P3: an MPU starts with its only RAP and holds at most G frames
325
- * (`rap-not-mpu-start`, `mpu-longer-than-gop`, `rap-spacing-mismatch`), in
326
- * one movie fragment (`mpu-multiple-fragments`).
367
+ * (`rap-not-mpu-start`, `mpu-longer-than-gop`, `rap-spacing-mismatch`),
368
+ * and its DU headers state each frame's MPU position in one of two layouts
369
+ * (`mpu-multiple-fragments` when an MPU shows two fragments and a DU
370
+ * header states sample_number above 1, which is neither):
371
+ * - one movie fragment per MPU (ATSC 3.0): the position is
372
+ * sample_number − 1. This is the rule until some MPU of the sequence
373
+ * shows two fragments.
374
+ * - one fragment per frame, numbered one per frame (FFmpeg's MoQ MMT
375
+ * muxer, every DU header stating sample_number 1): the position is the
376
+ * fragment's distance from the fragment of the MPU's first RAP-flagged
377
+ * DU header (its anchor). The RAP's own fragment is position 0. Each
378
+ * anchor must lie exactly G fragments per MPU from the anchor received
379
+ * before it, which is kept past the horizon, and from the anchor
380
+ * received last (`rap-spacing-mismatch`, as after a dropped frame).
381
+ * Once two anchors kept that spacing, fragment numbers count frames:
382
+ * later fragments get positions, and an anchor arriving past the
383
+ * spacing is a RAP inside its MPU or follows an MPU longer than G
384
+ * (`rap-not-mpu-start`). An MPU whose anchor was not received has no
385
+ * positions; its blocks stay unknown. A second RAP-flagged fragment, or
386
+ * a DU header in a fragment before the anchor, refutes the MPU start
387
+ * (`rap-not-mpu-start`).
327
388
  *
328
389
  * P1 and P2 are what make a block's frames contiguous and lie within
329
- * [idxMax − D + 1, idxMin + D − 1] of its MPU. What refutes P1 is a pair of
330
- * source packets whose wire-stated authored order and SBN order disagree:
331
- * a later MPU in an earlier block, a later data unit of one MPU (by
332
- * movie_fragment_sequence_number, sample_number, then DU offset) in an
390
+ * [positionMax − D + 1, positionMin + D − 1] of its MPU. What refutes P1 is
391
+ * a pair of source packets whose wire-stated authored order and SBN order
392
+ * disagree: a later MPU in an earlier block, a later data unit of one MPU
393
+ * (by movie_fragment_sequence_number, sample_number, then DU offset) in an
333
394
  * earlier block, or one data unit in two blocks. That is the signature of a
334
395
  * round-robin interleave, which scatters one run over several concurrent
335
396
  * blocks. Non-adjacency alone is not: a sample larger than K packets
@@ -357,8 +418,23 @@ export class BlockClassifier {
357
418
  #mpuSbnSpans = new Map<number, { min: number; max: number }>()
358
419
  #dataUnitStarts = new Map<number, DataUnitStart[]>()
359
420
  #highestMpu: number | null = null
360
- /** MPU → movie_fragment_sequence_number observed in it. */
361
- #mpuFragments = new Map<number, number>()
421
+ /**
422
+ * P3 layout, kept for the MPUs within the classification horizon and valid
423
+ * within one continuous SBN sequence (`noteSourceDiscontinuity`).
424
+ */
425
+ #mpus = new Map<number, MpuLayout>()
426
+ /** An MPU of this sequence showed two movie fragments: each frame is one. */
427
+ #fragmentPerFrame = false
428
+ /** A DU header of this sequence stated sample_number above 1. */
429
+ #multiSampleFragment = false
430
+ /**
431
+ * The anchor received last, whether or not its MPU is still in the
432
+ * horizon. Each new anchor, and the anchor of every DU header's MPU, is
433
+ * checked against it.
434
+ */
435
+ #lastAnchor: { mpu: number; fragment: number } | null = null
436
+ /** Two anchors were exactly G fragments per MPU apart. */
437
+ #fragmentsProven = false
362
438
  #lastRap: { mpu: number; presentationTime: bigint; mediaTimescale: number } | null = null
363
439
 
364
440
  constructor(geometry: BlockClassifierGeometry) {
@@ -394,7 +470,7 @@ export class BlockClassifier {
394
470
  this.#geometry = geometry
395
471
  this.#blocks.clear()
396
472
  this.#clearContiguityLedger()
397
- this.#mpuFragments.clear()
473
+ this.#clearMpuLayout()
398
474
  this.#lastRap = null
399
475
  this.#mpuBoundsRaps = true
400
476
  if (geometry.trackKind === 'video' && geometry.mode === 'all-protected') {
@@ -430,11 +506,13 @@ export class BlockClassifier {
430
506
  /**
431
507
  * The stream's SBN sequence restarted (FECManager source discontinuity:
432
508
  * a publisher restart, or the SS_ID space wrapped). Authored order and SBN
433
- * order are comparable only within one continuous sequence, so the P1
434
- * ledger starts again.
509
+ * order are comparable only within one continuous sequence, and a
510
+ * restarted publisher numbers MPUs and movie fragments again, so the P1
511
+ * ledger and the P3 layout start again.
435
512
  */
436
513
  noteSourceDiscontinuity(): void {
437
514
  this.#clearContiguityLedger()
515
+ this.#clearMpuLayout()
438
516
  }
439
517
 
440
518
  /** Register a block that exists without evidence (a vanished block). */
@@ -457,21 +535,23 @@ export class BlockClassifier {
457
535
  if (this.#geometry.trackKind === 'audio') return []
458
536
  const changes: ClassifierChange[] = []
459
537
  const block = this.#blockFor(sbn)
538
+ const placement = this.#place(evidence)
460
539
 
461
540
  if (evidence.rap) block.rapSeen = true
462
541
  if (evidence.mpu !== undefined) block.mpus.add(evidence.mpu)
463
- if (evidence.idx !== undefined) {
464
- block.idxMin = block.idxMin === undefined ? evidence.idx : Math.min(block.idxMin, evidence.idx)
465
- block.idxMax = block.idxMax === undefined ? evidence.idx : Math.max(block.idxMax, evidence.idx)
542
+ const { position } = placement
543
+ if (position !== undefined) {
544
+ block.positionMin =
545
+ block.positionMin === undefined ? position : Math.min(block.positionMin, position)
546
+ block.positionMax =
547
+ block.positionMax === undefined ? position : Math.max(block.positionMax, position)
466
548
  }
467
549
 
468
550
  // A RAP inside an MPU refutes "an MPU boundary bounds RAPs" whatever the
469
551
  // classifier mode, because gap decisions rely on it in every mode.
470
- if (evidence.rap && evidence.idx !== undefined && evidence.idx !== 0) {
471
- this.#mpuBoundsRaps = false
472
- }
552
+ if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false
473
553
 
474
- const violation = this.#checkInvariants(sbn, block, evidence)
554
+ const violation = this.#checkInvariants(sbn, block, evidence, placement)
475
555
  if (violation !== null) changes.push(...this.#disable(violation))
476
556
 
477
557
  const next = this.#classify(block)
@@ -549,14 +629,13 @@ export class BlockClassifier {
549
629
  sbn: number,
550
630
  block: BlockEvidence,
551
631
  evidence: SourceSymbolEvidence,
632
+ placement: Placement,
552
633
  ): ClassifierReason | null {
553
634
  if (this.#mode === 'all-protected' || this.#geometry.trackKind !== 'video') return null
554
635
  const geometry = this.#geometry
555
636
  if (geometry.mode !== 'classifying') return null
556
- if (evidence.rap && evidence.idx !== undefined && evidence.idx !== 0) {
557
- return 'rap-not-mpu-start'
558
- }
559
- if (evidence.idx !== undefined && evidence.idx >= geometry.gopFrames) {
637
+ if (placement.rapNotMpuStart) return 'rap-not-mpu-start'
638
+ if (placement.position !== undefined && placement.position >= geometry.gopFrames) {
560
639
  return 'mpu-longer-than-gop'
561
640
  }
562
641
  // A block closes at the latest after D media units, so the DU headers it
@@ -565,32 +644,109 @@ export class BlockClassifier {
565
644
  // round-robin across concurrent blocks) and the window rule is void.
566
645
  if (
567
646
  block.mpus.size === 1 &&
568
- block.idxMin !== undefined &&
569
- block.idxMax !== undefined &&
570
- block.idxMax - block.idxMin >= geometry.interleaveUnits
647
+ block.positionMin !== undefined &&
648
+ block.positionMax !== undefined &&
649
+ block.positionMax - block.positionMin >= geometry.interleaveUnits
571
650
  ) {
572
651
  return 'block-wider-than-interleave'
573
652
  }
574
- if (evidence.mpu !== undefined && evidence.movieFragment !== undefined) {
575
- const fragment = this.#mpuFragments.get(evidence.mpu)
576
- if (fragment === undefined) {
577
- this.#mpuFragments.set(evidence.mpu, evidence.movieFragment)
578
- // One entry per MPU still inside the classification horizon.
579
- for (const mpu of this.#mpuFragments.keys()) {
580
- if (mpu + 1 < evidence.mpu) this.#mpuFragments.delete(mpu)
581
- }
582
- } else if (fragment !== evidence.movieFragment) {
583
- // sample_number is then a position within a movie fragment, not
584
- // within the MPU, and the window rule's geometry does not hold.
585
- return 'mpu-multiple-fragments'
586
- }
587
- }
653
+ if (placement.violation !== undefined) return placement.violation
588
654
  if (evidence.mpu !== undefined && this.#contradictsAuthoredOrder(sbn, evidence.mpu, evidence)) {
589
655
  return 'block-not-contiguous'
590
656
  }
591
657
  return null
592
658
  }
593
659
 
660
+ /**
661
+ * The MPU position a source symbol's DU header proves (P3), and what it
662
+ * refutes. Runs in every mode: mpuBoundsRaps needs its RAP verdict.
663
+ */
664
+ #place(evidence: SourceSymbolEvidence): Placement {
665
+ const { mpu, idx, movieFragment: fragment } = evidence
666
+ if (idx === undefined) return UNPLACED
667
+ const bySample: Placement = { position: idx, rapNotMpuStart: evidence.rap && idx !== 0 }
668
+ // Every wire DU header states both; evidence without them keeps the
669
+ // one-fragment rule unless the sequence is fragment-per-frame.
670
+ if (mpu === undefined || fragment === undefined) {
671
+ return this.#fragmentPerFrame && !this.#multiSampleFragment
672
+ ? { rapNotMpuStart: bySample.rapNotMpuStart }
673
+ : bySample
674
+ }
675
+ let layout = this.#mpus.get(mpu)
676
+ if (layout === undefined) {
677
+ layout = { low: fragment }
678
+ this.#mpus.set(mpu, layout)
679
+ // One entry per MPU still inside the classification horizon.
680
+ for (const other of this.#mpus.keys()) {
681
+ if (other + 1 < mpu) this.#mpus.delete(other)
682
+ }
683
+ } else if (fragment !== layout.low) {
684
+ this.#fragmentPerFrame = true
685
+ if (((fragment - layout.low) | 0) < 0) layout.low = fragment
686
+ }
687
+ if (idx !== 0) this.#multiSampleFragment = true
688
+ let arrival: number | undefined
689
+ if (evidence.rap && layout.anchor === undefined) {
690
+ layout.anchor = fragment
691
+ arrival = this.#anchorDrift(mpu, fragment)
692
+ // Proof takes two MPUs: an MPU's RAP header seen again proves nothing.
693
+ if (arrival === 0 && this.#lastAnchor?.mpu !== mpu) this.#fragmentsProven = true
694
+ this.#lastAnchor = { mpu, fragment }
695
+ }
696
+ // Until an MPU shows two fragments, sample_number − 1 is the position.
697
+ // Once one has, a sample_number above 1 leaves neither layout.
698
+ if (!this.#fragmentPerFrame) return bySample
699
+ if (this.#multiSampleFragment) return { ...bySample, violation: 'mpu-multiple-fragments' }
700
+ const { anchor } = layout
701
+ if (anchor === undefined) return UNPLACED
702
+ // A new anchor against the anchor received before it; any other DU
703
+ // header's anchor against the anchor received last, so an anchor that
704
+ // arrived before the layout was known is held to the spacing too.
705
+ const drift = arrival ?? this.#anchorDrift(mpu, anchor)
706
+ // RFC 1982 distance from the anchor: positive for a later fragment.
707
+ const offset = (fragment - anchor) | 0
708
+ return {
709
+ ...(offset === 0 || (offset > 0 && this.#fragmentsProven) ? { position: offset } : {}),
710
+ rapNotMpuStart:
711
+ (evidence.rap && offset !== 0) ||
712
+ ((layout.low - anchor) | 0) < 0 ||
713
+ // Fragments count frames: an anchor arriving past the spacing is a
714
+ // RAP inside its MPU, or an earlier MPU outran G.
715
+ (arrival !== undefined && arrival > 0 && this.#fragmentsProven),
716
+ ...(drift === undefined || drift === 0 ? {} : { violation: 'rap-spacing-mismatch' }),
717
+ }
718
+ }
719
+
720
+ /**
721
+ * How many fragments MPU m's anchor `fragment` lies past the start that
722
+ * the anchor received last predicts for MPU m: one frame per fragment and
723
+ * G frames per MPU put the anchors of MPUs m and m' exactly G * (m - m')
724
+ * fragments apart, modulo 2^32. Undefined without a last anchor, a
725
+ * cadence, or this layout.
726
+ */
727
+ #anchorDrift(mpu: number, fragment: number): number | undefined {
728
+ const geometry = this.#geometry
729
+ const last = this.#lastAnchor
730
+ if (
731
+ last === null ||
732
+ !this.#fragmentPerFrame ||
733
+ this.#multiSampleFragment ||
734
+ geometry.trackKind !== 'video' ||
735
+ geometry.mode !== 'classifying'
736
+ ) {
737
+ return undefined
738
+ }
739
+ return (fragment - last.fragment - geometry.gopFrames * (mpu - last.mpu)) | 0
740
+ }
741
+
742
+ #clearMpuLayout(): void {
743
+ this.#mpus.clear()
744
+ this.#fragmentPerFrame = false
745
+ this.#multiSampleFragment = false
746
+ this.#lastAnchor = null
747
+ this.#fragmentsProven = false
748
+ }
749
+
594
750
  #clearContiguityLedger(): void {
595
751
  this.#mpuSbnSpans.clear()
596
752
  this.#dataUnitStarts.clear()
@@ -698,14 +854,17 @@ export class BlockClassifier {
698
854
  if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') return 'unknown'
699
855
  if (
700
856
  block.mpus.size === 1 &&
701
- block.idxMin !== undefined &&
702
- block.idxMax !== undefined
857
+ block.positionMin !== undefined &&
858
+ block.positionMax !== undefined
703
859
  ) {
704
860
  // A block closes every D media units, so its frames are contiguous and
705
- // lie in [idxMax − D + 1, idxMin + D − 1] of MPU m. Index 0 is the only
706
- // RAP of an MPU and G bounds its length.
861
+ // lie in [positionMax − D + 1, positionMin + D − 1] of MPU m. Position
862
+ // 0 is the only RAP of an MPU and G bounds its length.
707
863
  const span = geometry.interleaveUnits - 1
708
- if (block.idxMax - span >= 1 && block.idxMin + span <= geometry.gopFrames - 1) {
864
+ if (
865
+ block.positionMax - span >= 1 &&
866
+ block.positionMin + span <= geometry.gopFrames - 1
867
+ ) {
709
868
  return 'delta'
710
869
  }
711
870
  }
@@ -746,7 +905,12 @@ export interface GapFrameEvidence {
746
905
  * same-MPU then no longer proves a gap lost only deltas.
747
906
  */
748
907
  readonly mpu?: number
749
- /** 0-based sample position within the MPU, when the geometry verifies it. */
908
+ /**
909
+ * 0-based sample position within its movie fragment (sample_number − 1).
910
+ * State it on both sides only when both frames are in one movie fragment:
911
+ * decideGap reads `after.idx − before.idx − 1` as the samples missed
912
+ * between them.
913
+ */
750
914
  readonly idx?: number
751
915
  /** Authored presentation time in `timescale` ticks. */
752
916
  readonly pts?: bigint
@@ -37,6 +37,7 @@ export { FEC_BLOCK_PROFILES, isFecBlockProfile, parseFecBlockProfile, type FecBl
37
37
  // Re-exported here, not from index.ts: index's bundle keeps `./*.js` external,
38
38
  // so a direct mmt-base re-export there leaves a dangling `./mmtp.js` import.
39
39
  export {
40
+ runtimeFecCatalogReport,
40
41
  validateFecCatalog,
41
42
  type FecCatalogCode,
42
43
  type FecCatalogInstance,
@@ -1276,9 +1276,21 @@ function isH264IntraSlice(nal: Uint8Array): boolean {
1276
1276
  return sliceType === 2 || sliceType === 4 || sliceType === 7 || sliceType === 9
1277
1277
  }
1278
1278
 
1279
+ /**
1280
+ * Escaped bytes after the NAL header that always hold first_mb_in_slice and
1281
+ * slice_type. {@link readUnsignedExpGolomb} reads at most 61 bits per ue(v)
1282
+ * and gives up at the 31st leading zero, so both fields end within 122 bits
1283
+ * (16 bytes) of RBSP. {@link removeEmulationPrevention} drops a 0x03 only
1284
+ * after two kept zero bytes since the last one it dropped, so 32 escaped
1285
+ * bytes unescape to at least 22.
1286
+ */
1287
+ const H264_SLICE_TYPE_ESCAPED_BYTES = 32
1288
+
1279
1289
  function readH264SliceType(nal: Uint8Array): number | null {
1280
1290
  if (nal.length < 2 || (nal[0]! & 0x1f) !== 1) return null
1281
- const rbsp = removeEmulationPrevention(nal.subarray(1))
1291
+ // Unescape the start of the slice header only, not the whole slice: this
1292
+ // runs on every non-IDR frame.
1293
+ const rbsp = removeEmulationPrevention(nal.subarray(1, 1 + H264_SLICE_TYPE_ESCAPED_BYTES))
1282
1294
  const state = { bitOffset: 0 }
1283
1295
  if (readUnsignedExpGolomb(rbsp, state) === null) return null
1284
1296
  return readUnsignedExpGolomb(rbsp, state)
@@ -1705,6 +1717,114 @@ if (import.meta.vitest) {
1705
1717
  })
1706
1718
  })
1707
1719
 
1720
+ describe('readH264SliceType', () => {
1721
+ /** The read as it was before the prefix bound: unescape the whole NAL unit. */
1722
+ const wholeNalSliceType = (nal: Uint8Array): number | null => {
1723
+ if (nal.length < 2 || (nal[0]! & 0x1f) !== 1) return null
1724
+ const rbsp = removeEmulationPrevention(nal.subarray(1))
1725
+ const state = { bitOffset: 0 }
1726
+ if (readUnsignedExpGolomb(rbsp, state) === null) return null
1727
+ return readUnsignedExpGolomb(rbsp, state)
1728
+ }
1729
+ const hex = (text: string) => Uint8Array.from(text.match(/../g)!, (byte) => parseInt(byte, 16))
1730
+ const ue = (value: number) => {
1731
+ const code = (value + 1).toString(2)
1732
+ return '0'.repeat(code.length - 1) + code
1733
+ }
1734
+ /** A nal_unit_type 1 NAL unit from RBSP bits, escaped as an encoder escapes it (H.264 §7.4.1). */
1735
+ const sliceNal = (bits: string): Uint8Array => {
1736
+ const rbsp = `${bits}1`.padEnd(Math.ceil((bits.length + 1) / 8) * 8, '0').match(/.{8}/g)!
1737
+ const nal = [0x01]
1738
+ let zeros = 0
1739
+ for (const byte of rbsp.map((bits8) => parseInt(bits8, 2))) {
1740
+ if (zeros >= 2 && byte <= 0x03) {
1741
+ nal.push(0x03)
1742
+ zeros = 0
1743
+ }
1744
+ nal.push(byte)
1745
+ zeros = byte === 0 ? zeros + 1 : 0
1746
+ }
1747
+ return Uint8Array.from(nal)
1748
+ }
1749
+
1750
+ // x264 core 164 (FFmpeg 6.1.1) slices of testsrc2: 64x48 with open-gop=1:bframes=2:slices=3;
1751
+ // 1280x720 main with bframes=2:slices=4, each carrying an emulation_prevention_three_byte
1752
+ // in its first 32 bytes; and the first 40 bytes of 7680x4320 slices=4 slices, whose
1753
+ // first_mb_in_slice takes up to 33 bits. [name, NAL unit, slice_type, keyframe]
1754
+ const x264Slices: Array<[string, Uint8Array, number | null, boolean]> = [
1755
+ ['64x48 P', hex('419a231885bfd53888f63ef5b1e1e39b9ff2eabf03fd3f4d7d4317ffcbf75176'), 5, false],
1756
+ ['64x48 B', hex('419e414212fffeeade283707cb70f7'), 6, false],
1757
+ ['64x48 non-IDR I', hex(
1758
+ '4128899037f384db2be0cfe48aa23558781dd429f7db8e8a6ae44f7ca2333ba1029477da6ddfeac61843c5680cbf66' +
1759
+ '247469d64549b0f5f7ca6acc529f5cf032b35d8dedc6b2412ece24f42f80b593fc0f3ff47a08c84799ff2ada18ac39' +
1760
+ 'a527e23eb34c8167fd',
1761
+ ), 7, true],
1762
+ ['1280x720 B, escape at byte 10', hex(
1763
+ '01006e27a81109ff000003016b662ea5ea46000f57880f3fb0d3f03ff7dac0546fc9966a5f6d86cb795db178882f6e' +
1764
+ '19b75d92170917306190f262fd58268702db2eff86a9651e48',
1765
+ ), 6, false],
1766
+ ['1280x720 P, escape at byte 15', hex(
1767
+ '41006e26a8cd1329e1bffea784000003002b5ef096f0320bd99f00037f22327e886223b7996bb04acd35ad9a0385f0' +
1768
+ '2c1801eb6226bc94993d1880172ffbb23db74729569b6f3934cba0cba17b7c29ce0e216080cb7b18e5876df59e8530' +
1769
+ '2da9cba203fe6769178a2e02eeaa54a6f87568cbaa019a3442eae19c8a7adc8cd02441bee573c5408b6552abd2d9d3',
1770
+ ), 5, false],
1771
+ ['1280x720 B, escape at byte 22', hex('01006e27da9109ff01a4c1dbc27ed915a3172ec80000030352'), 6, false],
1772
+ ['7680x4320 IDR, first_mb_in_slice 97440', hex(
1773
+ '650000be5088843a118a000218f1c00040f63800087949c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9c9',
1774
+ ), null, true],
1775
+ ['7680x4320 P, first_mb_in_slice 32640', hex(
1776
+ '410003fc09a20a806ff0ae0085a611cc7ad5f2020e25900ba4c3398016b57e100011021220200020',
1777
+ ), 5, false],
1778
+ ['7680x4320 P, first_mb_in_slice 97440', hex(
1779
+ '410000be509a20a8078f5a83cc40d800783b017f5c6d7e4883fb4801a9c569245bd04135f7c00806',
1780
+ ), 5, false],
1781
+ ]
1782
+ // Field values far past what a picture needs, so that escapes fall inside the two fields.
1783
+ const syntheticSlices: Array<[string, Uint8Array, number | null]> = [
1784
+ ['an escape inside first_mb_in_slice', sliceNal(ue(2 ** 24 - 1) + ue(2)), 2],
1785
+ ['an escape between the fields', sliceNal(ue(2 ** 21 - 1) + ue(7)), 7],
1786
+ ['an escape inside slice_type', sliceNal(ue(0) + ue(2 ** 22 - 1)), 2 ** 22 - 1],
1787
+ ['the longest fields, five escapes', sliceNal(ue(2 ** 30 - 1) + ue(2 ** 30 - 1)), 2 ** 30 - 1],
1788
+ ['the largest values', sliceNal(ue(2 ** 31 - 2) + ue(2 ** 31 - 2)), 2 ** 31 - 2],
1789
+ ['31 leading zeros in first_mb_in_slice', sliceNal(`${'0'.repeat(31)}1`), null],
1790
+ ['31 leading zeros in slice_type', sliceNal(`1${'0'.repeat(31)}1`), null],
1791
+ ['escapes running past the slice header', sliceNal(ue(0) + ue(5) + '0'.repeat(400)), 5],
1792
+ ]
1793
+
1794
+ test('reads the slice_type of real and synthetic slices', () => {
1795
+ for (const [name, nal, sliceType] of [...x264Slices, ...syntheticSlices]) {
1796
+ expect(readH264SliceType(nal), name).toBe(sliceType)
1797
+ }
1798
+ })
1799
+
1800
+ test('matches the whole-NAL unescape at every truncation', () => {
1801
+ for (const [name, nal] of [...x264Slices, ...syntheticSlices]) {
1802
+ for (let end = 0; end <= nal.length; end++) {
1803
+ const cut = nal.subarray(0, end)
1804
+ expect(readH264SliceType(cut), `${name}, first ${end} bytes`).toBe(wholeNalSliceType(cut))
1805
+ }
1806
+ }
1807
+ })
1808
+
1809
+ test('matches the whole-NAL unescape on zero-heavy NAL units', () => {
1810
+ const bytes = [0x00, 0x00, 0x00, 0x03, 0x01, 0x02, 0x80, 0xff]
1811
+ let seed = 1
1812
+ const next = () => (seed = (Math.imul(seed, 1103515245) + 12345) >>> 0) >>> 16
1813
+ for (let i = 0; i < 5000; i++) {
1814
+ const nal = new Uint8Array(2 + (next() % 63))
1815
+ nal[0] = 0x41
1816
+ for (let j = 1; j < nal.length; j++) nal[j] = bytes[next() % bytes.length]!
1817
+ expect(readH264SliceType(nal), Array.from(nal).join()).toBe(wholeNalSliceType(nal))
1818
+ }
1819
+ })
1820
+
1821
+ test('classifies the x264 slices as keyframes or not', () => {
1822
+ for (const [name, nal, , keyframe] of x264Slices) {
1823
+ expect(classifyH264Keyframe(rawH264NalToAvcc(nal), { allowPartialAvcc: true }), name).toBe(keyframe)
1824
+ }
1825
+ })
1826
+ })
1827
+
1708
1828
  describe('avccToAnnexB', () => {
1709
1829
  test('converts with SPS/PPS on keyframe', () => {
1710
1830
  const avcc = new Uint8Array([0, 0, 0, 3, 0x65, 0xAA, 0xBB])