@blockcast/mmt-container 2.2.0-main.a88c3a0aa4f3 → 2.2.0-main.bdefba2a99c2

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 (77) hide show
  1. package/README.md +29 -17
  2. package/dist/browser-runtime.js +491 -177
  3. package/dist/browser-runtime.js.map +4 -4
  4. package/dist/carp-catalog.js.map +1 -1
  5. package/dist/catalog-fec-params.d.ts +17 -1
  6. package/dist/catalog-fec-params.d.ts.map +1 -1
  7. package/dist/catalog-fec-params.js +15 -0
  8. package/dist/catalog-fec-params.js.map +2 -2
  9. package/dist/catalog-network-source.js.map +1 -1
  10. package/dist/cmcd-producer.d.ts +60 -47
  11. package/dist/cmcd-producer.d.ts.map +1 -1
  12. package/dist/cmcd-producer.js +138 -109
  13. package/dist/cmcd-producer.js.map +2 -2
  14. package/dist/delivery-catalog.js +24 -15
  15. package/dist/delivery-catalog.js.map +2 -2
  16. package/dist/delta-fallback-config.js.map +1 -1
  17. package/dist/fec-manager.js.map +2 -2
  18. package/dist/fec-state.js.map +1 -1
  19. package/dist/fec-worker-setup.d.ts +1 -1
  20. package/dist/fec-worker-setup.js +1 -1
  21. package/dist/fec-worker-setup.js.map +1 -1
  22. package/dist/held-layer-admission.js.map +1 -1
  23. package/dist/index.d.ts +4 -3
  24. package/dist/index.d.ts.map +1 -1
  25. package/dist/index.js +9 -1
  26. package/dist/index.js.map +2 -2
  27. package/dist/iso-block-locator.js.map +1 -1
  28. package/dist/media-router.js.map +1 -1
  29. package/dist/mfu-reassembler.js +12 -19
  30. package/dist/mfu-reassembler.js.map +2 -2
  31. package/dist/mmtp-container-parser.js +12 -19
  32. package/dist/mmtp-container-parser.js.map +2 -2
  33. package/dist/mmtp-container-parser.no-modules.js +133 -34
  34. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  35. package/dist/mmtp-decode-pipeline.js +12 -19
  36. package/dist/mmtp-decode-pipeline.js.map +2 -2
  37. package/dist/mmtp-fec-session.d.ts +41 -3
  38. package/dist/mmtp-fec-session.d.ts.map +1 -1
  39. package/dist/mmtp-fec-session.js +118 -13
  40. package/dist/mmtp-fec-session.js.map +3 -3
  41. package/dist/mmtp-router.js +36 -34
  42. package/dist/mmtp-router.js.map +2 -2
  43. package/dist/multicast-auth-catalog.js.map +1 -1
  44. package/dist/multicast-input.js.map +1 -1
  45. package/dist/multicast-manager.d.ts +2 -0
  46. package/dist/multicast-manager.d.ts.map +1 -1
  47. package/dist/multicast-manager.js +37 -34
  48. package/dist/multicast-manager.js.map +2 -2
  49. package/dist/multicast-transport.js +24 -15
  50. package/dist/multicast-transport.js.map +2 -2
  51. package/dist/multicast-unwrap.js +12 -19
  52. package/dist/multicast-unwrap.js.map +2 -2
  53. package/dist/no-modules.js +130 -33
  54. package/dist/no-modules.js.map +3 -3
  55. package/dist/repair-fetch.js.map +1 -1
  56. package/dist/repair-layer-subscriptions.d.ts +82 -0
  57. package/dist/repair-layer-subscriptions.d.ts.map +1 -0
  58. package/dist/repair-layer-subscriptions.js +192 -0
  59. package/dist/repair-layer-subscriptions.js.map +7 -0
  60. package/dist/signaling.js.map +2 -2
  61. package/dist/timestamp-codec.js +12 -19
  62. package/dist/timestamp-codec.js.map +2 -2
  63. package/dist/track-session.d.ts +1 -1
  64. package/dist/track-session.js.map +1 -1
  65. package/dist/wasm-mfu-reassembler.js.map +1 -1
  66. package/dist/wasm-mmtp-container-parser.js +12 -19
  67. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  68. package/package.json +8 -5
  69. package/schemas/catalog.schema.json +4 -0
  70. package/src/catalog-fec-params.ts +36 -1
  71. package/src/cmcd-producer.ts +189 -179
  72. package/src/fec-worker-setup.ts +2 -2
  73. package/src/index.ts +17 -2
  74. package/src/mmtp-fec-session.ts +115 -15
  75. package/src/multicast-manager.ts +3 -0
  76. package/src/repair-layer-subscriptions.ts +261 -0
  77. package/src/track-session.ts +1 -1
package/src/index.ts CHANGED
@@ -526,10 +526,13 @@ export {
526
526
  type FecStarvationDetectorConfig,
527
527
  } from './fec-starvation-detector.js'
528
528
 
529
- // CMCD Producer (x-bc-* vendor key telemetry, BLO-1044)
529
+ // CMCD v2 Event-mode producer (CTA-5004-B, com.blockcast-* custom keys)
530
530
  export {
531
531
  CmcdProducer,
532
- type CmcdParams,
532
+ encodeCmcdRecord,
533
+ type CmcdRecord,
534
+ type CmcdToken,
535
+ type CmcdValue,
533
536
  type CmcdProducerOptions,
534
537
  type SnapshotData,
535
538
  type TransportSnapshot,
@@ -546,6 +549,7 @@ export {
546
549
  type TrackFecParams,
547
550
  type TrackFecUnavailable,
548
551
  catalogTrackFecUnavailable,
552
+ catalogTrackDeliveryMode,
549
553
  catalogGroupDurationMs,
550
554
  catalogKeyframeCadenceMs,
551
555
  catalogFecMediaUnitsPerSecond,
@@ -602,11 +606,22 @@ export {
602
606
  type MmtpFecSessionConfig,
603
607
  type MmtpFecSessionDecoder,
604
608
  type MmtpFecSessionDecoderConstructor,
609
+ type MmtpFecSessionMessageConfig,
610
+ type MmtpFecSessionMessageUpdate,
605
611
  type MmtpFecSessionMixedPathStats,
606
612
  type MmtpFecSessionPath,
607
613
  type MmtpFecSessionPathCounts,
608
614
  type MmtpFecSessionStats,
609
615
  } from "./mmtp-fec-session.js";
616
+ // MoQ repair-layer subscriptions by measured loss (BLO-35456)
617
+ export {
618
+ RepairLayerSubscriptions,
619
+ type MoqRepairDelivery,
620
+ type RepairLayerSource,
621
+ type RepairLayerSubscriptionsOptions,
622
+ type RepairLayerSubscriptionsSnapshot,
623
+ type RepairTrackSubscription,
624
+ } from "./repair-layer-subscriptions.js";
610
625
 
611
626
  export {
612
627
  catalogAmtNetworkSource,
@@ -23,6 +23,15 @@
23
23
  * uses. A packet below B_0 at or after the anchor fails the session closed:
24
24
  * `stats.failClosed` reports why, and every later repair is refused.
25
25
  *
26
+ * Catalog-less (draft-ramadan-moq-mmt-02 8.3, 13.2): a receiver holding
27
+ * layer 0 under the AL-FEC message alone builds the session from the message's
28
+ * fec_flow entry (`alFecFlow`) instead. K, T, the code point and the repair
29
+ * packet_id come from that entry, and layer 0 is held at
30
+ * maximum_p_for_repair_flow, standing for O_0 + P_0, by the anchored clause of
31
+ * draft-ramadan-moq-fec-core-00 7.3.2 alone. A later version that raises the
32
+ * field raises the held total (updateAlFecFlow()); the message carries no
33
+ * millisecond budget, so the caller states the retention (fec-core-00 9.4).
34
+ *
26
35
  * Every repair packet that cannot be used is counted under the reason it was
27
36
  * refused, and every block ends under exactly one outcome, so a stream whose
28
37
  * FEC is doing nothing can be told apart from one with nothing to repair.
@@ -30,6 +39,8 @@
30
39
 
31
40
  import {
32
41
  admitMmtpRepairObject,
42
+ alFecRaptorQFlowConfig,
43
+ FEC_CODE_RAPTORQ,
33
44
  isoBlockContains,
34
45
  isoBlocksBehindLowerBound,
35
46
  parseFecBlockProfile,
@@ -39,6 +50,8 @@ import {
39
50
  serial32Precedes,
40
51
  ssbg1FitsSymbol,
41
52
  trimSsbg1SourceSymbol,
53
+ type AlFecFlow,
54
+ type AlFecRaptorQFlowConfig,
42
55
  type FecBlockProfile,
43
56
  } from '@blockcast/mmt-base'
44
57
  import { deriveFecRetentionBlocks, fecBlockBudgetMs } from '@blockcast/mmt-fec'
@@ -105,6 +118,25 @@ export interface MmtpFecSessionConfig {
105
118
  heldLayers?: readonly number[]
106
119
  }
107
120
 
121
+ /**
122
+ * A catalog-less session: one fec_flow entry of the AL-FEC message
123
+ * (`parseAlFecMessage(...).flows[i]`), draft-ramadan-moq-mmt-02 8.3.
124
+ */
125
+ export interface MmtpFecSessionMessageConfig {
126
+ /** The source track's entry; it must pass `alFecRaptorQFlowConfig`. */
127
+ alFecFlow: AlFecFlow
128
+ /**
129
+ * The decoder retention in blocks. The message carries no elapsed-time
130
+ * budget (mmt-02 7.5), so open-block state is bounded by local policy
131
+ * (fec-core-00 9.4); required, never defaulted.
132
+ */
133
+ retentionBlocks: number
134
+ Decoder: MmtpFecSessionDecoderConstructor
135
+ }
136
+
137
+ /** What updateAlFecFlow() did with a later version of the message. */
138
+ export type MmtpFecSessionMessageUpdate = 'raised' | 'unchanged' | 'refused'
139
+
108
140
  /**
109
141
  * The path a symbol arrived on: its MoQT subscription, or the multicast
110
142
  * group (native SSM or AMT) carrying the same asset. The caller states it;
@@ -197,12 +229,17 @@ export class MmtpFecSession {
197
229
  readonly algorithm: 'raptorq' | 'reed-solomon'
198
230
  readonly sourceSymbols: number
199
231
  /** P_0 = B_0, the held total every repair packet is checked against. */
200
- readonly repairSymbols: number
232
+ get repairSymbols(): number {
233
+ return this.#repairSymbols
234
+ }
201
235
  readonly symbolSize: number
202
236
  /** The decoder's retention, in blocks, derived from the catalog budget. */
203
237
  readonly retentionBlocks: number
204
238
 
205
239
  #decoder: MmtpFecSessionDecoder | null
240
+ #repairSymbols: number
241
+ /** The message entry a catalog-less session was built from; undefined under a catalog. */
242
+ #message: AlFecRaptorQFlowConfig | undefined
206
243
  /** Blocks a repair has defined and that are not settled yet, by SS_Start. */
207
244
  #blocks = new Map<number, BlockState>()
208
245
  /** SS_Starts of settled blocks, so a later repair for one is refused. */
@@ -240,7 +277,26 @@ export class MmtpFecSession {
240
277
  * the scheme, the block profile, K, P_0 (`repairSymbols`), T,
241
278
  * `interleaveDepthMs` or `reorderToleranceMs`. None is defaulted.
242
279
  */
243
- constructor(config: MmtpFecSessionConfig) {
280
+ constructor(config: MmtpFecSessionConfig | MmtpFecSessionMessageConfig) {
281
+ if (config && 'alFecFlow' in config) {
282
+ const message = alFecRaptorQFlowConfig(config.alFecFlow)
283
+ if (!message) {
284
+ throw new Error('MmtpFecSession: the AL-FEC entry is outside draft-ramadan-moq-mmt-02 8.3 (iso-ssbg1-v1)')
285
+ }
286
+ this.#message = message
287
+ // Coding byte 0x14 is the iso-ssbg1-v1 profile (mmt-02 8.3).
288
+ this.blockProfile = parseFecBlockProfile('iso-ssbg1-v1', 'alFecFlow')
289
+ this.algorithm = message.fecCodeId === FEC_CODE_RAPTORQ ? 'raptorq' : 'reed-solomon'
290
+ this.sourceSymbols = message.maximumK
291
+ this.#repairSymbols = message.maximumP
292
+ this.symbolSize = message.repairSymbolSize
293
+ this.retentionBlocks = requirePositiveInteger(config.retentionBlocks, 'retentionBlocks')
294
+ this.#repairPacketId = message.repairFlowId
295
+ this.#heldLayers = layerZero(message.maximumP)
296
+ this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols)
297
+ this.#decoder = buildDecoder(config.Decoder, this)
298
+ return
299
+ }
244
300
  const fec = config?.fec
245
301
  if (!fec || typeof fec !== 'object') {
246
302
  throw new Error('MmtpFecSession: the catalog fec instance is required')
@@ -251,7 +307,7 @@ export class MmtpFecSession {
251
307
  }
252
308
  this.algorithm = fec.scheme
253
309
  this.sourceSymbols = requirePositiveInteger(fec.sourceSymbols, 'fec.sourceSymbols')
254
- this.repairSymbols = requirePositiveInteger(fec.repairSymbols, 'fec.repairSymbols')
310
+ this.#repairSymbols = requirePositiveInteger(fec.repairSymbols, 'fec.repairSymbols')
255
311
  this.symbolSize = requirePositiveInteger(fec.symbolSize, 'fec.symbolSize')
256
312
  const interleaveDepthMs = requireNumber(fec.interleaveDepthMs, 'fec.interleaveDepthMs')
257
313
  const reorderToleranceMs = requireNumber(fec.reorderToleranceMs, 'fec.reorderToleranceMs')
@@ -271,17 +327,38 @@ export class MmtpFecSession {
271
327
  config.heldLayers,
272
328
  )
273
329
  this.#anchorHorizon = heldLayerAnchorHorizon(this.retentionBlocks, this.sourceSymbols)
274
- if (typeof config.Decoder !== 'function') {
275
- throw new Error('MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required')
276
- }
277
- const decoder = new config.Decoder(this.retentionBlocks, this.blockProfile, this.algorithm)
278
- try {
279
- decoder.configure_params(this.sourceSymbols, this.symbolSize)
280
- } catch (error) {
281
- decoder.free()
282
- throw error
330
+ this.#decoder = buildDecoder(config.Decoder, this)
331
+ }
332
+
333
+ /**
334
+ * A later version of the AL-FEC message, catalog-less sessions only. A
335
+ * maximum_p_for_repair_flow above the held total raises it (`raised`): the
336
+ * anchored check restarts at the new total, so a block generated under the
337
+ * previous one stays valid before the first block carrying the new total
338
+ * (fec-core-00 7.3.2, mmt-02 8.3). A field at or below it changes nothing
339
+ * (`unchanged`): no publisher lowers it, and the check catches a wire that
340
+ * does. An entry with another asset, repair flow, code point, K or T, or
341
+ * one outside 8.3, is `refused`: that is a new source encoding, which needs
342
+ * a new session. A latched fail-closed stays latched either way.
343
+ */
344
+ updateAlFecFlow(flow: AlFecFlow): MmtpFecSessionMessageUpdate {
345
+ const held = this.#message
346
+ if (!held) throw new Error('MmtpFecSession: updateAlFecFlow() needs a session built from an AL-FEC entry')
347
+ const next = alFecRaptorQFlowConfig(flow)
348
+ if (
349
+ !next ||
350
+ next.sourcePacketIds[0] !== held.sourcePacketIds[0] ||
351
+ next.repairFlowId !== held.repairFlowId ||
352
+ next.fecCodeId !== held.fecCodeId ||
353
+ next.maximumK !== held.maximumK ||
354
+ next.repairSymbolSize !== held.repairSymbolSize
355
+ ) {
356
+ return 'refused'
283
357
  }
284
- this.#decoder = decoder
358
+ if (next.maximumP <= this.#repairSymbols) return 'unchanged'
359
+ this.#repairSymbols = next.maximumP
360
+ this.#heldLayers = layerZero(next.maximumP)
361
+ return 'raised'
285
362
  }
286
363
 
287
364
  /** True once release() ran. */
@@ -386,7 +463,7 @@ export class MmtpFecSession {
386
463
  // An RSB_length below a held layer's total goes to the 7.3.2 stop, not
387
464
  // to the discard; the block state is unchanged either way.
388
465
  const verdict = this.#heldLayers.failsClosed(
389
- repairTrackName, frame.ssStart, frame.rsbLength, this.#anchorHorizon, this.#newestSource,
466
+ this.#trackFor(repairTrackName), frame.ssStart, frame.rsbLength, this.#anchorHorizon, this.#newestSource,
390
467
  )
391
468
  if (verdict) {
392
469
  this.#stats.failClosed = verdict
@@ -399,7 +476,7 @@ export class MmtpFecSession {
399
476
  // fec-01 6.3.9, after the 4.5 discards and the size check, before a block
400
477
  // is placed. Without a track name only the anchored rule (b) applies.
401
478
  const verdict = this.#heldLayers.admit(
402
- repairTrackName,
479
+ this.#trackFor(repairTrackName),
403
480
  frame.ssStart,
404
481
  frame.rsbLength,
405
482
  this.#anchorHorizon,
@@ -464,6 +541,11 @@ export class MmtpFecSession {
464
541
  return true
465
542
  }
466
543
 
544
+ /** Catalog-less: layer 0 has no own-track clause (mmt-02 8.3), so no track name is judged. */
545
+ #trackFor(repairTrackName: string | undefined): string | undefined {
546
+ return this.#message ? undefined : repairTrackName
547
+ }
548
+
467
549
  #drop(reason: string): Uint8Array[] {
468
550
  this.#stats.dropped[reason] = (this.#stats.dropped[reason] ?? 0) + 1
469
551
  return []
@@ -600,6 +682,24 @@ export class MmtpFecSession {
600
682
  }
601
683
  }
602
684
 
685
+ function layerZero(total: number): HeldLayerAdmission {
686
+ return new HeldLayerAdmission([{ layer: 0, repairTrackName: '', rsIdOffset: 0, repairSymbols: total }])
687
+ }
688
+
689
+ function buildDecoder(Decoder: MmtpFecSessionDecoderConstructor, session: MmtpFecSession): MmtpFecSessionDecoder {
690
+ if (typeof Decoder !== 'function') {
691
+ throw new Error('MmtpFecSession: a decoder constructor (wasm_bindgen.MmtFecDecoder) is required')
692
+ }
693
+ const decoder = new Decoder(session.retentionBlocks, session.blockProfile, session.algorithm)
694
+ try {
695
+ decoder.configure_params(session.sourceSymbols, session.symbolSize)
696
+ } catch (error) {
697
+ decoder.free()
698
+ throw error
699
+ }
700
+ return decoder
701
+ }
702
+
603
703
  function requirePositiveInteger(value: unknown, path: string): number {
604
704
  if (typeof value !== 'number' || !Number.isSafeInteger(value) || value <= 0) {
605
705
  throw new Error(`MmtpFecSession: ${path} must be a positive integer (got ${String(value)})`)
@@ -98,6 +98,8 @@ export interface MulticastRepairEndpoint {
98
98
  mode?: string;
99
99
  amtRelay?: string;
100
100
  amtRelayPort?: number;
101
+ /** The media join's `'driad'` discovery (no relay pinned), carried so the repair group rides the same relay. */
102
+ amtDiscovery?: 'driad';
101
103
  /** The repair packet IDs this group carries. */
102
104
  packetIds: number[];
103
105
  /** Each repair packet ID bound to the media packet ID it repairs. */
@@ -2427,6 +2429,7 @@ export class MulticastManager {
2427
2429
  mode: endpoint.mode as MulticastEndpointConfig["mode"],
2428
2430
  amtRelay: endpoint.amtRelay,
2429
2431
  amtRelayPort: endpoint.amtRelayPort ?? (endpoint.amtRelay?.trim() ? DEFAULT_AMT_RELAY_PORT : undefined),
2432
+ amtDiscovery: endpoint.amtDiscovery,
2430
2433
  packetIds: endpoint.packetIds,
2431
2434
  tracks: endpoint.tracks.map(({ name, packetId }) => ({ name, packetId })),
2432
2435
  // A protected repair group's records ride in band on its port (7.2.3).
@@ -0,0 +1,261 @@
1
+ /**
2
+ * MoQ repair-layer subscriptions by measured loss (BLO-35456).
3
+ *
4
+ * MoQ is per-track subscribe, so a repair layer the receiver does not
5
+ * subscribe costs nothing past the relay. This is the mechanism that decides
6
+ * which of a source's repair tracks to hold: it measures loss from the MMTP
7
+ * `packet_sequence_number` gaps the receiver already sees on the source track
8
+ * (no new signalling), holds base layers 0..n-1 (draft-ramadan-moq-fec 6.3,
9
+ * `resolveRepairLayers`), and holds the keyframe overlay track while any base
10
+ * layer is held. The policy here is deliberately the simplest per-layer
11
+ * add/drop; the join policy proper is BLO-35457.
12
+ *
13
+ * Every repair packet is handed to `feed` with the repair track it arrived on,
14
+ * so libmmt routes an overlay packet to the overlay instance and never to the
15
+ * base (`MmtpRouter.feedRepairPacket(..., repairTrackName)`).
16
+ *
17
+ * `stream` delivery means QUIC retransmits: no repair track is ever
18
+ * subscribed (FEC only for unreliable transports). The mode is the source's
19
+ * `deliveryMode` (`catalogTrackDeliveryMode`); absent is `datagram`. It is
20
+ * read from the current source, so on a catalog refresh re-feed the updated
21
+ * source through `switchSource` for a changed `deliveryMode` to take effect.
22
+ *
23
+ * ABR switch R -> R' (`switchSource`): R's subscriptions are closed, the layer
24
+ * count carries to R', and any packet R's subscriptions deliver after the
25
+ * switch is dropped, never fed.
26
+ */
27
+
28
+ import { serial32Distance } from '@blockcast/mmt-base'
29
+ import type { RepairLayerParams, RepairOverlayParams } from './repair-layers.js'
30
+
31
+ export type MoqRepairDelivery = 'datagram' | 'stream'
32
+
33
+ /** The source's FEC shape, as `fecParams` resolves it. */
34
+ export interface RepairLayerSource {
35
+ /** K: source symbols per base block. */
36
+ fecK: number
37
+ /** Base layers, layer 0 first (`TrackFecParams.repairLayers`). */
38
+ repairLayers?: readonly RepairLayerParams[]
39
+ /** Keyframe overlays (`TrackFecParams.repairOverlays`); at most one is used. */
40
+ repairOverlays?: readonly RepairOverlayParams[]
41
+ /** The publisher's MoQ delivery mode; absent is `datagram`. */
42
+ deliveryMode?: MoqRepairDelivery
43
+ }
44
+
45
+ export interface RepairTrackSubscription {
46
+ close(): void
47
+ }
48
+
49
+ export interface RepairLayerSubscriptionsOptions {
50
+ source: RepairLayerSource
51
+ /** Subscribe one repair track; every object payload goes to `onPacket`. */
52
+ subscribe(
53
+ repairTrackName: string,
54
+ priority: number,
55
+ onPacket: (packet: Uint8Array) => void,
56
+ ): RepairTrackSubscription
57
+ /** Hand one repair packet to the decoder, e.g. `processRepairFromMoQ`. */
58
+ feed(packet: Uint8Array, repairTrackName: string): void
59
+ /** Expected source packets per loss window. Default 500. */
60
+ windowPackets?: number
61
+ /** Repair held per unit of measured loss. Default 2. */
62
+ margin?: number
63
+ /** Consecutive windows wanting fewer layers before one is dropped. Default 3. */
64
+ dropAfterWindows?: number
65
+ }
66
+
67
+ export interface RepairLayerSubscriptionsSnapshot {
68
+ delivery: MoqRepairDelivery
69
+ layerCount: number
70
+ subscribedTracks: string[]
71
+ repairPackets: number
72
+ repairBytes: number
73
+ /** Packets a closed subscription delivered after its switch or drop. */
74
+ staleDropped: number
75
+ /** Loss rate of the last closed window; null before the first. */
76
+ lossRate: number | null
77
+ }
78
+
79
+ const SERIAL32_HALF = 0x80000000
80
+
81
+ export class RepairLayerSubscriptions {
82
+ readonly #opts: RepairLayerSubscriptionsOptions
83
+ readonly #windowPackets: number
84
+ readonly #margin: number
85
+ readonly #dropAfterWindows: number
86
+ #source: RepairLayerSource
87
+ #layerCount = 0
88
+ #subs = new Map<string, { sub: RepairTrackSubscription }>()
89
+ #disposed = false
90
+ #lastSeq: number | undefined
91
+ #expected = 0
92
+ #lost = 0
93
+ #wantFewer = 0
94
+ #lossRate: number | null = null
95
+ #repairPackets = 0
96
+ #repairBytes = 0
97
+ #staleDropped = 0
98
+
99
+ constructor(opts: RepairLayerSubscriptionsOptions) {
100
+ this.#opts = opts
101
+ this.#source = opts.source
102
+ this.#windowPackets = opts.windowPackets ?? 500
103
+ this.#margin = opts.margin ?? 2
104
+ this.#dropAfterWindows = opts.dropAfterWindows ?? 3
105
+ }
106
+
107
+ get layerCount(): number {
108
+ return this.#layerCount
109
+ }
110
+
111
+ /**
112
+ * One source packet's MMTP `packet_sequence_number`, in arrival order.
113
+ * The sequence is per `packet_id`: pass the packets of ONE packet_id only,
114
+ * or interleaved sequences read as loss.
115
+ */
116
+ noteSourceSequence(seq: number): void {
117
+ if (this.#disposed || this.#delivery() === 'stream') return
118
+ seq >>>= 0
119
+ if (this.#lastSeq === undefined) {
120
+ this.#lastSeq = seq
121
+ return
122
+ }
123
+ const d = serial32Distance(this.#lastSeq, seq)
124
+ if (d === 0) return
125
+ const back = d >= SERIAL32_HALF ? 2 ** 32 - d : 0
126
+ if (d > this.#windowPackets && (back === 0 || back > this.#windowPackets)) {
127
+ // A step wider than one window, either way, is a discontinuity (a
128
+ // publisher restart), not loss or reorder: restart the window from here.
129
+ // ponytail: a real outage longer than a window is also read as a restart;
130
+ // FEC cannot repair that anyway.
131
+ this.#lastSeq = seq
132
+ this.#expected = 0
133
+ this.#lost = 0
134
+ return
135
+ }
136
+ if (back === 0) {
137
+ this.#expected += d
138
+ this.#lost += d - 1
139
+ this.#lastSeq = seq
140
+ } else if (this.#lost > 0) {
141
+ // A late packet fills a hole counted as lost. Holes are not tracked
142
+ // individually, so one whose window already closed cancels a hole in
143
+ // this window instead: a bias toward lower loss of at most the reorder
144
+ // depth per window.
145
+ this.#lost -= 1
146
+ }
147
+ if (this.#expected >= this.#windowPackets) this.#closeWindow()
148
+ }
149
+
150
+ /** ABR switch R -> R': close R's tracks, carry the layer count to R'. */
151
+ switchSource(next: RepairLayerSource): void {
152
+ if (this.#disposed) return
153
+ this.#closeAll()
154
+ this.#source = next
155
+ this.#lastSeq = undefined
156
+ this.#expected = 0
157
+ this.#lost = 0
158
+ this.#wantFewer = 0
159
+ this.#layerCount = this.#delivery() === 'stream' ? 0 : Math.min(this.#layerCount, this.#layers().length)
160
+ this.#reconcile()
161
+ }
162
+
163
+ snapshot(): RepairLayerSubscriptionsSnapshot {
164
+ return {
165
+ delivery: this.#delivery(),
166
+ layerCount: this.#layerCount,
167
+ subscribedTracks: [...this.#subs.keys()],
168
+ repairPackets: this.#repairPackets,
169
+ repairBytes: this.#repairBytes,
170
+ staleDropped: this.#staleDropped,
171
+ lossRate: this.#lossRate,
172
+ }
173
+ }
174
+
175
+ dispose(): void {
176
+ if (this.#disposed) return
177
+ this.#closeAll()
178
+ this.#disposed = true
179
+ }
180
+
181
+ #delivery(): MoqRepairDelivery {
182
+ return this.#source.deliveryMode === 'stream' ? 'stream' : 'datagram'
183
+ }
184
+
185
+ #layers(): readonly RepairLayerParams[] {
186
+ return this.#source.repairLayers ?? []
187
+ }
188
+
189
+ #closeWindow(): void {
190
+ const rate = this.#lost / this.#expected
191
+ this.#lossRate = rate
192
+ this.#expected = 0
193
+ this.#lost = 0
194
+ const target = this.#targetLayers(rate)
195
+ if (target > this.#layerCount) {
196
+ this.#wantFewer = 0
197
+ this.#layerCount = target
198
+ } else if (target < this.#layerCount) {
199
+ this.#wantFewer += 1
200
+ if (this.#wantFewer >= this.#dropAfterWindows) {
201
+ this.#wantFewer = 0
202
+ this.#layerCount -= 1
203
+ }
204
+ } else {
205
+ this.#wantFewer = 0
206
+ }
207
+ this.#reconcile()
208
+ }
209
+
210
+ /** Fewest base layers whose summed P covers margin x the measured loss of K. */
211
+ #targetLayers(rate: number): number {
212
+ if (rate <= 0) return 0
213
+ const needed = Math.ceil(rate * this.#source.fecK * this.#margin)
214
+ const layers = this.#layers()
215
+ let held = 0
216
+ for (let n = 0; n < layers.length; n++) {
217
+ held += layers[n]!.repairSymbols
218
+ if (held >= needed) return n + 1
219
+ }
220
+ return layers.length
221
+ }
222
+
223
+ /** Stream delivery never leaves layer count 0, so it never subscribes. */
224
+ #reconcile(): void {
225
+ const want = new Map<string, number>()
226
+ for (const layer of this.#layers().slice(0, this.#layerCount)) {
227
+ want.set(layer.repairTrackName, layer.priority)
228
+ }
229
+ const overlay = this.#source.repairOverlays?.[0]
230
+ if (this.#layerCount > 0 && overlay) want.set(overlay.repairTrackName, overlay.priority)
231
+
232
+ for (const [name, entry] of this.#subs) {
233
+ if (!want.has(name)) {
234
+ entry.sub.close()
235
+ this.#subs.delete(name)
236
+ }
237
+ }
238
+ for (const [name, priority] of want) {
239
+ if (this.#subs.has(name)) continue
240
+ const entry = {} as { sub: RepairTrackSubscription }
241
+ entry.sub = this.#opts.subscribe(name, priority, (packet) => this.#onPacket(name, entry, packet))
242
+ this.#subs.set(name, entry)
243
+ }
244
+ }
245
+
246
+ /** Fenced on the entry itself, so a closed subscription is stale even if its track is re-added. */
247
+ #onPacket(name: string, entry: { sub: RepairTrackSubscription }, packet: Uint8Array): void {
248
+ if (this.#disposed || this.#subs.get(name) !== entry) {
249
+ this.#staleDropped += 1
250
+ return
251
+ }
252
+ this.#repairPackets += 1
253
+ this.#repairBytes += packet.byteLength
254
+ this.#opts.feed(packet, name)
255
+ }
256
+
257
+ #closeAll(): void {
258
+ for (const entry of this.#subs.values()) entry.sub.close()
259
+ this.#subs.clear()
260
+ }
261
+ }
@@ -58,7 +58,7 @@ export interface TrackSessionConfig {
58
58
  * This is runtime join state, not catalog geometry: a receiver on a clean
59
59
  * path joins layer 0 only while a lossy one adds layers, so the catalog's
60
60
  * total P is not what this receiver is receiving. Diagnostics that report P
61
- * (the worker snapshot, CMCD `x-bc-fec-p`) must read this.
61
+ * (the worker snapshot, CMCD `com.blockcast-fp`) must read this.
62
62
  *
63
63
  * Absent when the caller joins no layers explicitly, in which case P_0 is
64
64
  * what was joined. That is an identity on a single-layer track, not a