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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (129) hide show
  1. package/README.md +125 -2
  2. package/dist/__tests__/ad-creative-signer.d.ts +11 -0
  3. package/dist/__tests__/ad-creative-signer.d.ts.map +1 -0
  4. package/dist/__tests__/test-utils.d.ts +1 -0
  5. package/dist/__tests__/test-utils.d.ts.map +1 -1
  6. package/dist/ad-beacon.d.ts +39 -0
  7. package/dist/ad-beacon.d.ts.map +1 -0
  8. package/dist/ad-beacon.js +21 -0
  9. package/dist/ad-beacon.js.map +7 -0
  10. package/dist/ad-creative-record.d.ts +65 -0
  11. package/dist/ad-creative-record.d.ts.map +1 -0
  12. package/dist/ad-creative-record.js +2281 -0
  13. package/dist/ad-creative-record.js.map +7 -0
  14. package/dist/ad-creative-timeline.d.ts +103 -0
  15. package/dist/ad-creative-timeline.d.ts.map +1 -0
  16. package/dist/ad-creative-timeline.js +2548 -0
  17. package/dist/ad-creative-timeline.js.map +7 -0
  18. package/dist/block-policy.d.ts +128 -14
  19. package/dist/block-policy.d.ts.map +1 -1
  20. package/dist/block-policy.js +472 -27
  21. package/dist/block-policy.js.map +2 -2
  22. package/dist/browser-runtime.js +1024 -117
  23. package/dist/browser-runtime.js.map +4 -4
  24. package/dist/carp-catalog.d.ts +1 -0
  25. package/dist/carp-catalog.d.ts.map +1 -1
  26. package/dist/carp-catalog.js +34 -0
  27. package/dist/carp-catalog.js.map +4 -4
  28. package/dist/catalog-fec-params.js.map +1 -1
  29. package/dist/catalog-network-source.d.ts +1 -17
  30. package/dist/catalog-network-source.d.ts.map +1 -1
  31. package/dist/catalog-network-source.js +25 -19
  32. package/dist/catalog-network-source.js.map +3 -3
  33. package/dist/cmaf-block-assembler.d.ts +10 -2
  34. package/dist/cmaf-block-assembler.d.ts.map +1 -1
  35. package/dist/cmaf-block-assembler.js +30 -8
  36. package/dist/cmaf-block-assembler.js.map +3 -3
  37. package/dist/codec-utils.d.ts.map +1 -1
  38. package/dist/codec-utils.js +16 -3
  39. package/dist/codec-utils.js.map +2 -2
  40. package/dist/conceal-timeline.d.ts +24 -1
  41. package/dist/conceal-timeline.d.ts.map +1 -1
  42. package/dist/conceal-timeline.js +201 -4
  43. package/dist/conceal-timeline.js.map +3 -3
  44. package/dist/datagram-leg-deadline.d.ts +4 -0
  45. package/dist/datagram-leg-deadline.d.ts.map +1 -1
  46. package/dist/datagram-leg-deadline.js.map +2 -2
  47. package/dist/event-timeline-mmtp.d.ts +17 -0
  48. package/dist/event-timeline-mmtp.d.ts.map +1 -0
  49. package/dist/event-timeline-mmtp.js +3117 -0
  50. package/dist/event-timeline-mmtp.js.map +7 -0
  51. package/dist/fec-manager.d.ts +24 -3
  52. package/dist/fec-manager.d.ts.map +1 -1
  53. package/dist/fec-manager.js +531 -38
  54. package/dist/fec-manager.js.map +2 -2
  55. package/dist/feed-gate.d.ts +114 -0
  56. package/dist/feed-gate.d.ts.map +1 -0
  57. package/dist/feed-gate.js +175 -0
  58. package/dist/feed-gate.js.map +7 -0
  59. package/dist/index.d.ts +3 -2
  60. package/dist/index.d.ts.map +1 -1
  61. package/dist/index.js +13 -1
  62. package/dist/index.js.map +2 -2
  63. package/dist/iso-bmff-timing.d.ts +16 -0
  64. package/dist/iso-bmff-timing.d.ts.map +1 -1
  65. package/dist/iso-bmff-timing.js +28 -0
  66. package/dist/iso-bmff-timing.js.map +2 -2
  67. package/dist/mfu-reassembler.d.ts +2 -0
  68. package/dist/mfu-reassembler.d.ts.map +1 -1
  69. package/dist/mfu-reassembler.js +4 -2
  70. package/dist/mfu-reassembler.js.map +2 -2
  71. package/dist/mmtp-container-parser.d.ts +12 -0
  72. package/dist/mmtp-container-parser.d.ts.map +1 -1
  73. package/dist/mmtp-container-parser.js +73 -3
  74. package/dist/mmtp-container-parser.js.map +2 -2
  75. package/dist/mmtp-container-parser.no-modules.js +103 -25
  76. package/dist/mmtp-container-parser.no-modules.js.map +4 -4
  77. package/dist/mmtp-decode-pipeline.js +73 -3
  78. package/dist/mmtp-decode-pipeline.js.map +2 -2
  79. package/dist/mmtp-router.d.ts +20 -2
  80. package/dist/mmtp-router.d.ts.map +1 -1
  81. package/dist/mmtp-router.js +150 -23
  82. package/dist/mmtp-router.js.map +3 -3
  83. package/dist/multicast-auth-catalog.js.map +1 -1
  84. package/dist/multicast-input.js.map +1 -1
  85. package/dist/multicast-manager.d.ts +23 -2
  86. package/dist/multicast-manager.d.ts.map +1 -1
  87. package/dist/multicast-manager.js +737 -86
  88. package/dist/multicast-manager.js.map +3 -3
  89. package/dist/multicast-transport.js +44 -22
  90. package/dist/multicast-transport.js.map +2 -2
  91. package/dist/no-modules.js +98 -22
  92. package/dist/no-modules.js.map +4 -4
  93. package/dist/repair-fetch.d.ts +10 -3
  94. package/dist/repair-fetch.d.ts.map +1 -1
  95. package/dist/repair-fetch.js +31 -5
  96. package/dist/repair-fetch.js.map +2 -2
  97. package/dist/wasm-mfu-reassembler.js.map +2 -2
  98. package/dist/wasm-mmtp-container-parser.js +73 -3
  99. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  100. package/package.json +17 -5
  101. package/schemas/catalog.schema.json +7 -2
  102. package/src/ad-beacon.ts +51 -0
  103. package/src/ad-creative-record.ts +276 -0
  104. package/src/ad-creative-timeline.ts +410 -0
  105. package/src/block-policy.ts +673 -42
  106. package/src/carp-catalog.ts +9 -0
  107. package/src/catalog-network-source.ts +3 -37
  108. package/src/cmaf-block-assembler.ts +17 -0
  109. package/src/codec-utils.ts +19 -3
  110. package/src/conceal-timeline.ts +60 -5
  111. package/src/datagram-leg-deadline.ts +4 -0
  112. package/src/event-timeline-mmtp.ts +55 -0
  113. package/src/fec-manager.ts +84 -12
  114. package/src/feed-gate.ts +295 -0
  115. package/src/index.ts +21 -0
  116. package/src/iso-bmff-timing.ts +33 -0
  117. package/src/mfu-reassembler.ts +4 -0
  118. package/src/mmtp-container-parser.ts +51 -5
  119. package/src/mmtp-router.ts +116 -4
  120. package/src/multicast-manager.ts +31 -0
  121. package/src/repair-fetch.ts +53 -8
  122. package/test-vectors/catalog/README.md +1 -0
  123. package/test-vectors/catalog/negative/event-timeline-empty-event-type.json +41 -0
  124. package/test-vectors/catalog/positive/event-timeline-ad-creative.json +41 -0
  125. package/test-vectors/catalog/positive/event-timeline-wallclock-no-depends.json +38 -0
  126. package/test-vectors/catalog/positive/multicast-event-timeline.json +81 -0
  127. package/test-vectors/catalog/section-codes.json +1 -0
  128. package/test-vectors/frame-needs-v1.json +295 -0
  129. package/test-vectors/repair-policy-v1.json +36 -3
@@ -15,8 +15,11 @@
15
15
  * Everything here is derived from catalog-authored timing and in-band MMTP
16
16
  * evidence. There are no timers, no cadence heuristics, and no defaults: a
17
17
  * track whose geometry cannot be derived exactly runs in the defined
18
- * fail-closed mode `all-protected`, where every block is treated as possibly
19
- * keyframe-bearing.
18
+ * fail-closed mode `all-protected`, where the window rule is off: a block is
19
+ * treated as possibly keyframe-bearing unless the MPU numbers of the DU
20
+ * headers held around it show otherwise (the MPU rule). That rule needs no
21
+ * block geometry, but it classes nothing on a track whose catalog does not
22
+ * state a keyframe interval equal to its group duration.
20
23
  *
21
24
  * All three players (moqtail, hang, Shaka) consume this one implementation.
22
25
  */
@@ -108,6 +111,13 @@ export interface BlockClassifierGeometryInput {
108
111
  readonly keyframeIntervalTicks?: number
109
112
  /** Catalog `keyframeIntervalMs`. */
110
113
  readonly keyframeIntervalMs?: number
114
+ /**
115
+ * The track's catalog group duration in ms (`catalogGroupDurationMs`: the
116
+ * tick form over the timescale where the catalog states it, so it may be a
117
+ * fraction). Never a cadence. It is only compared with the keyframe
118
+ * interval: the MPU rule classes nothing unless the two are equal.
119
+ */
120
+ readonly groupDurationMs?: number
111
121
  }
112
122
 
113
123
  /** Exact keyframe interval as a rational number of seconds: ticks / timescale. */
@@ -128,6 +138,8 @@ export type BlockClassifierGeometry =
128
138
  /** G: frames per GOP. */
129
139
  readonly gopFrames: number
130
140
  readonly keyframeInterval: KeyframeInterval
141
+ /** The catalog group duration in ms, when stated (the MPU rule's catalog test). */
142
+ readonly groupDurationMs?: number
131
143
  }
132
144
  | {
133
145
  readonly trackKind: 'video'
@@ -135,6 +147,8 @@ export type BlockClassifierGeometry =
135
147
  readonly reason: ClassifierReason
136
148
  /** The catalog interval when one is stated: gap decisions use it (keyframeInstantBetween). */
137
149
  readonly keyframeInterval?: KeyframeInterval
150
+ /** The catalog group duration in ms, when stated (the MPU rule's catalog test). */
151
+ readonly groupDurationMs?: number
138
152
  }
139
153
 
140
154
  /**
@@ -164,8 +178,13 @@ function isPositiveFinite(value: number | undefined): value is number {
164
178
  * Derive the per-track classifier geometry from raw catalog fields.
165
179
  *
166
180
  * `all-protected` is the policy's defined fail-closed state, not a default:
167
- * it is returned with the exact reason. The only throw is for a value the
168
- * catalog validator already rejects (a non-positive block span).
181
+ * it is returned with the exact reason. It turns the window rule off; the
182
+ * MPU rule can still class a block `delta` where the catalog states a
183
+ * keyframe interval equal to the group duration (`mpuRuleCatalogReason`).
184
+ * A `classifying` geometry whose catalog does not state that gets no `delta`
185
+ * either: the window rule classes only on a track the MPU rule applies to.
186
+ * The only throw is for a value the catalog validator already rejects (a
187
+ * non-positive block span).
169
188
  */
170
189
  export function deriveBlockClassifierGeometry(
171
190
  input: BlockClassifierGeometryInput,
@@ -186,11 +205,13 @@ export function deriveBlockClassifierGeometry(
186
205
  } else if (isPositiveFinite(input.keyframeIntervalMs)) {
187
206
  keyframeInterval = { ticks: input.keyframeIntervalMs, timescale: 1000 }
188
207
  }
208
+ const groupDuration = isPositiveFinite(input.groupDurationMs) ? { groupDurationMs: input.groupDurationMs } : {}
189
209
  const protect = (reason: ClassifierReason): BlockClassifierGeometry => ({
190
210
  trackKind: 'video',
191
211
  mode: 'all-protected',
192
212
  reason,
193
213
  ...(keyframeInterval === undefined ? {} : { keyframeInterval }),
214
+ ...groupDuration,
194
215
  })
195
216
 
196
217
  if (!isPositiveFinite(input.framerate)) return protect('framerate-absent')
@@ -211,9 +232,71 @@ export function deriveBlockClassifierGeometry(
211
232
  interleaveUnits,
212
233
  gopFrames,
213
234
  keyframeInterval,
235
+ ...groupDuration,
214
236
  }
215
237
  }
216
238
 
239
+ /**
240
+ * Why the MPU rule classes no block on a track (`BlockClassifier.mpuRuleOff`).
241
+ * Under every reason but the last the window rule classes none either: the
242
+ * track gets no `delta` (fec-multicast-01 Block Classification).
243
+ *
244
+ * The first three are the catalog's: it does not state that the publisher
245
+ * keeps one RAP to an MPU. It carries no usable keyframe interval (none, or
246
+ * one that is not a whole number of its unit), no group duration, or two that
247
+ * differ. The rest are what the stream showed. Each lasts for the epoch but
248
+ * the last, which ends at the next source discontinuity.
249
+ */
250
+ export type MpuRuleOffReason =
251
+ | 'keyframe-interval-absent'
252
+ | 'group-duration-absent'
253
+ | 'keyframe-interval-not-group-duration'
254
+ /** A DU header carried RAP_flag and was not the first sample of its movie fragment, or was held and lay in another fragment than the first header held of its MPU. */
255
+ | 'rap-inside-mpu'
256
+ /** An MPU held a sample one keyframe interval or more after another, by decode time. */
257
+ | 'mpu-longer-than-keyframe-interval'
258
+ /** `mpuBoundsRaps` went false (see `BlockClassifier.mpuBoundsRaps`). */
259
+ | 'mpu-bounds-raps-refuted'
260
+ /** Two DU headers lay in blocks against their authored order. */
261
+ | 'du-headers-out-of-order'
262
+
263
+ function isPositiveSafeInteger(value: number): boolean {
264
+ return Number.isSafeInteger(value) && value > 0
265
+ }
266
+
267
+ /**
268
+ * The catalog's side of the MPU rule (fec-multicast-01 Block Classification):
269
+ * a keyframe interval equal to the group duration is the publisher's
270
+ * statement that every MPU of the track holds one RAP, its first sample. A
271
+ * packet does not say so, and a publisher of an earlier revision could put
272
+ * more RAPs in an MPU. Null when the catalog states it, else what is missing.
273
+ *
274
+ * Integers compare exactly, as rationals: ticks / timescale against ms / 1000.
275
+ * A group duration that the catalog states in ticks reaches here as the
276
+ * double nearest ticks / timescale * 1000. Each side then carries at most two
277
+ * roundings, so the two are equal when they differ by no more than
278
+ * 2 * Number.EPSILON of the group duration (as exactInteger reads a quotient).
279
+ */
280
+ function mpuRuleCatalogReason(
281
+ geometry: Extract<BlockClassifierGeometry, { trackKind: 'video' }>,
282
+ ): MpuRuleOffReason | null {
283
+ const interval = geometry.keyframeInterval
284
+ if (
285
+ interval === undefined ||
286
+ !isPositiveSafeInteger(interval.ticks) ||
287
+ !isPositiveSafeInteger(interval.timescale)
288
+ ) {
289
+ return 'keyframe-interval-absent'
290
+ }
291
+ const groupMs = geometry.groupDurationMs
292
+ if (!isPositiveFinite(groupMs)) return 'group-duration-absent'
293
+ const { ticks, timescale } = interval
294
+ const equal = Number.isSafeInteger(groupMs)
295
+ ? BigInt(ticks) * 1000n === BigInt(groupMs) * BigInt(timescale)
296
+ : Math.abs((ticks / timescale) * 1000 - groupMs) <= 2 * Number.EPSILON * groupMs
297
+ return equal ? null : 'keyframe-interval-not-group-duration'
298
+ }
299
+
217
300
  /**
218
301
  * The keyframe interval expressed in a media track's timescale, or null when
219
302
  * the geometry states none or the interval is not an exact integer number of
@@ -251,8 +334,10 @@ export function keyframeInstantBetween(start: bigint, interval: bigint, from: bi
251
334
 
252
335
  /**
253
336
  * In-band evidence from ONE first-arrival source symbol received from the
254
- * network. Recovered symbols and repair symbols never contribute, and the
255
- * MFU `priority > 0x80` hint is not evidence.
337
+ * network. Repair symbols never contribute, and the MFU `priority > 0x80`
338
+ * hint is not evidence. A recovered symbol is no evidence for its own block
339
+ * and supports no class by the window rule; its DU header alone bounds the
340
+ * blocks around it for the MPU rule (BlockClassifier.observeRecovered).
256
341
  */
257
342
  export interface SourceSymbolEvidence {
258
343
  /** The MMTP header R (RAP) bit. */
@@ -283,12 +368,35 @@ export interface SourceSymbolEvidence {
283
368
  * The MMTP header packet_sequence_number (contiguous per packet_id). Not
284
369
  * classification evidence: FECManager uses it to bound how many blocks the
285
370
  * producer can have started between two source symbols, so an outage is
286
- * never mistaken for a source restart.
371
+ * never mistaken for a source restart. A hop may write it anew on every
372
+ * packet it forwards (cast's bridge does), so a gap in it, or none, says
373
+ * nothing of what was lost before that hop.
287
374
  */
288
375
  readonly packetSequenceNumber?: number
376
+ /**
377
+ * DU-header `dep_counter` (ISO/IEC 23008-1 `dependency_counter`). Carried
378
+ * for whoever wants to see it. Nothing here reads it: no class and no gap
379
+ * decision changes with its value.
380
+ */
381
+ readonly depCounter?: number
289
382
  }
290
383
 
291
- export type ReclassificationEvidence = 'rap' | 'mpu-span' | 'window' | 'classifier-disabled'
384
+ /**
385
+ * What moved a block's class. `mpu-rule`: the MPU numbers of the DU headers
386
+ * held before and after the block show that it holds no part of a RAP.
387
+ */
388
+ export type ReclassificationEvidence =
389
+ | 'rap'
390
+ | 'mpu-span'
391
+ | 'window'
392
+ | 'mpu-rule'
393
+ /**
394
+ * @deprecated Never emitted. It named the dependent run in `dep_counter`,
395
+ * which no longer classes a block. The name stays so that a consumer that
396
+ * spells it still compiles and an event recorded earlier still validates.
397
+ */
398
+ | 'dependent-run'
399
+ | 'classifier-disabled'
292
400
 
293
401
  export type ClassifierChange =
294
402
  | {
@@ -321,6 +429,18 @@ interface DataUnitStart {
321
429
  readonly sbn: number
322
430
  }
323
431
 
432
+ /** A held DU header as the MPU rule reads it. */
433
+ interface HeldHeader extends DataUnitStart {
434
+ readonly rap: boolean
435
+ /**
436
+ * Its FEC source symbol id when it arrived from the network. A header that
437
+ * FEC rebuilt has none here: it is not counted as a packet that arrived.
438
+ */
439
+ readonly ssId?: number
440
+ /** Its MPU position, where the wire proved one when it arrived (P3). */
441
+ readonly position?: number
442
+ }
443
+
324
444
  /**
325
445
  * Authored order of two data-unit starts of one MPU. Fragment numbers wrap
326
446
  * at 2^32, so they compare in RFC 1982 serial order.
@@ -332,6 +452,42 @@ function compareDataUnitStarts(
332
452
  return ((a.movieFragment - b.movieFragment) | 0) || a.idx - b.idx || a.offset - b.offset
333
453
  }
334
454
 
455
+ /** The first index of an SBN-ordered list whose block is `sbn` or later. */
456
+ function firstStartAtOrAfter(starts: readonly HeldHeader[], sbn: number): number {
457
+ let lo = 0
458
+ let hi = starts.length
459
+ while (lo < hi) {
460
+ const mid = (lo + hi) >>> 1
461
+ if (starts[mid]!.sbn < sbn) lo = mid + 1
462
+ else hi = mid
463
+ }
464
+ return lo
465
+ }
466
+
467
+ /**
468
+ * What arrived of one MPU. The MPU rule asks only about an MPU's start and
469
+ * about its last packet, so that is all that is kept however long the MPU.
470
+ */
471
+ interface ArrivedPackets {
472
+ /** Source symbol id to block, for the first ARRIVED_START_MAX packets that arrived. */
473
+ readonly start: Map<number, number>
474
+ /** The highest source symbol id among those that arrived. */
475
+ last: number
476
+ }
477
+
478
+ /** More packets than an MPU's metadata and first sample take; a longer start proves nothing. */
479
+ const ARRIVED_START_MAX = 4096
480
+
481
+ /** The first DU header after `headers[at]`, in authored order, of another sample. */
482
+ function nextSampleHeader(headers: readonly HeldHeader[], at: number): HeldHeader | undefined {
483
+ const of = headers[at]!
484
+ for (let i = at + 1; i < headers.length; i++) {
485
+ const header = headers[i]!
486
+ if (header.movieFragment !== of.movieFragment || header.idx !== of.idx) return header
487
+ }
488
+ return undefined
489
+ }
490
+
335
491
  /**
336
492
  * How many MPUs behind the newest released RAP a stale release can be. The
337
493
  * release gate holds a frame for seconds at most, so a late copy is a few
@@ -372,8 +528,11 @@ const UNPLACED: Placement = { rapNotMpuStart: false }
372
528
  * `delta→unknown` when an invariant disables classification. `keyframe` is
373
529
  * terminal.
374
530
  *
375
- * The delta window rule rests on three premises, each guarded by an
376
- * invariant that fires on positive evidence only:
531
+ * The delta window rule classes a block only on a track the MPU rule applies
532
+ * to: one whose catalog passes that rule's test and that has shown neither a
533
+ * RAP inside an MPU nor an MPU longer than the keyframe interval
534
+ * (`mpuRuleOff`). It rests on three premises, each guarded by an invariant
535
+ * that fires on positive evidence only:
377
536
  *
378
537
  * - P1: the source packets of one block are one contiguous run of the
379
538
  * stream's authored order, and blocks follow each other in SBN order
@@ -440,6 +599,50 @@ export class BlockClassifier {
440
599
  #mpuSbnSpans = new Map<number, { min: number; max: number }>()
441
600
  #dataUnitStarts = new Map<number, DataUnitStart[]>()
442
601
  #highestMpu: number | null = null
602
+ /**
603
+ * The DU headers held, per MPU in authored order, for the MPU rule. Kept in
604
+ * every mode (the rule needs no catalog cadence) for the same horizon and
605
+ * the same continuous SBN sequence as the P1 ledger.
606
+ */
607
+ #headers = new Map<number, HeldHeader[]>()
608
+ /**
609
+ * The source packets that arrived, per MPU. The MPU rule asks it whether
610
+ * every packet between two held DU headers arrived, and where. Same
611
+ * horizon as the headers.
612
+ */
613
+ #arrived = new Map<number, ArrivedPackets>()
614
+ #heldHighestMpu: number | null = null
615
+ /** Two DU headers of this sequence lay in blocks against their authored order: the MPU rule proves nothing. */
616
+ #headerOrderRefuted = false
617
+ /**
618
+ * A DU header held carried RAP_flag and was not of its MPU's first sample:
619
+ * not the first sample of its movie fragment, or in another movie fragment
620
+ * than the first DU header held of its MPU. This stream puts a RAP inside
621
+ * an MPU, and neither rule proves anything for the rest of the epoch. It is
622
+ * the MPU rule's own reading, in every DU-header layout and of rebuilt
623
+ * headers too. The first case is read on a header of an MPU behind the two
624
+ * kept as well. `mpuBoundsRaps`, which the stall or conceal decision reads,
625
+ * is set as before and not from here.
626
+ */
627
+ #rapInsideMpu = false
628
+ /** What the catalog lacks for the MPU rule, or null when it states a keyframe interval equal to the group duration. */
629
+ #mpuRuleCatalog: MpuRuleOffReason | null = null
630
+ /**
631
+ * The lowest and highest decode time known in an MPU, for the two MPUs of
632
+ * the highest numbers: those of the samples that held movie fragment
633
+ * metadata times (noteDecodeTimes). Valid within one MPU sequence, as the
634
+ * P1 ledger is; if MPU numbers go back with no source discontinuity, the
635
+ * new ones are not read until then, as their DU headers are not.
636
+ */
637
+ #decodeSpans = new Map<number, { readonly min: bigint; readonly max: bigint; readonly mediaTimescale: number }>()
638
+ /**
639
+ * An MPU held a sample one keyframe interval or more after another by
640
+ * decode time, so it lasts longer than the interval. A track of an earlier
641
+ * revision whose interval equals its group duration can hold a further RAP
642
+ * only in such an MPU: neither rule proves anything for the rest of the
643
+ * epoch.
644
+ */
645
+ #mpuOutlastsInterval = false
443
646
  /**
444
647
  * P3 layout, kept for the MPUs within the classification horizon and valid
445
648
  * within one continuous SBN sequence (`noteSourceDiscontinuity`).
@@ -488,6 +691,21 @@ export class BlockClassifier {
488
691
  return this.#mpuBoundsRaps
489
692
  }
490
693
 
694
+ /**
695
+ * Why the MPU rule classes no block on this track now, or null while it
696
+ * can. A catalog reason is known from the start of the epoch; the others
697
+ * name what the stream showed. A block the rule would have classed reads
698
+ * `unknown` under every one of them, and so does one the window rule would
699
+ * have classed, under every one but `du-headers-out-of-order`.
700
+ */
701
+ get mpuRuleOff(): MpuRuleOffReason | null {
702
+ if (this.#mpuRuleCatalog !== null) return this.#mpuRuleCatalog
703
+ if (this.#rapInsideMpu) return 'rap-inside-mpu'
704
+ if (this.#mpuOutlastsInterval) return 'mpu-longer-than-keyframe-interval'
705
+ if (!this.#mpuBoundsRaps) return 'mpu-bounds-raps-refuted'
706
+ return this.#headerOrderRefuted ? 'du-headers-out-of-order' : null
707
+ }
708
+
491
709
  /** Begin a fresh epoch (catalog change or track reset). */
492
710
  reset(geometry: BlockClassifierGeometry = this.#geometry): void {
493
711
  this.#geometry = geometry
@@ -496,6 +714,9 @@ export class BlockClassifier {
496
714
  this.#clearMpuLayout()
497
715
  this.#lastRap = null
498
716
  this.#mpuBoundsRaps = true
717
+ this.#rapInsideMpu = false
718
+ this.#mpuOutlastsInterval = false
719
+ this.#mpuRuleCatalog = geometry.trackKind === 'video' ? mpuRuleCatalogReason(geometry) : null
499
720
  if (geometry.trackKind === 'video' && geometry.mode === 'all-protected') {
500
721
  this.#mode = 'all-protected'
501
722
  this.#reason = geometry.reason
@@ -541,9 +762,16 @@ export class BlockClassifier {
541
762
  this.#lastRap = null
542
763
  }
543
764
 
544
- /** Register a block that exists without evidence (a vanished block). */
545
- touch(sbn: number): void {
546
- this.#blockFor(sbn)
765
+ /**
766
+ * Register a block that exists without evidence of its own: a vanished
767
+ * block, or one only repair symbols state. The DU headers already held
768
+ * around it class it now (the MPU rule); no later header need come between
769
+ * them to ask again.
770
+ */
771
+ touch(sbn: number): ClassifierChange[] {
772
+ const changes: ClassifierChange[] = []
773
+ this.#reclassify(sbn, this.#blockFor(sbn), changes)
774
+ return changes
547
775
  }
548
776
 
549
777
  /** Forget a resolved block. */
@@ -556,8 +784,15 @@ export class BlockClassifier {
556
784
  return this.#blocks.get(sbn)?.cls ?? 'unknown'
557
785
  }
558
786
 
559
- /** Record one first-arrival source symbol's evidence for block `sbn`. */
560
- observe(sbn: number, evidence: SourceSymbolEvidence): ClassifierChange[] {
787
+ /**
788
+ * Record one first-arrival source symbol's evidence for block `sbn`.
789
+ * `ssId` is its FEC source symbol id (the block's SS_Start plus its ESI,
790
+ * ISO/IEC 23008-1 C.5.2). The publisher numbers the packets of the FEC
791
+ * flow with it, one each, so the MPU rule reads from it whether every
792
+ * packet between two DU headers arrived. Without it the rule's two
793
+ * exceptions prove nothing.
794
+ */
795
+ observe(sbn: number, evidence: SourceSymbolEvidence, ssId?: number): ClassifierChange[] {
561
796
  if (this.#geometry.trackKind === 'audio') return []
562
797
  const changes: ClassifierChange[] = []
563
798
  const block = this.#blockFor(sbn)
@@ -575,25 +810,157 @@ export class BlockClassifier {
575
810
 
576
811
  // A RAP inside an MPU refutes "an MPU boundary bounds RAPs" whatever the
577
812
  // classifier mode, because gap decisions rely on it in every mode.
578
- if (placement.rapNotMpuStart) this.#mpuBoundsRaps = false
813
+ if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes)
579
814
 
580
815
  const violation = this.#checkInvariants(sbn, block, evidence, placement)
581
816
  if (violation !== null) changes.push(...this.#disable(violation))
582
817
 
583
- const next = this.#classify(block)
584
- if (next !== block.cls && this.#allowed(block.cls, next)) {
585
- changes.push({
586
- kind: 'reclassified',
587
- sbn,
588
- from: block.cls,
589
- to: next,
590
- evidence: this.#evidenceFor(block, next),
591
- })
592
- block.cls = next
818
+ this.#noteArrived(sbn, evidence.mpu, ssId)
819
+ const bounds = this.#noteHeader(sbn, evidence, position, ssId, changes)
820
+ this.#reclassify(sbn, block, changes)
821
+ // A new DU header can bound any block held: it may have had its last
822
+ // symbol already.
823
+ if (bounds) this.#reclassifyOthers(sbn, changes)
824
+ return changes
825
+ }
826
+
827
+ /**
828
+ * A first-arrival source symbol placed in a repair-less span (IsoBlockLocator:
829
+ * the SS_IDs between two stated blocks whose every repair was lost). A span
830
+ * is no block: it can hold several producer blocks, so nothing block-scoped
831
+ * is read from it (no record, P1, P2 or MPU-rule bound) and its blocks stay
832
+ * unknown. What its DU header says of its MPU (P3) still counts (BLO-57323).
833
+ */
834
+ observeInSpan(evidence: SourceSymbolEvidence): ClassifierChange[] {
835
+ if (this.#geometry.trackKind === 'audio') return []
836
+ const changes: ClassifierChange[] = []
837
+ const placement = this.#place(evidence)
838
+ if (placement.rapNotMpuStart) this.#refuteMpuBounds(changes)
839
+ const geometry = this.#geometry
840
+ if (this.#mode === 'all-protected' || geometry.mode !== 'classifying') return changes
841
+ if (placement.rapNotMpuStart) changes.push(...this.#disable('rap-not-mpu-start'))
842
+ else if (placement.position !== undefined && placement.position >= geometry.gopFrames) {
843
+ changes.push(...this.#disable('mpu-longer-than-gop'))
844
+ } else if (placement.violation !== undefined) changes.push(...this.#disable(placement.violation))
845
+ return changes
846
+ }
847
+
848
+ /**
849
+ * The DU header of a source packet that a decode rebuilt, in block `sbn`.
850
+ * It bounds the blocks around that block for the MPU rule as a header that
851
+ * arrived does: the rule reads the DU headers the receiver holds. The
852
+ * rebuilt block is whole, so it gets no class and no record, and the
853
+ * packet is no evidence for P1 or P3, which rest on what arrived: it
854
+ * supports no class by the window rule, and can only end it. It is not
855
+ * counted as a packet that arrived either (#arrivedBetween).
856
+ */
857
+ observeRecovered(sbn: number, evidence: SourceSymbolEvidence): ClassifierChange[] {
858
+ if (this.#geometry.trackKind === 'audio') return []
859
+ const { mpu, idx, movieFragment } = evidence
860
+ if (mpu === undefined || idx === undefined || movieFragment === undefined) return []
861
+ const changes: ClassifierChange[] = []
862
+ // A second sample in a movie fragment is a fact of the stream whoever
863
+ // shows it. Fragment numbers stop counting samples, and where an MPU has
864
+ // shown two fragments the layout the window rule stands on is gone: say
865
+ // so now, as #place does for a header that arrives.
866
+ if (idx !== 0) {
867
+ this.#multiSampleFragment = true
868
+ const geometry = this.#geometry
869
+ if (this.#fragmentPerFrame && geometry.trackKind === 'video' && geometry.mode === 'classifying') {
870
+ changes.push(...this.#disable('mpu-multiple-fragments'))
871
+ }
872
+ }
873
+ if (this.#noteHeader(sbn, evidence, this.#positionHeld(mpu, idx, movieFragment), undefined, changes)) {
874
+ this.#reclassifyOthers(sbn, changes)
875
+ }
876
+ return changes
877
+ }
878
+
879
+ /**
880
+ * Decode times the receiver can determine: `first` and `last` are those of
881
+ * the first and the last sample that one held movie fragment's metadata
882
+ * (FT=1) times, of MPU `mpu`, in ticks of `mediaTimescale`; a `trun` lists
883
+ * samples in decode order, so `first` is not after `last`. They are read
884
+ * for one thing, and only on a track the MPU rule applies to: an MPU with
885
+ * two samples a keyframe interval or more apart lasts longer than the
886
+ * interval, so its first sample need not be its only RAP. The rule then
887
+ * stops for the rest of the epoch, the window rule with it, and every delta
888
+ * class goes (fec-multicast-01 Block Classification). No class comes from
889
+ * a decode time. The MPU's first sample is never later than the earliest
890
+ * one known, so the known span is no longer than the real one.
891
+ */
892
+ noteDecodeTimes(mpu: number, first: bigint, last: bigint, mediaTimescale: number): ClassifierChange[] {
893
+ const changes: ClassifierChange[] = []
894
+ const geometry = this.#geometry
895
+ if (geometry.trackKind !== 'video' || this.#mpuRuleCatalog !== null || !isPositiveSafeInteger(mediaTimescale)) {
896
+ return changes
897
+ }
898
+ const held = this.#decodeSpans.get(mpu)
899
+ // Ticks of another timescale are another clock: the MPU's span starts again.
900
+ const known = held?.mediaTimescale === mediaTimescale ? held : undefined
901
+ let late = false
902
+ if (held === undefined && this.#decodeSpans.size >= 2) {
903
+ // Kept by MPU number, as the DU headers are: the two highest. A report for an MPU behind both is late (a
904
+ // slow repair) and must not push out the MPU the stream is in: it is not kept, and only its own span is read.
905
+ const lowest = Math.min(...this.#decodeSpans.keys())
906
+ late = mpu < lowest
907
+ if (!late) this.#decodeSpans.delete(lowest)
908
+ }
909
+ const min = known !== undefined && known.min < first ? known.min : first
910
+ const max = known !== undefined && known.max > last ? known.max : last
911
+ if (!late) this.#decodeSpans.set(mpu, { min, max, mediaTimescale })
912
+ // The catalog test passed, so the interval is stated in whole ticks.
913
+ const { ticks, timescale } = geometry.keyframeInterval!
914
+ if ((max - min) * BigInt(timescale) >= BigInt(ticks) * BigInt(mediaTimescale)) {
915
+ this.#mpuOutlastsInterval = true
916
+ this.#withdraw(changes)
593
917
  }
594
918
  return changes
595
919
  }
596
920
 
921
+ /** Ask again for every block held but `own`: a new DU header can bound any of them. */
922
+ #reclassifyOthers(own: number, changes: ClassifierChange[]): void {
923
+ for (const [sbn, block] of this.#blocks) {
924
+ if (sbn !== own) this.#reclassify(sbn, block, changes)
925
+ }
926
+ }
927
+
928
+ /**
929
+ * Move delta blocks back to unknown: a premise their class stood on is
930
+ * gone. After DU headers out of block order, what the window rule still
931
+ * holds for is classed again as its blocks are seen.
932
+ */
933
+ #withdraw(changes: ClassifierChange[]): void {
934
+ for (const [sbn, block] of this.#blocks) {
935
+ if (block.cls !== 'delta') continue
936
+ block.cls = 'unknown'
937
+ changes.push({ kind: 'reclassified', sbn, from: 'delta', to: 'unknown', evidence: 'classifier-disabled' })
938
+ }
939
+ }
940
+
941
+ /**
942
+ * An MPU boundary stopped bounding this stream's RAPs: neither rule proves
943
+ * anything from now on, and every delta class goes.
944
+ */
945
+ #refuteMpuBounds(changes: ClassifierChange[]): void {
946
+ if (!this.#mpuBoundsRaps) return
947
+ this.#mpuBoundsRaps = false
948
+ this.#withdraw(changes)
949
+ }
950
+
951
+ #reclassify(sbn: number, block: BlockEvidence, changes: ClassifierChange[]): void {
952
+ const next = this.#classify(block, sbn)
953
+ if (next === block.cls || !this.#allowed(block.cls, next)) return
954
+ changes.push({
955
+ kind: 'reclassified',
956
+ sbn,
957
+ from: block.cls,
958
+ to: next,
959
+ evidence: this.#evidenceFor(block, next),
960
+ })
961
+ block.cls = next
962
+ }
963
+
597
964
  /**
598
965
  * Record a RAP frame released in order. Released MPU-start RAPs of MPUs m
599
966
  * and m+n must be exactly n keyframe intervals apart in the media
@@ -634,7 +1001,9 @@ export class BlockClassifier {
634
1001
  previous.decodeTime === undefined ||
635
1002
  (decodeTime - previous.decodeTime) % interval !== 0n
636
1003
  ) {
637
- this.#mpuBoundsRaps = false
1004
+ const changes: ClassifierChange[] = []
1005
+ this.#refuteMpuBounds(changes)
1006
+ return changes
638
1007
  }
639
1008
  return []
640
1009
  }
@@ -794,6 +1163,19 @@ export class BlockClassifier {
794
1163
  }
795
1164
  }
796
1165
 
1166
+ /**
1167
+ * The MPU position #place gives a DU header, read from the layout the
1168
+ * arrived headers built and recording nothing: where a rebuilt header
1169
+ * stands for the catalog interval's check in the MPU rule.
1170
+ */
1171
+ #positionHeld(mpu: number, idx: number, fragment: number): number | undefined {
1172
+ if (!this.#fragmentPerFrame || this.#multiSampleFragment) return idx
1173
+ const anchor = this.#mpus.get(mpu)?.anchor
1174
+ if (anchor === undefined) return undefined
1175
+ const offset = (fragment - anchor) | 0
1176
+ return offset === 0 || (offset > 0 && this.#fragmentsProven) ? offset : undefined
1177
+ }
1178
+
797
1179
  /**
798
1180
  * How many fragments MPU m's anchor `fragment` lies past the start that
799
1181
  * the anchor received last predicts for MPU m: one frame per fragment and
@@ -828,6 +1210,11 @@ export class BlockClassifier {
828
1210
  this.#mpuSbnSpans.clear()
829
1211
  this.#dataUnitStarts.clear()
830
1212
  this.#highestMpu = null
1213
+ this.#headers.clear()
1214
+ this.#arrived.clear()
1215
+ this.#heldHighestMpu = null
1216
+ this.#headerOrderRefuted = false
1217
+ this.#decodeSpans.clear()
831
1218
  }
832
1219
 
833
1220
  /**
@@ -924,28 +1311,272 @@ export class BlockClassifier {
924
1311
  return changes
925
1312
  }
926
1313
 
927
- #classify(block: BlockEvidence): BlockClass {
1314
+ #classify(block: BlockEvidence, sbn: number): BlockClass {
928
1315
  if (block.rapSeen || block.mpus.size >= 2) return 'keyframe'
929
- if (this.#mode === 'all-protected') return 'unknown'
1316
+ // Only a keyframe or a withdrawal moves a delta block: no symbol re-proves it.
1317
+ if (block.cls === 'delta') return 'delta'
1318
+ if (this.#windowHolds(block) || this.#mpuRuleHolds(block, sbn)) return 'delta'
1319
+ return 'unknown'
1320
+ }
1321
+
1322
+ #windowHolds(block: BlockEvidence): boolean {
1323
+ // A track the MPU rule does not apply to gets no delta at all (fec-multicast-01 Block Classification): one whose
1324
+ // catalog fails the test, or that showed a RAP inside an MPU or an MPU longer than the keyframe interval. DU
1325
+ // headers out of block order stop the MPU rule alone: this rule has its own check of the order (P1).
1326
+ const off = this.mpuRuleOff
1327
+ if (this.#mode === 'all-protected' || (off !== null && off !== 'du-headers-out-of-order')) return false
930
1328
  const geometry = this.#geometry
931
- if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') return 'unknown'
1329
+ if (geometry.trackKind !== 'video' || geometry.mode !== 'classifying') return false
932
1330
  if (
933
- block.mpus.size === 1 &&
934
- block.positionMin !== undefined &&
935
- block.positionMax !== undefined
1331
+ block.mpus.size !== 1 ||
1332
+ block.positionMin === undefined ||
1333
+ block.positionMax === undefined
936
1334
  ) {
937
- // A block closes every D media units, so its frames are contiguous and
938
- // lie in [positionMax − D + 1, positionMin + D − 1] of MPU m. Position
939
- // 0 is the only RAP of an MPU and G bounds its length.
940
- const span = geometry.interleaveUnits - 1
1335
+ return false
1336
+ }
1337
+ // A block closes every D media units, so its frames are contiguous and
1338
+ // lie in [positionMax − D + 1, positionMin + D − 1] of MPU m. Position
1339
+ // 0 is the only RAP of an MPU and G bounds its length.
1340
+ const span = geometry.interleaveUnits - 1
1341
+ return block.positionMax - span >= 1 && block.positionMin + span <= geometry.gopFrames - 1
1342
+ }
1343
+
1344
+ /**
1345
+ * Keep the header and arrival ledgers to the two newest MPUs. False for an
1346
+ * MPU behind them, which is not kept: no block still asked lies there, and
1347
+ * the ledgers stay bounded when MPU numbers go back with no source
1348
+ * discontinuity (a restart nothing signalled, or the 2^32 wrap). The rule
1349
+ * is then silent until the next one.
1350
+ */
1351
+ #noteHeldMpu(mpu: number): boolean {
1352
+ const highest = this.#heldHighestMpu
1353
+ if (highest !== null && mpu <= highest) return mpu + 1 >= highest
1354
+ this.#heldHighestMpu = mpu
1355
+ for (const held of [this.#headers, this.#arrived]) {
1356
+ for (const other of [...held.keys()]) {
1357
+ if (other + 1 < mpu) held.delete(other)
1358
+ }
1359
+ }
1360
+ return true
1361
+ }
1362
+
1363
+ /** Record a source packet that arrived as source symbol `ssId`, for #arrivedBetween. */
1364
+ #noteArrived(sbn: number, mpu: number | undefined, ssId: number | undefined): void {
1365
+ if (mpu === undefined || ssId === undefined || !this.#noteHeldMpu(mpu)) return
1366
+ const arrived = this.#arrived.get(mpu)
1367
+ if (arrived === undefined) this.#arrived.set(mpu, { start: new Map([[ssId, sbn]]), last: ssId })
1368
+ else {
1369
+ if (arrived.start.size < ARRIVED_START_MAX) arrived.start.set(ssId, sbn)
1370
+ if (ssId > arrived.last) arrived.last = ssId
1371
+ }
1372
+ }
1373
+
1374
+ /**
1375
+ * Record a held DU header for the MPU rule; `ssId` is its source symbol id
1376
+ * when it arrived, undefined for one that FEC rebuilt. True when it is new
1377
+ * and in order: the blocks held are then asked again. Blocks follow
1378
+ * authored order (P1), so the first header that lies against it withdraws
1379
+ * every class, and the rule proves nothing for the rest of the sequence.
1380
+ */
1381
+ #noteHeader(
1382
+ sbn: number,
1383
+ evidence: SourceSymbolEvidence,
1384
+ position: number | undefined,
1385
+ ssId: number | undefined,
1386
+ changes: ClassifierChange[],
1387
+ ): boolean {
1388
+ const { mpu, idx, movieFragment } = evidence
1389
+ if (this.#geometry.trackKind !== 'video' || mpu === undefined || idx === undefined || movieFragment === undefined) {
1390
+ return false
1391
+ }
1392
+ if (!this.#noteHeldMpu(mpu)) {
1393
+ // A header of an MPU behind the two newest is not kept. A RAP that is not the first sample of its movie
1394
+ // fragment needs nothing else held to show it, so that much is still read.
1395
+ if (evidence.rap && idx !== 0 && !this.#rapInsideMpu) {
1396
+ this.#rapInsideMpu = true
1397
+ this.#withdraw(changes)
1398
+ }
1399
+ return false
1400
+ }
1401
+ const header: HeldHeader = {
1402
+ movieFragment,
1403
+ idx,
1404
+ offset: evidence.offset ?? 0,
1405
+ sbn,
1406
+ rap: evidence.rap,
1407
+ ...(ssId === undefined ? {} : { ssId }),
1408
+ ...(position === undefined ? {} : { position }),
1409
+ }
1410
+ let headers = this.#headers.get(mpu)
1411
+ if (headers === undefined) {
1412
+ headers = []
1413
+ this.#headers.set(mpu, headers)
1414
+ }
1415
+ let at = 0
1416
+ let end = headers.length
1417
+ while (at < end) {
1418
+ const mid = (at + end) >>> 1
1419
+ if (compareDataUnitStarts(headers[mid]!, header) < 0) at = mid + 1
1420
+ else end = mid
1421
+ }
1422
+ if (at < headers.length && compareDataUnitStarts(headers[at]!, header) === 0) return false
1423
+ headers.splice(at, 0, header)
1424
+ // A RAP is an MPU's first sample. A RAP-flagged header is a RAP inside the MPU when it is not the first sample of
1425
+ // its movie fragment (whatever else is held: a header that FEC rebuilt may be the only one of its MPU), or when
1426
+ // its movie fragment is not that of the first header held.
1427
+ const first = headers[0]!
1428
+ if (
1429
+ !this.#rapInsideMpu &&
1430
+ ((header.rap && header.idx !== 0) ||
1431
+ (at === 0 ? headers : [header]).some((held) => held.rap && held.movieFragment !== first.movieFragment))
1432
+ ) {
1433
+ this.#rapInsideMpu = true
1434
+ this.#withdraw(changes)
1435
+ }
1436
+ const before = headers[at - 1]?.sbn
1437
+ const after = headers[at + 1]?.sbn
1438
+ if ((before !== undefined && before > sbn) || (after !== undefined && after < sbn)) {
1439
+ if (!this.#headerOrderRefuted) {
1440
+ this.#headerOrderRefuted = true
1441
+ this.#withdraw(changes)
1442
+ }
1443
+ return false
1444
+ }
1445
+ return true
1446
+ }
1447
+
1448
+ /**
1449
+ * The MPU rule. L is the DU header held last before the block and U the
1450
+ * one held first after it. Every packet carries its MPU number, and an MPU
1451
+ * holds one RAP: its first sample.
1452
+ *
1453
+ * - R1, L and U in one MPU: the block holds no part of a RAP, provided the
1454
+ * MPU's first sample ended before the block (#firstSampleEndedBefore).
1455
+ * - R2, U in the next MPU: the block may hold the start of that MPU,
1456
+ * unless that start arrived whole (#startArrivedWhole). The block is
1457
+ * then the tail of L's MPU, and R1's proviso decides.
1458
+ * - R3, more than one MPU apart: a whole MPU is gone, its RAP with it.
1459
+ * - R4, no U held yet (or no L): not known. The next DU header asks again.
1460
+ *
1461
+ * It rests on the publisher keeping one RAP to an MPU, which no packet
1462
+ * says. So it classes nothing unless the catalog states a keyframe interval
1463
+ * equal to the group duration, and nothing once the stream showed
1464
+ * otherwise: a RAP inside an MPU (mpuBoundsRaps, or a RAP-flagged DU header
1465
+ * held that is not of its MPU's first sample: #noteHeader), an MPU longer than the
1466
+ * keyframe interval by the decode times known (noteDecodeTimes), or DU
1467
+ * headers against the block order. `mpuRuleOff` names which. `dep_counter`
1468
+ * is not read.
1469
+ */
1470
+ #mpuRuleHolds(block: BlockEvidence, sbn: number): boolean {
1471
+ // shortcut: reads the DU headers of the blocks around this one, not the nearest inside it, so it classes fewer blocks than the rule allows; upgrade when observe() is given symbol positions.
1472
+ if (this.mpuRuleOff !== null) return false
1473
+ let lower: HeldHeader | undefined
1474
+ let upper: HeldHeader | undefined
1475
+ let lowerMpu = 0
1476
+ let upperMpu = 0
1477
+ let lowerAt = 0
1478
+ let upperAt = 0
1479
+ for (const [mpu, headers] of this.#headers) {
1480
+ // While the order holds, sbn never decreases along a list: split it at this block.
1481
+ const before = firstStartAtOrAfter(headers, sbn) - 1
1482
+ const after = firstStartAtOrAfter(headers, sbn + 1)
1483
+ const below = headers[before]
1484
+ const above = headers[after]
1485
+ // The nearest block decides. Where two MPUs meet in one block, the later MPU is the nearer below and the earlier above.
941
1486
  if (
942
- block.positionMax - span >= 1 &&
943
- block.positionMin + span <= geometry.gopFrames - 1
1487
+ below !== undefined &&
1488
+ (lower === undefined || below.sbn > lower.sbn || (below.sbn === lower.sbn && mpu > lowerMpu))
944
1489
  ) {
945
- return 'delta'
1490
+ lower = below
1491
+ lowerMpu = mpu
1492
+ lowerAt = before
1493
+ }
1494
+ if (
1495
+ above !== undefined &&
1496
+ (upper === undefined || above.sbn < upper.sbn || (above.sbn === upper.sbn && mpu < upperMpu))
1497
+ ) {
1498
+ upper = above
1499
+ upperMpu = mpu
1500
+ upperAt = after
946
1501
  }
947
1502
  }
948
- return 'unknown'
1503
+ if (lower === undefined || upper === undefined) return false
1504
+ if (block.mpus.size === 1 && !block.mpus.has(lowerMpu)) return false
1505
+ if (upperMpu === lowerMpu) {
1506
+ // A RAP header after L in L's MPU is L's own sample again: the block lies inside the MPU's first sample.
1507
+ if (upper.rap) return false
1508
+ // The catalog interval wins where it places a keyframe between the two.
1509
+ const geometry = this.#geometry
1510
+ if (
1511
+ geometry.trackKind === 'video' &&
1512
+ geometry.mode === 'classifying' &&
1513
+ lower.position !== undefined &&
1514
+ upper.position !== undefined &&
1515
+ Math.floor(upper.position / geometry.gopFrames) > Math.floor(lower.position / geometry.gopFrames)
1516
+ ) {
1517
+ return false
1518
+ }
1519
+ } else if (upperMpu !== lowerMpu + 1 || !this.#startArrivedWhole(upperMpu, upperAt)) {
1520
+ // R3 is stated here, and kept by the ledgers too: a header two MPUs behind the newest is not held.
1521
+ return false
1522
+ }
1523
+ return this.#firstSampleEndedBefore(sbn, lowerMpu, lowerAt)
1524
+ }
1525
+
1526
+ /**
1527
+ * R1's proviso for block `sbn`, where header `at` of MPU `mpu` is the one
1528
+ * held last before it: no part of the MPU's first sample lies in the
1529
+ * block. A sample start without RAP_flag is not the first sample. Any
1530
+ * other header may be of it (a later data unit of a sample need not repeat
1531
+ * the flag). That sample ended before the block only if every packet from
1532
+ * the header to the next sample's DU header arrived, in earlier blocks.
1533
+ */
1534
+ #firstSampleEndedBefore(sbn: number, mpu: number, at: number): boolean {
1535
+ const headers = this.#headers.get(mpu)!
1536
+ const lower = headers[at]!
1537
+ if (lower.offset === 0 && !lower.rap) return true
1538
+ // shortcut: a packet between the two headers that lies in the block itself counts as one of the first sample, though it may be the next fragment's metadata, so where every block opens with movie fragment metadata (FFmpeg's muxer) the block after a keyframe stays unknown; upgrade when the evidence says which packets are metadata.
1539
+ const next = nextSampleHeader(headers, at)
1540
+ return next !== undefined && this.#arrivedBetween(mpu, lower, next, sbn)
1541
+ }
1542
+
1543
+ /**
1544
+ * R2's exception: the start of MPU `mpu` arrived whole. Its header `at`,
1545
+ * the DU header held first after the block, is of the MPU's RAP. Every
1546
+ * packet before it arrived, back to the last packet of the MPU before: so
1547
+ * did the MPU and movie fragment metadata sent before the sample. And
1548
+ * every packet after it arrived, up to the next sample's DU header.
1549
+ */
1550
+ #startArrivedWhole(mpu: number, at: number): boolean {
1551
+ const headers = this.#headers.get(mpu)!
1552
+ const first = headers[at]!
1553
+ const arrived = this.#arrived.get(mpu)
1554
+ const previous = this.#arrived.get(mpu - 1)
1555
+ if (!first.rap || first.ssId === undefined || arrived === undefined || previous === undefined) return false
1556
+ let ssId = first.ssId - 1
1557
+ while (arrived.start.has(ssId)) ssId--
1558
+ if (ssId !== previous.last) return false
1559
+ const next = nextSampleHeader(headers, at)
1560
+ return next !== undefined && this.#arrivedBetween(mpu, first, next)
1561
+ }
1562
+
1563
+ /**
1564
+ * Whether every packet sent after DU header `from` and before DU header
1565
+ * `to`, both of MPU `mpu`, arrived as a packet of that MPU, each in a block
1566
+ * before `before` when one is given. The source symbol id counts every
1567
+ * packet of the FEC flow, so no id may be missing between the two. Ids are
1568
+ * read as plain numbers, as block starts are: past the 2^32 wrap of the id
1569
+ * nothing is proved.
1570
+ */
1571
+ #arrivedBetween(mpu: number, from: HeldHeader, to: HeldHeader, before?: number): boolean {
1572
+ // shortcut: a packet that FEC rebuilt does not count as arrived (only the DU headers of rebuilt packets are handed over), so a start that FEC completed proves nothing here; upgrade when the router hands every rebuilt packet over with its source symbol id.
1573
+ const arrived = this.#arrived.get(mpu)
1574
+ if (arrived === undefined || from.ssId === undefined || to.ssId === undefined) return false
1575
+ for (let ssId = from.ssId + 1; ssId !== to.ssId; ssId++) {
1576
+ const sbn = arrived.start.get(ssId)
1577
+ if (sbn === undefined || (before !== undefined && sbn >= before)) return false
1578
+ }
1579
+ return true
949
1580
  }
950
1581
 
951
1582
  #allowed(from: BlockClass, to: BlockClass): boolean {
@@ -956,7 +1587,7 @@ export class BlockClassifier {
956
1587
  }
957
1588
 
958
1589
  #evidenceFor(block: BlockEvidence, to: BlockClass): ReclassificationEvidence {
959
- if (to === 'delta') return 'window'
1590
+ if (to === 'delta') return this.#windowHolds(block) ? 'window' : 'mpu-rule'
960
1591
  return block.rapSeen ? 'rap' : 'mpu-span'
961
1592
  }
962
1593
  }