@blockcast/mmt-container 2.1.0 → 2.2.0-main.0f6aad7bb803

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 (62) hide show
  1. package/dist/browser-runtime.js +458 -77
  2. package/dist/browser-runtime.js.map +4 -4
  3. package/dist/carp-catalog.js.map +1 -1
  4. package/dist/catalog-fec-params.js.map +1 -1
  5. package/dist/catalog-network-source.js.map +1 -1
  6. package/dist/cmcd-producer.d.ts +5 -0
  7. package/dist/cmcd-producer.d.ts.map +1 -1
  8. package/dist/cmcd-producer.js.map +2 -2
  9. package/dist/delivery-catalog.js.map +1 -1
  10. package/dist/delta-fallback-config.js.map +1 -1
  11. package/dist/fec-manager.js.map +2 -2
  12. package/dist/fec-state.js.map +1 -1
  13. package/dist/fec-worker-setup.js.map +1 -1
  14. package/dist/held-layer-admission.js.map +1 -1
  15. package/dist/index.d.ts +1 -1
  16. package/dist/index.d.ts.map +1 -1
  17. package/dist/index.js.map +2 -2
  18. package/dist/iso-block-locator.js.map +1 -1
  19. package/dist/mfu-reassembler.js +12 -19
  20. package/dist/mfu-reassembler.js.map +2 -2
  21. package/dist/mmtp-container-parser.js +12 -19
  22. package/dist/mmtp-container-parser.js.map +2 -2
  23. package/dist/mmtp-container-parser.no-modules.js +133 -34
  24. package/dist/mmtp-container-parser.no-modules.js.map +3 -3
  25. package/dist/mmtp-decode-pipeline.js +12 -19
  26. package/dist/mmtp-decode-pipeline.js.map +2 -2
  27. package/dist/mmtp-fec-session.d.ts +41 -3
  28. package/dist/mmtp-fec-session.d.ts.map +1 -1
  29. package/dist/mmtp-fec-session.js +118 -13
  30. package/dist/mmtp-fec-session.js.map +3 -3
  31. package/dist/mmtp-router.d.ts +9 -1
  32. package/dist/mmtp-router.d.ts.map +1 -1
  33. package/dist/mmtp-router.js +1468 -33
  34. package/dist/mmtp-router.js.map +4 -4
  35. package/dist/multicast-auth-catalog.js.map +1 -1
  36. package/dist/multicast-input.js.map +1 -1
  37. package/dist/multicast-manager.d.ts +15 -2
  38. package/dist/multicast-manager.d.ts.map +1 -1
  39. package/dist/multicast-manager.js +15246 -14969
  40. package/dist/multicast-manager.js.map +4 -4
  41. package/dist/multicast-transport.d.ts +11 -3
  42. package/dist/multicast-transport.d.ts.map +1 -1
  43. package/dist/multicast-transport.js +255 -19
  44. package/dist/multicast-transport.js.map +4 -4
  45. package/dist/multicast-unwrap.js +12 -19
  46. package/dist/multicast-unwrap.js.map +2 -2
  47. package/dist/no-modules.js +130 -33
  48. package/dist/no-modules.js.map +3 -3
  49. package/dist/repair-fetch.js.map +1 -1
  50. package/dist/signaling.js.map +2 -2
  51. package/dist/timestamp-codec.js +12 -19
  52. package/dist/timestamp-codec.js.map +2 -2
  53. package/dist/wasm-mfu-reassembler.js.map +1 -1
  54. package/dist/wasm-mmtp-container-parser.js +12 -19
  55. package/dist/wasm-mmtp-container-parser.js.map +2 -2
  56. package/package.json +5 -5
  57. package/src/cmcd-producer.ts +5 -0
  58. package/src/index.ts +2 -0
  59. package/src/mmtp-fec-session.ts +115 -15
  60. package/src/mmtp-router.ts +81 -16
  61. package/src/multicast-manager.ts +26 -5
  62. package/src/multicast-transport.ts +44 -20
@@ -149,30 +149,26 @@ function isEmptyOrExactLegacyTrailer(payload, start, end) {
149
149
  const authLength = view2.getUint16(2, false);
150
150
  return start + LEGACY_TRAILER_HEADER_SIZE + authLength === end;
151
151
  }
152
- function resolveDeclaredTrailers(payload, declaredEnd, fecType, options, rapFlag = false) {
152
+ function resolveDeclaredTrailers(payload, declaredEnd, fecType, options) {
153
153
  if (declaredEnd > payload.length)
154
154
  return null;
155
155
  if (options?.skipFecId) {
156
- return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false, hasOverlayFecId: false } : null;
156
+ return isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length) ? { hasFecId: false } : null;
157
157
  }
158
- const overlay = options?.overlayDeclared === true && rapFlag;
159
158
  if (fecType === 1) {
160
- const fecStart = payload.length - sourceFecTrailerSize(overlay);
159
+ const fecStart = payload.length - SOURCE_FEC_PAYLOAD_ID_SIZE;
161
160
  if (fecStart < declaredEnd || !isEmptyOrExactLegacyTrailer(payload, declaredEnd, fecStart)) {
162
161
  return null;
163
162
  }
164
- return { hasFecId: true, hasOverlayFecId: overlay };
163
+ return { hasFecId: true };
165
164
  }
166
- if (fecType !== 0 || overlay)
165
+ if (fecType !== 0)
167
166
  return null;
168
167
  if (isEmptyOrExactLegacyTrailer(payload, declaredEnd, payload.length)) {
169
- return { hasFecId: false, hasOverlayFecId: false };
168
+ return { hasFecId: false };
170
169
  }
171
170
  return null;
172
171
  }
173
- function sourceFecTrailerSize(overlay) {
174
- return overlay ? 2 * SOURCE_FEC_PAYLOAD_ID_SIZE : SOURCE_FEC_PAYLOAD_ID_SIZE;
175
- }
176
172
  function planMfuExtraction(mmtpPacket, options, parsedHeader) {
177
173
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE) {
178
174
  return {
@@ -225,11 +221,11 @@ function planMfuExtraction(mmtpPacket, options, parsedHeader) {
225
221
  if ("rejection" in layoutResult)
226
222
  return layoutResult;
227
223
  const { layout } = layoutResult;
228
- const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options, header.rapFlag);
224
+ const trailerLayout = resolveDeclaredTrailers(payload, layout.dataEnd, header.fecType, options);
229
225
  if (!trailerLayout) {
230
226
  if (!options?.skipFecId && header.fecType === 1) {
231
227
  const observed = payload.length - layout.dataEnd;
232
- const expected = sourceFecTrailerSize(options?.overlayDeclared === true && header.rapFlag);
228
+ const expected = SOURCE_FEC_PAYLOAD_ID_SIZE;
233
229
  if (observed !== expected) {
234
230
  return {
235
231
  rejection: {
@@ -261,13 +257,10 @@ function extractPlannedMfu(mmtpPacket, result) {
261
257
  const mfuDuHeader = mfuDuHeaderPresent && mpu.timedFlag === 1 ? parseTimedMfuDuHeader(payload, MPU_HEADER_SIZE) : null;
262
258
  const itemId = mfuDuHeaderPresent && mpu.timedFlag === 0 ? new DataView(payload.buffer, payload.byteOffset + MPU_HEADER_SIZE, 4).getUint32(0, false) : null;
263
259
  const data = payload.subarray(mfuOffset, dataEnd);
264
- const trailerStart = mmtpPacket.length - sourceFecTrailerSize(trailerLayout.hasOverlayFecId);
265
- const ssIdAt = (offset) => ({
266
- ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + offset, 4).getUint32(0, false)
267
- });
268
- const fecPayloadId = trailerLayout.hasFecId ? ssIdAt(trailerStart) : null;
269
- const overlayFecPayloadId = trailerLayout.hasOverlayFecId ? ssIdAt(trailerStart + SOURCE_FEC_PAYLOAD_ID_SIZE) : null;
270
- return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId, overlayFecPayloadId };
260
+ const fecPayloadId = trailerLayout.hasFecId ? {
261
+ ssId: new DataView(mmtpPacket.buffer, mmtpPacket.byteOffset + mmtpPacket.length - SOURCE_FEC_PAYLOAD_ID_SIZE, 4).getUint32(0, false)
262
+ } : null;
263
+ return { header, mpu, fragmentType, data, mfuDuHeader, itemId, fecPayloadId };
271
264
  }
272
265
  function sourceFecPayloadIdOf(mmtpPacket, header) {
273
266
  if (mmtpPacket.length < MMTP_HEADER_SIZE + MPU_HEADER_SIZE)
@@ -377,6 +370,1412 @@ var RUNTIME_FEC_RECEIVER = Object.freeze({
377
370
  overlays: true
378
371
  });
379
372
 
373
+ // node_modules/@blockcast/mmt-transport/dist/multicast-tier.js
374
+ function endpointKey(endpoint) {
375
+ return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
376
+ }
377
+ function carriesMedia(endpoint) {
378
+ return endpoint.carriesMedia !== false;
379
+ }
380
+ function selectMulticastTier(endpoints, estimate) {
381
+ const media = endpoints.filter(carriesMedia);
382
+ if (media.length <= 1)
383
+ return media[0];
384
+ const ranked = media.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > 0).sort((a, b) => a.bandwidth - b.bandwidth);
385
+ if (ranked.length < 2)
386
+ return media[0];
387
+ if (estimate === void 0)
388
+ return ranked[0];
389
+ const budget = estimate * 0.8;
390
+ let selected;
391
+ for (const endpoint of ranked) {
392
+ if (endpoint.bandwidth <= budget)
393
+ selected = endpoint;
394
+ }
395
+ return selected ?? ranked[0];
396
+ }
397
+
398
+ // node_modules/@blockcast/mmt-transport/dist/abr-controller.js
399
+ var QUALITY_LEVELS = Object.freeze([
400
+ { name: "240p", bitrate: 3e5, width: 426, height: 240, fps: 15 },
401
+ { name: "360p", bitrate: 5e5, width: 640, height: 360, fps: 24 },
402
+ { name: "480p", bitrate: 1e6, width: 854, height: 480, fps: 30 },
403
+ { name: "720p", bitrate: 25e5, width: 1280, height: 720, fps: 30 },
404
+ { name: "1080p", bitrate: 5e6, width: 1920, height: 1080, fps: 30 },
405
+ { name: "1440p", bitrate: 8e6, width: 2560, height: 1440, fps: 30 },
406
+ { name: "4K", bitrate: 15e6, width: 3840, height: 2160, fps: 30 }
407
+ ].map((level) => Object.freeze(level)));
408
+ function positiveFinite(value) {
409
+ return typeof value === "number" && Number.isFinite(value) && value > 0;
410
+ }
411
+ function validateQualityLadder(ladder) {
412
+ if (!Array.isArray(ladder) || ladder.length === 0) {
413
+ throw new TypeError("[ABR] ladder must list at least one rendition (e.g. the catalog's video tracks)");
414
+ }
415
+ const names = /* @__PURE__ */ new Set();
416
+ for (const level of ladder) {
417
+ if (typeof level?.name !== "string" || level.name.length === 0) {
418
+ throw new TypeError("[ABR] every ladder rendition needs a name");
419
+ }
420
+ if (!positiveFinite(level.bitrate)) {
421
+ throw new RangeError(`[ABR] rendition ${level.name}: bitrate must be a positive finite number, got ${String(level.bitrate)}`);
422
+ }
423
+ for (const field of ["width", "height", "fps"]) {
424
+ if (level[field] !== void 0 && !positiveFinite(level[field])) {
425
+ throw new RangeError(`[ABR] rendition ${level.name}: ${field} must be a positive finite number when stated, got ${String(level[field])}`);
426
+ }
427
+ }
428
+ if (names.has(level.name))
429
+ throw new RangeError(`[ABR] rendition ${level.name} appears twice in the ladder`);
430
+ names.add(level.name);
431
+ }
432
+ return Object.freeze([...ladder].sort((a, b) => a.bitrate - b.bitrate).map((level) => Object.freeze({ ...level })));
433
+ }
434
+ var AdaptiveBitrateController = class {
435
+ /** The caller's renditions, ascending by bitrate (`validateQualityLadder`). */
436
+ ladder;
437
+ currentQualityIndex;
438
+ history = [];
439
+ historyWindow = 1e4;
440
+ // 10 second window
441
+ upgradeThreshold = 0.8;
442
+ // 80% of target bitrate sustained
443
+ downgradeThreshold = 0.5;
444
+ // 50% of target bitrate triggers downgrade
445
+ stabilityPeriod = 5e3;
446
+ // Wait 5s before upgrading
447
+ lastQualityChange = 0;
448
+ onQualityChange;
449
+ // FEC stats for effective loss rate calculation
450
+ fecStats = {
451
+ rawLossRate: 0,
452
+ effectiveLossRate: 0,
453
+ recoveryRate: 1,
454
+ fecEnabled: false
455
+ };
456
+ constructor(options) {
457
+ if (!options || typeof options !== "object") {
458
+ throw new TypeError("[ABR] AdaptiveBitrateController needs { ladder, initialQuality }");
459
+ }
460
+ this.ladder = validateQualityLadder(options.ladder);
461
+ this.currentQualityIndex = options.initialQuality === void 0 ? 0 : this.ladder.findIndex((q) => q.name === options.initialQuality);
462
+ if (this.currentQualityIndex < 0) {
463
+ throw new RangeError(`[ABR] initial rendition ${String(options.initialQuality)} is not in the ladder`);
464
+ }
465
+ }
466
+ setCallback(callback) {
467
+ this.onQualityChange = callback;
468
+ }
469
+ getCurrentQuality() {
470
+ return this.ladder[this.currentQualityIndex];
471
+ }
472
+ /** Selects the multicast (S,G) tier without replacing a player's unicast ABR manager. */
473
+ selectMulticastTier(endpoints, estimate = this.getMetrics().measuredBitrate || void 0) {
474
+ return selectMulticastTier(endpoints, estimate);
475
+ }
476
+ /**
477
+ * Record network sample for bitrate adaptation
478
+ *
479
+ * @param bytesReceived - Bytes received in this sample
480
+ * @param packetsLost - Packets lost (raw, before FEC recovery)
481
+ */
482
+ recordSample(bytesReceived, packetsLost) {
483
+ const now = Date.now();
484
+ this.history.push({ timestamp: now, bytesReceived, packetsLost });
485
+ this.history = this.history.filter((s) => now - s.timestamp < this.historyWindow);
486
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
487
+ const currentQuality = this.getCurrentQuality();
488
+ const effectiveLossRate = this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate;
489
+ if (now - this.lastQualityChange < this.stabilityPeriod) {
490
+ return;
491
+ }
492
+ if (effectiveLossRate > 0.05 || measuredBitrate < currentQuality.bitrate * this.downgradeThreshold) {
493
+ this.downgrade();
494
+ return;
495
+ }
496
+ if (measuredBitrate > currentQuality.bitrate * this.upgradeThreshold && effectiveLossRate < 0.01 && this.currentQualityIndex < this.ladder.length - 1) {
497
+ this.upgrade();
498
+ }
499
+ }
500
+ /**
501
+ * Update FEC statistics for ABR decisions
502
+ *
503
+ * ABR uses the effective loss rate (after FEC recovery) rather than the
504
+ * raw transport loss rate.
505
+ *
506
+ * @param stats - FEC statistics from the FEC decoder
507
+ */
508
+ setFecStats(stats) {
509
+ this.fecStats = stats;
510
+ }
511
+ /**
512
+ * Get current FEC statistics
513
+ */
514
+ getFecStats() {
515
+ return { ...this.fecStats };
516
+ }
517
+ calculateMetrics() {
518
+ if (this.history.length < 2) {
519
+ return { measuredBitrate: 0, lossRate: 0 };
520
+ }
521
+ const totalBytes = this.history.reduce((sum, s) => sum + s.bytesReceived, 0);
522
+ const totalLost = this.history.reduce((sum, s) => sum + s.packetsLost, 0);
523
+ const duration = (this.history[this.history.length - 1].timestamp - this.history[0].timestamp) / 1e3;
524
+ const measuredBitrate = duration > 0 ? totalBytes * 8 / duration : 0;
525
+ const lossRate = totalLost / (this.history.length + totalLost);
526
+ return { measuredBitrate, lossRate };
527
+ }
528
+ upgrade() {
529
+ if (this.currentQualityIndex >= this.ladder.length - 1)
530
+ return;
531
+ this.currentQualityIndex++;
532
+ this.lastQualityChange = Date.now();
533
+ const newQuality = this.getCurrentQuality();
534
+ console.log(`[ABR] Upgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
535
+ this.onQualityChange?.(newQuality);
536
+ }
537
+ downgrade() {
538
+ if (this.currentQualityIndex <= 0)
539
+ return;
540
+ this.currentQualityIndex--;
541
+ this.lastQualityChange = Date.now();
542
+ const newQuality = this.getCurrentQuality();
543
+ console.log(`[ABR] Downgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
544
+ this.onQualityChange?.(newQuality);
545
+ }
546
+ /**
547
+ * Select a ladder rendition: the caller switched to it (a manual override,
548
+ * or a switch the caller made). Throws for a name the ladder does not carry.
549
+ */
550
+ setQuality(name) {
551
+ const index = this.ladder.findIndex((q) => q.name === name);
552
+ if (index < 0)
553
+ throw new RangeError(`[ABR] rendition ${name} is not in the ladder`);
554
+ this.currentQualityIndex = index;
555
+ this.lastQualityChange = Date.now();
556
+ this.onQualityChange?.(this.getCurrentQuality());
557
+ }
558
+ /**
559
+ * Get current metrics including both raw and effective loss rates
560
+ */
561
+ getMetrics() {
562
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
563
+ return {
564
+ measuredBitrate,
565
+ rawLossRate,
566
+ effectiveLossRate: this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate,
567
+ fecEnabled: this.fecStats.fecEnabled,
568
+ sampleCount: this.history.length
569
+ };
570
+ }
571
+ /**
572
+ * Reset history and start fresh
573
+ */
574
+ reset() {
575
+ this.history = [];
576
+ this.lastQualityChange = 0;
577
+ }
578
+ };
579
+
580
+ // node_modules/@blockcast/mmt-base/dist/mmtp.js
581
+ var MPU_HEADER_SIZE2 = 8;
582
+ var MPU_LENGTH_FIELD_SIZE2 = 2;
583
+ var MPU_HEADER_REMAINDER_SIZE2 = MPU_HEADER_SIZE2 - MPU_LENGTH_FIELD_SIZE2;
584
+ var MMTP_SIGNALING_PACKET_ID2 = 0;
585
+ var MMTP_PACKET_ID_MAX = 65535;
586
+
587
+ // node_modules/@blockcast/mmt-base/dist/net-constants.js
588
+ var DEFAULT_AMT_RELAY_PORT = 2268;
589
+
590
+ // node_modules/@blockcast/mmt-base/dist/ntp-short.js
591
+ var NTP_SHORT_BITS2 = 32;
592
+ var NTP_SHORT_MODULUS2 = 2 ** NTP_SHORT_BITS2;
593
+ var NTP_SHORT_HALF_RANGE2 = 2 ** (NTP_SHORT_BITS2 - 1);
594
+ function isNtpShort(value) {
595
+ return Number.isInteger(value) && value >= 0 && value < NTP_SHORT_MODULUS2;
596
+ }
597
+ function compareNtpShort(a, b) {
598
+ if (!isNtpShort(a) || !isNtpShort(b)) {
599
+ throw new RangeError(`NTP-short values must be integers in [0, 2^${NTP_SHORT_BITS2}), got ${String(a)} and ${String(b)}`);
600
+ }
601
+ if (a === b)
602
+ return "equal";
603
+ const forward = (a - b + NTP_SHORT_MODULUS2) % NTP_SHORT_MODULUS2;
604
+ if (forward < NTP_SHORT_HALF_RANGE2)
605
+ return "after";
606
+ if (forward > NTP_SHORT_HALF_RANGE2)
607
+ return "before";
608
+ return "unordered";
609
+ }
610
+
611
+ // node_modules/@blockcast/mmt-base/dist/fec-block-profile.js
612
+ var FEC_BLOCK_PROFILES2 = Object.freeze([
613
+ "iso-ssbg1-v1"
614
+ ]);
615
+
616
+ // node_modules/@blockcast/mmt-base/dist/fec-bindings.js
617
+ var RUNTIME_FEC_RECEIVER2 = Object.freeze({
618
+ schemes: Object.freeze(["raptorq", "reed-solomon"]),
619
+ blockProfiles: Object.freeze(["iso-ssbg1-v1"]),
620
+ overlays: true
621
+ });
622
+
623
+ // node_modules/@blockcast/mmt-transport/dist/multicast-orchestrator.js
624
+ var DEFAULT_DWELL_MS = 3e3;
625
+ var DEFAULT_JOIN_DEADLINE_MS = 5e3;
626
+ var MulticastOrchestrator = class {
627
+ options;
628
+ #state = "stable";
629
+ #current;
630
+ #target;
631
+ #estimate;
632
+ #favored;
633
+ #joinStartedAt = 0;
634
+ /**
635
+ * Latest active-tier send time (NTP short), or undefined before the first.
636
+ * "Latest" is serial order, not the numerically largest value: after the
637
+ * field wraps, the largest value is the stale one.
638
+ */
639
+ #highWater;
640
+ #dwellMs;
641
+ #joinDeadlineMs;
642
+ constructor(options) {
643
+ this.options = options;
644
+ this.#dwellMs = options.dwellMs ?? DEFAULT_DWELL_MS;
645
+ this.#joinDeadlineMs = options.joinDeadlineMs ?? DEFAULT_JOIN_DEADLINE_MS;
646
+ if (!Number.isFinite(this.#dwellMs) || !Number.isFinite(this.#joinDeadlineMs) || this.#dwellMs <= 0 || this.#joinDeadlineMs <= 0) {
647
+ throw new Error("Multicast dwell and join deadline must be positive");
648
+ }
649
+ }
650
+ get state() {
651
+ return this.#state;
652
+ }
653
+ get current() {
654
+ return this.#current;
655
+ }
656
+ get target() {
657
+ return this.#target;
658
+ }
659
+ get estimate() {
660
+ return this.#estimate;
661
+ }
662
+ start() {
663
+ this.#current ??= this.options.initialEndpoint ?? selectMulticastTier(this.options.endpoints, void 0);
664
+ return this.#current;
665
+ }
666
+ onGoodput(sample) {
667
+ const bitrate = sample.bitrate;
668
+ if (!this.#current)
669
+ return void 0;
670
+ if (this.#state === "joining")
671
+ return this.poll();
672
+ if (this.options.adaptive === false)
673
+ return void 0;
674
+ if (bitrate === void 0 || !Number.isFinite(bitrate))
675
+ return void 0;
676
+ this.#estimate = bitrate;
677
+ const desired = selectMulticastTier(this.options.endpoints, bitrate);
678
+ if (!desired)
679
+ return void 0;
680
+ const desiredKey = endpointKey(desired);
681
+ if (desiredKey === endpointKey(this.#current)) {
682
+ if (this.#favored?.source === "goodput")
683
+ this.#favored = void 0;
684
+ return void 0;
685
+ }
686
+ if (typeof desired.bandwidth !== "number" || typeof this.#current.bandwidth !== "number" || desired.bandwidth >= this.#current.bandwidth) {
687
+ if (this.#favored?.source === "goodput")
688
+ this.#favored = void 0;
689
+ return void 0;
690
+ }
691
+ const now = this.#now();
692
+ if (!this.#favored || this.#favored.key !== desiredKey || this.#favored.source !== "goodput") {
693
+ this.#favored = { key: desiredKey, since: now, source: "goodput" };
694
+ return void 0;
695
+ }
696
+ if (now - this.#favored.since < this.#dwellMs)
697
+ return void 0;
698
+ this.#state = "joining";
699
+ this.#target = desired;
700
+ this.#joinStartedAt = now;
701
+ this.#favored = void 0;
702
+ return { kind: "join-target", current: this.#current, target: desired };
703
+ }
704
+ onHeadroom(sample) {
705
+ if (!this.#current || this.options.adaptive === false || this.#state === "joining")
706
+ return void 0;
707
+ if (!sample.healthy) {
708
+ if (this.#favored?.source === "headroom")
709
+ this.#favored = void 0;
710
+ return void 0;
711
+ }
712
+ if (this.#favored?.source === "goodput")
713
+ return void 0;
714
+ const currentBandwidth = this.#current.bandwidth;
715
+ if (typeof currentBandwidth !== "number")
716
+ return void 0;
717
+ const desired = this.options.endpoints.filter((endpoint) => carriesMedia(endpoint) && typeof endpoint.bandwidth === "number" && endpoint.bandwidth > currentBandwidth).sort((a, b) => a.bandwidth - b.bandwidth)[0];
718
+ if (!desired) {
719
+ this.#favored = void 0;
720
+ return void 0;
721
+ }
722
+ const desiredKey = endpointKey(desired);
723
+ if (desiredKey === endpointKey(this.#current)) {
724
+ this.#favored = void 0;
725
+ return void 0;
726
+ }
727
+ const now = this.#now();
728
+ if (!this.#favored || this.#favored.key !== desiredKey) {
729
+ this.#favored = { key: desiredKey, since: now, source: "headroom" };
730
+ return void 0;
731
+ }
732
+ if (now - this.#favored.since < this.#dwellMs)
733
+ return void 0;
734
+ this.#state = "joining";
735
+ this.#target = desired;
736
+ this.#joinStartedAt = now;
737
+ this.#favored = void 0;
738
+ return { kind: "join-target", current: this.#current, target: desired };
739
+ }
740
+ /**
741
+ * Join `target` because the viewer selected it, not because goodput or
742
+ * headroom ranked it. It runs whether or not the orchestrator adapts, and
743
+ * takes the path an adaptive join takes: commit on the target's RAP at or
744
+ * beyond the high-water mark, abandon at the join deadline. While it is
745
+ * pending nothing re-ranks the ladder; goodput only advances the deadline.
746
+ *
747
+ * Returns undefined, changing nothing, while another join is pending (cancel
748
+ * it first), when `target` is the current tier, or when it carries no media.
749
+ */
750
+ select(target) {
751
+ if (!this.#current || this.#state === "joining" || !carriesMedia(target))
752
+ return void 0;
753
+ if (endpointKey(target) === endpointKey(this.#current))
754
+ return void 0;
755
+ this.#state = "joining";
756
+ this.#target = target;
757
+ this.#joinStartedAt = this.#now();
758
+ this.#favored = void 0;
759
+ return { kind: "join-target", current: this.#current, target };
760
+ }
761
+ /**
762
+ * Feed a packet from the active tier (to advance the high-water mark) or
763
+ * from the in-flight target (to find a committable RAP).
764
+ *
765
+ * Serial order is only the true order while the compared instants are less
766
+ * than `NTP_SHORT_HALF_RANGE` (2^15 s, ~9.1 h) apart. Feeding every
767
+ * active-tier packet keeps the mark that close to the live stream. A mark
768
+ * refreshed only by commits can fall further behind than that, and a
769
+ * target RAP may then compare as older, so the join is abandoned.
770
+ */
771
+ onTierPacket(packet) {
772
+ if (!this.#current)
773
+ return void 0;
774
+ const sentAt = tierPacketSendTime(packet);
775
+ if (packet.endpointKey === endpointKey(this.#current) && sentAt !== void 0 && (this.#highWater === void 0 || compareNtpShort(sentAt, this.#highWater) === "after")) {
776
+ this.#highWater = sentAt;
777
+ }
778
+ if (this.#state !== "joining" || !this.#target)
779
+ return void 0;
780
+ const expired = this.poll();
781
+ if (expired)
782
+ return expired;
783
+ if (packet.endpointKey !== endpointKey(this.#target) || !packet.keyframe || !packet.hasValidCodecConfig || sentAt === void 0 || !this.#reachesHighWater(sentAt))
784
+ return void 0;
785
+ const command = {
786
+ kind: "commit-swap",
787
+ target: this.#target,
788
+ old: this.#current
789
+ };
790
+ this.#highWater = sentAt;
791
+ this.#current = this.#target;
792
+ this.#target = void 0;
793
+ this.#state = "stable";
794
+ return command;
795
+ }
796
+ poll() {
797
+ if (this.#state !== "joining" || !this.#target || !this.#current)
798
+ return void 0;
799
+ if (this.#now() - this.#joinStartedAt < this.#joinDeadlineMs)
800
+ return void 0;
801
+ return this.cancel();
802
+ }
803
+ cancel() {
804
+ if (this.#state !== "joining" || !this.#target || !this.#current)
805
+ return void 0;
806
+ const command = {
807
+ kind: "abandon-join",
808
+ current: this.#current,
809
+ target: this.#target
810
+ };
811
+ this.#target = void 0;
812
+ this.#state = "stable";
813
+ return command;
814
+ }
815
+ /**
816
+ * Whether a target RAP sent at `sentAt` is at or beyond the active tier's
817
+ * high-water mark. A pair exactly half the NTP-short space apart has no
818
+ * serial order, so it cannot show that and does not commit.
819
+ */
820
+ #reachesHighWater(sentAt) {
821
+ if (this.#highWater === void 0)
822
+ return true;
823
+ const order = compareNtpShort(sentAt, this.#highWater);
824
+ return order === "after" || order === "equal";
825
+ }
826
+ #now() {
827
+ const now = this.options.now();
828
+ if (!Number.isFinite(now))
829
+ throw new Error("Multicast orchestrator clock must be finite");
830
+ return now;
831
+ }
832
+ };
833
+ function tierPacketSendTime(packet) {
834
+ if (!Number.isFinite(packet.timestamp))
835
+ return void 0;
836
+ if (!isNtpShort(packet.timestamp)) {
837
+ throw new RangeError(`Multicast tier packet timestamp must be an MMTP NTP-short send time, got ${packet.timestamp}`);
838
+ }
839
+ return packet.timestamp;
840
+ }
841
+
842
+ // node_modules/@blockcast/mmt-transport/dist/endpoint-config.js
843
+ function toWindowMulticastSubscribeConfig(input) {
844
+ if (input.mode !== void 0 && !["auto", "native", "tunnel"].includes(input.mode)) {
845
+ throw new TypeError(`Unsupported multicast mode: ${String(input.mode)}`);
846
+ }
847
+ if (input.packetIds !== void 0 && !Array.isArray(input.packetIds)) {
848
+ throw new TypeError(`multicast packetIds must be an array, got ${input.packetIds === null ? "null" : typeof input.packetIds}`);
849
+ }
850
+ if (input.packetIds?.some((id) => !isMulticastTrackPacketId(id)) || input.tracks?.some((track) => !isMulticastTrackPacketId(track.packetId))) {
851
+ throw new RangeError(`multicast packetId must be an integer from 1 to ${MMTP_PACKET_ID_MAX}; packetId 0 is the MMTP signaling flow and is never a track's`);
852
+ }
853
+ const source = input.source?.trim() || void 0;
854
+ const senderAddress = input.senderAddress?.trim() || void 0;
855
+ if (source && senderAddress) {
856
+ throw new TypeError("multicast senderAddress is an ASM filter and never appears beside source");
857
+ }
858
+ const base = {
859
+ group: input.group,
860
+ port: input.port,
861
+ ...source ? { source } : {},
862
+ consume: "bytes",
863
+ ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
864
+ };
865
+ const filter = senderAddress ? { senderAddress } : {};
866
+ if (input.atsc3) {
867
+ if (senderAddress)
868
+ throw new TypeError("an ATSC3 tuner request carries no senderAddress");
869
+ const { frequency, plpId, serviceId } = input.atsc3;
870
+ if (!Number.isInteger(frequency) || frequency < 1) {
871
+ throw new TypeError(`ATSC3 tuning requires a positive integer frequency in kHz, got ${String(frequency)}`);
872
+ }
873
+ return {
874
+ ...base,
875
+ origin: "tuner",
876
+ standard: "atsc3",
877
+ frequency,
878
+ ...plpId !== void 0 ? { plpId } : {},
879
+ ...serviceId !== void 0 ? { serviceId } : {}
880
+ };
881
+ }
882
+ const relay = input.amtRelay?.trim();
883
+ const driad = !relay && input.amtDiscovery === "driad";
884
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && (relay !== void 0 && relay !== "" || driad);
885
+ if (!wantsAmt) {
886
+ const native = {
887
+ ...base,
888
+ ...filter,
889
+ origin: "ip-multicast",
890
+ ...input.tracks?.length ? { tracks: input.tracks.map(({ name, packetId }) => ({ name, packetId })) } : {}
891
+ };
892
+ return native;
893
+ }
894
+ const relayPort = input.amtRelayPort;
895
+ if (driad) {
896
+ if (!base.source)
897
+ throw new TypeError("AMT DRIAD discovery requires a source address");
898
+ if (relayPort !== void 0 && !isPositivePort(relayPort)) {
899
+ throw new TypeError("AMT DRIAD discovery requires a valid relay port when one is given");
900
+ }
901
+ return {
902
+ ...base,
903
+ source: base.source,
904
+ origin: "amt",
905
+ discovery: "driad",
906
+ ...relayPort !== void 0 ? { relayPort } : {}
907
+ };
908
+ }
909
+ if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
910
+ throw new TypeError("AMT requires a resolved relay and a valid relay port");
911
+ }
912
+ return {
913
+ ...base,
914
+ ...filter,
915
+ origin: "amt",
916
+ relay,
917
+ relayPort
918
+ };
919
+ }
920
+ function isValidMulticastGroupAddress(address) {
921
+ const value = address?.trim().toLowerCase();
922
+ if (!value)
923
+ return false;
924
+ if (value.startsWith("ff"))
925
+ return isValidIpv6MulticastAddress(value);
926
+ const parts = value.split(".");
927
+ if (parts.length !== 4)
928
+ return false;
929
+ const octets = parts.map((part) => {
930
+ if (!/^\d+$/.test(part))
931
+ return Number.NaN;
932
+ const octet = Number(part);
933
+ return Number.isInteger(octet) && octet >= 0 && octet <= 255 ? octet : Number.NaN;
934
+ });
935
+ return octets.every(Number.isInteger) && octets[0] >= 224 && octets[0] <= 239;
936
+ }
937
+ function normalizeMulticastEndpoint(endpoint) {
938
+ const groupAddress = endpoint.groupAddress.trim().toLowerCase();
939
+ const sourceAddress = endpoint.sourceAddress?.trim().toLowerCase() || void 0;
940
+ const senderAddress = endpoint.senderAddress?.trim().toLowerCase() || void 0;
941
+ if (sourceAddress && senderAddress)
942
+ return void 0;
943
+ const amtRelay = endpoint.amtRelay?.trim().toLowerCase() || void 0;
944
+ if (!isValidMulticastGroupAddress(groupAddress) || !isPositivePort(endpoint.port))
945
+ return void 0;
946
+ if (endpoint.mode && !["auto", "native", "tunnel"].includes(endpoint.mode))
947
+ return void 0;
948
+ if (endpoint.amtRelayPort !== void 0 && !isPositivePort(endpoint.amtRelayPort))
949
+ return void 0;
950
+ return {
951
+ groupAddress,
952
+ ...sourceAddress ? { sourceAddress } : {},
953
+ ...senderAddress ? { senderAddress } : {},
954
+ port: endpoint.port,
955
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
956
+ ...amtRelay ? { amtRelay } : {},
957
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
958
+ ...endpoint.amtDiscovery === "driad" ? { amtDiscovery: "driad" } : {}
959
+ };
960
+ }
961
+ function multicastEndpointKey(endpoint) {
962
+ const normalized = normalizeMulticastEndpoint(endpoint);
963
+ if (!normalized)
964
+ throw new Error("Invalid multicast endpoint");
965
+ return JSON.stringify([
966
+ normalized.sourceAddress ?? "",
967
+ normalized.groupAddress,
968
+ normalized.port,
969
+ normalized.mode ?? "auto",
970
+ normalized.amtRelay ?? "",
971
+ normalized.amtRelayPort ?? "",
972
+ // A DRIAD join is a different gateway subscription from a native one.
973
+ ...normalized.amtDiscovery ? [normalized.amtDiscovery] : [],
974
+ // An ASM sender filter is a different subscription from the unfiltered join.
975
+ ...normalized.senderAddress ? [{ senderAddress: normalized.senderAddress }] : []
976
+ ]);
977
+ }
978
+ function isMulticastTrackPacketId(value) {
979
+ return Number.isInteger(value) && value > MMTP_SIGNALING_PACKET_ID2 && value <= MMTP_PACKET_ID_MAX;
980
+ }
981
+ function isValidIpv6MulticastAddress(value) {
982
+ if (!/^[0-9a-f:]+$/.test(value))
983
+ return false;
984
+ const compressed = value.includes("::");
985
+ if (value.indexOf("::") !== value.lastIndexOf("::"))
986
+ return false;
987
+ const groups = value.split(":").filter(Boolean);
988
+ if (groups.length === 0 || groups.length > 8)
989
+ return false;
990
+ if (!compressed && groups.length !== 8)
991
+ return false;
992
+ return groups.every((group) => /^[0-9a-f]{1,4}$/.test(group));
993
+ }
994
+ function isPositivePort(port) {
995
+ return Number.isInteger(port) && port > 0 && port <= 65535;
996
+ }
997
+
998
+ // node_modules/@blockcast/mmt-transport/dist/packet-batch.js
999
+ function subscriptionDeliversPacketBatches(subscription) {
1000
+ return subscription.eventTypes?.includes("packets") === true;
1001
+ }
1002
+
1003
+ // node_modules/@blockcast/mmt-transport/dist/multicast-subscription-pool.js
1004
+ var MulticastSubscriptionPool = class {
1005
+ #entries = /* @__PURE__ */ new Map();
1006
+ #gatewayIds = /* @__PURE__ */ new WeakMap();
1007
+ #nextGatewayId = 1;
1008
+ async acquire(gateway, config, consumer) {
1009
+ const endpoint = normalizeMulticastEndpoint({
1010
+ groupAddress: config.group,
1011
+ sourceAddress: config.source,
1012
+ port: config.port,
1013
+ mode: config.mode,
1014
+ amtRelay: config.amtRelay,
1015
+ amtRelayPort: config.amtRelayPort,
1016
+ amtDiscovery: config.amtDiscovery
1017
+ });
1018
+ if (!endpoint)
1019
+ throw new Error("Invalid multicast endpoint");
1020
+ if (typeof gateway.subscribe !== "function")
1021
+ throw new Error("window.multicast.subscribe unavailable");
1022
+ const key = multicastEndpointKey(endpoint);
1023
+ const internalKey = `${this.#gatewayId(gateway)}|${key}`;
1024
+ let record = this.#entries.get(internalKey);
1025
+ if (!record) {
1026
+ record = { claims: 0, entry: Promise.resolve(null) };
1027
+ const createdRecord = record;
1028
+ record.entry = this.#createEntry(gateway, endpoint, (entry2) => {
1029
+ if (this.#entries.get(internalKey) === createdRecord)
1030
+ this.#entries.delete(internalKey);
1031
+ this.#detach(entry2);
1032
+ }).catch((error) => {
1033
+ if (this.#entries.get(internalKey) === createdRecord)
1034
+ this.#entries.delete(internalKey);
1035
+ throw error;
1036
+ });
1037
+ this.#entries.set(internalKey, record);
1038
+ }
1039
+ record.claims++;
1040
+ let entry;
1041
+ try {
1042
+ entry = await record.entry;
1043
+ } catch (error) {
1044
+ record.claims--;
1045
+ throw error;
1046
+ }
1047
+ if (entry.closed) {
1048
+ record.claims--;
1049
+ return this.acquire(gateway, config, consumer);
1050
+ }
1051
+ const token = Symbol(key);
1052
+ entry.consumers.set(token, consumer);
1053
+ let released = false;
1054
+ return {
1055
+ key,
1056
+ release: async () => {
1057
+ if (released)
1058
+ return;
1059
+ released = true;
1060
+ entry.consumers.delete(token);
1061
+ record.claims--;
1062
+ if (record.claims > 0)
1063
+ return;
1064
+ if (this.#entries.get(internalKey) === record)
1065
+ this.#entries.delete(internalKey);
1066
+ this.#detach(entry);
1067
+ if (!entry.closed)
1068
+ await entry.subscription.unsubscribe();
1069
+ }
1070
+ };
1071
+ }
1072
+ get size() {
1073
+ return this.#entries.size;
1074
+ }
1075
+ async #createEntry(gateway, endpoint, onClosed) {
1076
+ const subscription = await gateway.subscribe(toWindowMulticastSubscribeConfig({
1077
+ group: endpoint.groupAddress,
1078
+ ...endpoint.sourceAddress ? { source: endpoint.sourceAddress } : {},
1079
+ port: endpoint.port,
1080
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
1081
+ ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
1082
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {},
1083
+ ...endpoint.amtDiscovery ? { amtDiscovery: endpoint.amtDiscovery } : {}
1084
+ }));
1085
+ const consumers = /* @__PURE__ */ new Map();
1086
+ let entry;
1087
+ const packetListener = subscriptionDeliversPacketBatches(subscription) ? {
1088
+ type: "packets",
1089
+ listener: (event) => {
1090
+ for (const data of event.detail) {
1091
+ this.#dispatch(consumers, (consumer) => consumer.onBytes(data));
1092
+ }
1093
+ }
1094
+ } : {
1095
+ type: "bytes",
1096
+ listener: (event) => {
1097
+ this.#dispatch(consumers, (consumer) => consumer.onBytes(event.detail));
1098
+ }
1099
+ };
1100
+ const stateListener = (event) => {
1101
+ this.#dispatch(consumers, (consumer) => consumer.onState?.(event.detail));
1102
+ if (event.detail === "closed" && !entry.closed) {
1103
+ entry.closed = true;
1104
+ onClosed(entry);
1105
+ }
1106
+ };
1107
+ const errorListener = (event) => {
1108
+ const error = event.detail instanceof Error ? event.detail : new Error(String(event.detail));
1109
+ this.#dispatch(consumers, (consumer) => consumer.onError?.(error));
1110
+ };
1111
+ entry = { subscription, consumers, packetListener, stateListener, errorListener, closed: false };
1112
+ if (packetListener.type === "packets") {
1113
+ subscription.addEventListener("packets", packetListener.listener);
1114
+ } else {
1115
+ subscription.addEventListener("bytes", packetListener.listener);
1116
+ }
1117
+ subscription.addEventListener("state", stateListener);
1118
+ subscription.addEventListener("error", errorListener);
1119
+ return entry;
1120
+ }
1121
+ #gatewayId(gateway) {
1122
+ const object = gateway;
1123
+ let id = this.#gatewayIds.get(object);
1124
+ if (!id) {
1125
+ id = this.#nextGatewayId++;
1126
+ this.#gatewayIds.set(object, id);
1127
+ }
1128
+ return id;
1129
+ }
1130
+ #detach(entry) {
1131
+ const { packetListener } = entry;
1132
+ if (packetListener.type === "packets") {
1133
+ entry.subscription.removeEventListener("packets", packetListener.listener);
1134
+ } else {
1135
+ entry.subscription.removeEventListener("bytes", packetListener.listener);
1136
+ }
1137
+ entry.subscription.removeEventListener("state", entry.stateListener);
1138
+ entry.subscription.removeEventListener("error", entry.errorListener);
1139
+ }
1140
+ #dispatch(consumers, callback) {
1141
+ for (const consumer of consumers.values()) {
1142
+ try {
1143
+ callback(consumer);
1144
+ } catch (error) {
1145
+ console.error("[Transport] multicast consumer callback failed", error);
1146
+ }
1147
+ }
1148
+ }
1149
+ };
1150
+ var multicastSubscriptionPool = new MulticastSubscriptionPool();
1151
+
1152
+ // node_modules/@blockcast/mmt-transport/dist/transport-manager.js
1153
+ var TransportManager = class {
1154
+ state = {
1155
+ mode: "disconnected",
1156
+ connected: false,
1157
+ packetsReceived: 0,
1158
+ bytesReceived: 0,
1159
+ lastPacketTime: 0
1160
+ };
1161
+ capabilities = null;
1162
+ subscription = null;
1163
+ /** Built by `connect()` from the caller's ladder; there is no built-in one. */
1164
+ abr = null;
1165
+ multicastOrchestrator = null;
1166
+ onOrchestratorCommand;
1167
+ connectionGeneration = 0;
1168
+ onPacket;
1169
+ onError;
1170
+ onStateChange;
1171
+ getWindow() {
1172
+ return typeof window === "undefined" ? void 0 : window;
1173
+ }
1174
+ getWindowMulticastGateway() {
1175
+ return this.getWindow()?.multicast;
1176
+ }
1177
+ async getGatewayCapabilities(gateway) {
1178
+ if (!gateway?.capabilities)
1179
+ return void 0;
1180
+ try {
1181
+ return typeof gateway.capabilities === "function" ? await gateway.capabilities() : gateway.capabilities;
1182
+ } catch (error) {
1183
+ console.warn("[Transport] window.multicast capabilities failed:", error);
1184
+ return void 0;
1185
+ }
1186
+ }
1187
+ async gatewaySupportsBytes(gateway) {
1188
+ if (typeof gateway?.subscribe !== "function")
1189
+ return false;
1190
+ if (!gateway.capabilities)
1191
+ return true;
1192
+ const capabilities = await this.getGatewayCapabilities(gateway);
1193
+ if (!capabilities)
1194
+ return false;
1195
+ const consumeModes = capabilities.consumeModes;
1196
+ return !consumeModes || consumeModes.includes("bytes");
1197
+ }
1198
+ /**
1199
+ * Detect available transport capabilities
1200
+ */
1201
+ async detectCapabilities() {
1202
+ if (this.capabilities)
1203
+ return this.capabilities;
1204
+ const gateway = this.getWindowMulticastGateway();
1205
+ const hasGatewayBytes = await this.gatewaySupportsBytes(gateway);
1206
+ const win = this.getWindow();
1207
+ this.capabilities = {
1208
+ nativeSSM: hasGatewayBytes,
1209
+ nativeIGMP: hasGatewayBytes,
1210
+ directSockets: typeof win?.UDPSocket !== "undefined",
1211
+ amt: false,
1212
+ driad: hasGatewayBytes,
1213
+ // the gateway runs RFC 8777 discovery
1214
+ fecDecode: false
1215
+ };
1216
+ console.log("[Transport] Capabilities:", this.capabilities);
1217
+ return this.capabilities;
1218
+ }
1219
+ /**
1220
+ * Connect using best available transport
1221
+ *
1222
+ * Promotion hierarchy:
1223
+ * 1. window.multicast gateway bytes
1224
+ * 2. AMT: a configured relay via the AMT proxy, else gateway DRIAD discovery
1225
+ * 3. MOQ WebTransport (final fallback)
1226
+ *
1227
+ * The ABR ladder (`abrLadder`) and initial rendition (`initialQuality`)
1228
+ * are checked first, before anything is torn down. A config that fails is
1229
+ * refused with the same shape as an invalid endpoint, the error to the
1230
+ * error callback and `false` resolved; unlike one, it is caught before the
1231
+ * live subscription closes, so a refused reconnect leaves that subscription,
1232
+ * its state and any connect already in flight untouched.
1233
+ */
1234
+ async connect(config) {
1235
+ let abr;
1236
+ try {
1237
+ abr = new AdaptiveBitrateController({
1238
+ ladder: config.abrLadder,
1239
+ initialQuality: config.initialQuality?.name
1240
+ });
1241
+ } catch (error) {
1242
+ const refused = error instanceof Error ? error : new Error(String(error));
1243
+ if (this.onError)
1244
+ this.onError(refused);
1245
+ else
1246
+ console.error("[Transport] ABR config refused, not connecting:", refused);
1247
+ return false;
1248
+ }
1249
+ const generation = ++this.connectionGeneration;
1250
+ this.subscription?.close();
1251
+ this.subscription = null;
1252
+ this.abr = null;
1253
+ this.state = {
1254
+ mode: "disconnected",
1255
+ connected: false,
1256
+ packetsReceived: 0,
1257
+ bytesReceived: 0,
1258
+ lastPacketTime: 0
1259
+ };
1260
+ this.onStateChange?.(this.state);
1261
+ const endpoint = normalizeMulticastEndpoint({
1262
+ groupAddress: config.group,
1263
+ sourceAddress: config.source,
1264
+ port: config.port,
1265
+ mode: config.mode,
1266
+ amtRelay: config.amtRelay,
1267
+ amtRelayPort: config.amtRelayPort
1268
+ });
1269
+ if (!endpoint) {
1270
+ const error = new Error("Invalid multicast endpoint configuration");
1271
+ this.onError?.(error);
1272
+ return false;
1273
+ }
1274
+ config = {
1275
+ ...config,
1276
+ group: endpoint.groupAddress,
1277
+ source: endpoint.sourceAddress ?? "",
1278
+ mode: endpoint.mode,
1279
+ amtRelay: endpoint.amtRelay,
1280
+ amtRelayPort: endpoint.amtRelayPort
1281
+ };
1282
+ const caps = await this.detectCapabilities();
1283
+ if (generation !== this.connectionGeneration)
1284
+ return false;
1285
+ this.abr = abr;
1286
+ abr.setCallback((quality) => {
1287
+ this.state.quality = quality;
1288
+ this.subscription?.onqualitychange?.(quality);
1289
+ this.onStateChange?.(this.state);
1290
+ });
1291
+ let connected = false;
1292
+ if (caps.nativeSSM || caps.nativeIGMP) {
1293
+ console.log("[Transport] Attempting window.multicast...");
1294
+ connected = await this.connectWindowMulticast(config, generation);
1295
+ if (connected) {
1296
+ if (generation !== this.connectionGeneration)
1297
+ return false;
1298
+ this.state.mode = "multicast";
1299
+ return true;
1300
+ }
1301
+ }
1302
+ if (!connected) {
1303
+ console.log("[Transport] Attempting AMT tunnel...");
1304
+ connected = await this.connectAmt(config, generation);
1305
+ if (connected) {
1306
+ if (generation !== this.connectionGeneration)
1307
+ return false;
1308
+ this.state.mode = "amt";
1309
+ return true;
1310
+ }
1311
+ }
1312
+ console.log("[Transport] All multicast transports failed, falling back to MOQ");
1313
+ return false;
1314
+ }
1315
+ /**
1316
+ * Connect via the lowercase window.multicast bytes gateway.
1317
+ */
1318
+ async connectWindowMulticast(config, generation, mode = "multicast") {
1319
+ try {
1320
+ const gateway = this.getWindowMulticastGateway();
1321
+ if (typeof gateway?.subscribe !== "function")
1322
+ return false;
1323
+ const lease = await multicastSubscriptionPool.acquire(gateway, config, {
1324
+ onBytes: (data) => {
1325
+ if (generation === this.connectionGeneration)
1326
+ this.handlePacket(data);
1327
+ },
1328
+ onState: (state) => {
1329
+ if (generation !== this.connectionGeneration)
1330
+ return;
1331
+ this.state.connected = state !== "closed";
1332
+ this.onStateChange?.(this.state);
1333
+ },
1334
+ onError: (error) => {
1335
+ if (generation !== this.connectionGeneration)
1336
+ return;
1337
+ console.error("[Transport] window.multicast error:", error);
1338
+ this.onError?.(error);
1339
+ }
1340
+ });
1341
+ if (generation !== this.connectionGeneration) {
1342
+ await lease.release();
1343
+ return false;
1344
+ }
1345
+ this.subscription = {
1346
+ id: lease.key,
1347
+ config,
1348
+ close: () => {
1349
+ void lease.release();
1350
+ }
1351
+ };
1352
+ this.state = {
1353
+ mode,
1354
+ connected: true,
1355
+ group: config.group,
1356
+ source: config.source,
1357
+ quality: this.requireAbr().getCurrentQuality(),
1358
+ packetsReceived: 0,
1359
+ bytesReceived: 0,
1360
+ lastPacketTime: 0
1361
+ };
1362
+ console.log(`[Transport] Connected via window.multicast: (${config.source}, ${config.group})`);
1363
+ this.onStateChange?.(this.state);
1364
+ return true;
1365
+ } catch (error) {
1366
+ console.warn("[Transport] window.multicast failed:", error);
1367
+ return false;
1368
+ }
1369
+ }
1370
+ /**
1371
+ * Connect via AMT: a configured relay goes through the AMT proxy; with no
1372
+ * relay, the window.multicast gateway discovers one per RFC 8777 (DRIAD).
1373
+ */
1374
+ async connectAmt(config, generation) {
1375
+ try {
1376
+ if (config.amtRelay)
1377
+ return await this.connectAmtProxy(config, config.amtRelay, generation);
1378
+ if (config.driadEnabled === false || !config.source || config.mode === "native") {
1379
+ console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
1380
+ return false;
1381
+ }
1382
+ console.log(`[Transport] Asking the gateway for a DRIAD relay for source ${config.source}...`);
1383
+ return await this.connectWindowMulticast({ ...config, amtDiscovery: "driad" }, generation, "amt");
1384
+ } catch (error) {
1385
+ console.warn("[Transport] AMT connection failed:", error);
1386
+ return false;
1387
+ }
1388
+ }
1389
+ /**
1390
+ * Connect via WebSocket-based AMT proxy (browser fallback)
1391
+ */
1392
+ async connectAmtProxy(config, amtRelay, generation) {
1393
+ try {
1394
+ const relayHost = amtRelay.includes(":") && !amtRelay.startsWith("[") ? `[${amtRelay}]` : amtRelay;
1395
+ const wsUrl = new URL(`wss://${relayHost}/amt-proxy`);
1396
+ wsUrl.searchParams.set("group", config.group);
1397
+ wsUrl.searchParams.set("source", config.source || "");
1398
+ wsUrl.searchParams.set("port", String(config.port));
1399
+ const ws = new WebSocket(wsUrl);
1400
+ return new Promise((resolve, reject) => {
1401
+ ws.binaryType = "arraybuffer";
1402
+ const timeout = setTimeout(() => {
1403
+ ws.close();
1404
+ reject(new Error("AMT proxy connection timeout"));
1405
+ }, 1e4);
1406
+ ws.onopen = () => {
1407
+ clearTimeout(timeout);
1408
+ if (generation !== this.connectionGeneration) {
1409
+ ws.close();
1410
+ resolve(false);
1411
+ return;
1412
+ }
1413
+ console.log(`[Transport] Connected to AMT proxy: ${amtRelay}`);
1414
+ this.subscription = {
1415
+ id: `amt-proxy-${Date.now()}`,
1416
+ config,
1417
+ close: () => ws.close()
1418
+ };
1419
+ this.state = {
1420
+ mode: "amt",
1421
+ connected: true,
1422
+ group: config.group,
1423
+ source: config.source,
1424
+ amtRelay,
1425
+ quality: this.requireAbr().getCurrentQuality(),
1426
+ packetsReceived: 0,
1427
+ bytesReceived: 0,
1428
+ lastPacketTime: 0
1429
+ };
1430
+ this.onStateChange?.(this.state);
1431
+ resolve(true);
1432
+ };
1433
+ ws.onmessage = (event) => {
1434
+ if (generation === this.connectionGeneration && event.data instanceof ArrayBuffer) {
1435
+ this.handlePacket(event.data);
1436
+ }
1437
+ };
1438
+ ws.onerror = (error) => {
1439
+ clearTimeout(timeout);
1440
+ if (generation !== this.connectionGeneration) {
1441
+ resolve(false);
1442
+ return;
1443
+ }
1444
+ console.error("[Transport] AMT proxy error:", error);
1445
+ reject(error);
1446
+ };
1447
+ ws.onclose = () => {
1448
+ clearTimeout(timeout);
1449
+ if (generation !== this.connectionGeneration) {
1450
+ resolve(false);
1451
+ return;
1452
+ }
1453
+ this.state.connected = false;
1454
+ this.onStateChange?.(this.state);
1455
+ resolve(false);
1456
+ };
1457
+ });
1458
+ } catch (error) {
1459
+ console.warn("[Transport] AMT proxy failed:", error);
1460
+ return false;
1461
+ }
1462
+ }
1463
+ /**
1464
+ * Handle received packet
1465
+ */
1466
+ handlePacket(data) {
1467
+ this.state.packetsReceived++;
1468
+ this.state.bytesReceived += data.byteLength;
1469
+ this.state.lastPacketTime = Date.now();
1470
+ this.abr?.recordSample(data.byteLength, 0);
1471
+ this.onPacket?.(data);
1472
+ }
1473
+ /**
1474
+ * Get current transport state
1475
+ */
1476
+ getState() {
1477
+ return { ...this.state };
1478
+ }
1479
+ /**
1480
+ * The rung of the live connection's `abrLadder` ABR is on; `null` when
1481
+ * there is no ladder (before `connect(config)` succeeds, after
1482
+ * `disconnect()`, or after a reconnect that was torn down and bailed).
1483
+ */
1484
+ getQuality() {
1485
+ return this.abr?.getCurrentQuality() ?? null;
1486
+ }
1487
+ /**
1488
+ * Force the rung named `name` of the live connection's `abrLadder`.
1489
+ * Throws `Error` when there is no ladder (see `getQuality()`), and
1490
+ * `RangeError` when the ladder has no rung of that name; it never falls
1491
+ * back to another rung.
1492
+ */
1493
+ setQuality(name) {
1494
+ this.requireAbr().setQuality(name);
1495
+ }
1496
+ /** The controller `connect()` built; before it there is no ladder to adapt over. */
1497
+ requireAbr() {
1498
+ if (!this.abr)
1499
+ throw new Error("[Transport] ABR has no ladder before connect(config)");
1500
+ return this.abr;
1501
+ }
1502
+ /** Configures multicast-only ABR while leaving the caller's MoQ ABR untouched. */
1503
+ configureMulticastTiers(options, onCommand) {
1504
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
1505
+ this.multicastOrchestrator = new MulticastOrchestrator(options);
1506
+ this.onOrchestratorCommand = onCommand;
1507
+ return this.multicastOrchestrator.start();
1508
+ }
1509
+ recordMulticastGoodput(bitrate) {
1510
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onGoodput({ bitrate }));
1511
+ }
1512
+ recordMulticastHeadroom(healthy) {
1513
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onHeadroom({ healthy }));
1514
+ }
1515
+ recordMulticastTierPacket(packet) {
1516
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onTierPacket(packet));
1517
+ }
1518
+ pollMulticastTierSwitch() {
1519
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.poll());
1520
+ }
1521
+ /** Abandon the in-flight tier join, e.g. because the host could not join the target. */
1522
+ cancelMulticastTierJoin() {
1523
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
1524
+ }
1525
+ /**
1526
+ * Set packet callback
1527
+ */
1528
+ setPacketCallback(callback) {
1529
+ this.onPacket = callback;
1530
+ }
1531
+ /**
1532
+ * Set error callback
1533
+ */
1534
+ setErrorCallback(callback) {
1535
+ this.onError = callback;
1536
+ }
1537
+ /**
1538
+ * Set state change callback
1539
+ */
1540
+ setStateCallback(callback) {
1541
+ this.onStateChange = callback;
1542
+ }
1543
+ /**
1544
+ * Disconnect
1545
+ */
1546
+ disconnect() {
1547
+ this.connectionGeneration++;
1548
+ this.subscription?.close();
1549
+ this.subscription = null;
1550
+ this.abr = null;
1551
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
1552
+ this.multicastOrchestrator = null;
1553
+ this.onOrchestratorCommand = void 0;
1554
+ this.state = {
1555
+ mode: "disconnected",
1556
+ connected: false,
1557
+ packetsReceived: 0,
1558
+ bytesReceived: 0,
1559
+ lastPacketTime: 0
1560
+ };
1561
+ this.onStateChange?.(this.state);
1562
+ }
1563
+ dispatchOrchestratorCommand(command) {
1564
+ if (command)
1565
+ this.onOrchestratorCommand?.(command);
1566
+ return command;
1567
+ }
1568
+ };
1569
+ var transportManager = new TransportManager();
1570
+
1571
+ // node_modules/@blockcast/mmt-transport/dist/multicast-receiver-gateway.js
1572
+ var USER_AGENT_VERIFIED = /* @__PURE__ */ Symbol.for("@blockcast/mmt-transport/user-agent-verified/v1");
1573
+
1574
+ // node_modules/@blockcast/mmt-transport/dist/moqt-priority.js
1575
+ var MAX_MOQT_PRIORITY = 255;
1576
+ function moqtPriority(value, field) {
1577
+ if (!Number.isInteger(value) || value < 0 || value > MAX_MOQT_PRIORITY) {
1578
+ throw new RangeError(`${field} must be an integer in [0, ${MAX_MOQT_PRIORITY}], got ${value}`);
1579
+ }
1580
+ return value;
1581
+ }
1582
+ function moqtSubscriberPriority(value) {
1583
+ return moqtPriority(value, "MOQT subscriber priority");
1584
+ }
1585
+ function moqtPublisherPriority(value) {
1586
+ return moqtPriority(value, "MOQT publisher priority");
1587
+ }
1588
+ var MOQT_SUBSCRIBER_PRIORITY = Object.freeze({
1589
+ catalog: moqtSubscriberPriority(0),
1590
+ /**
1591
+ * @deprecated A repair FETCH's SUBSCRIBER_PRIORITY is derived per request
1592
+ * from the catalog source and repair priorities (draft-ramadan-moq-fec
1593
+ * §11.4.5), not a player constant. Use the `subscriberPriority` that
1594
+ * `@blockcast/mmt-container`'s `wireRepairFetch` puts on each
1595
+ * `RepairFetchRequest` (`repairFetchSubscriberPriority`).
1596
+ */
1597
+ deadlineRepair: moqtSubscriberPriority(0),
1598
+ audio: moqtSubscriberPriority(1),
1599
+ video: moqtSubscriberPriority(2),
1600
+ /**
1601
+ * @deprecated See `deadlineRepair`: use the request's catalog-derived
1602
+ * `RepairFetchRequest.subscriberPriority` (draft-ramadan-moq-fec §11.4.5).
1603
+ */
1604
+ backgroundRepair: moqtSubscriberPriority(3)
1605
+ });
1606
+ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
1607
+ catalog: moqtPublisherPriority(32),
1608
+ source: moqtPublisherPriority(128),
1609
+ repair: moqtPublisherPriority(240)
1610
+ });
1611
+
1612
+ // node_modules/@blockcast/mmt-transport/dist/amt-gateway.js
1613
+ var AMTGatewayManager = class {
1614
+ subscriptions = /* @__PURE__ */ new Map();
1615
+ messageHandler;
1616
+ pendingPackets = /* @__PURE__ */ new Map();
1617
+ constructor() {
1618
+ this.messageHandler = (event) => {
1619
+ const data = event.data;
1620
+ console.log(`[AMT] SW message received:`, data.type);
1621
+ if (data.type === "UDP_PACKET") {
1622
+ this.handlePacket(data);
1623
+ } else if (data.type === "SOCKET_ERROR") {
1624
+ this.handleSocketError(data);
1625
+ } else if (data.type === "DEBUG_LOG") {
1626
+ console.log(`[AMT SW Debug] ${data.message}`);
1627
+ }
1628
+ };
1629
+ if (typeof navigator !== "undefined" && navigator.serviceWorker) {
1630
+ navigator.serviceWorker.addEventListener("message", this.messageHandler);
1631
+ console.log("[AMT] Registered service worker message handler");
1632
+ } else {
1633
+ console.warn("[AMT] Service worker not available");
1634
+ }
1635
+ }
1636
+ /**
1637
+ * Subscribe via AMT tunnel
1638
+ */
1639
+ async subscribe(config) {
1640
+ const { key } = config;
1641
+ if (config.protected) {
1642
+ throw new Error("AMTGatewayManager refuses a protected join: it reports no per-datagram sender (multicast-02 7.2.7)");
1643
+ }
1644
+ const keyStr = this.getKeyString(key);
1645
+ if (this.subscriptions.has(keyStr)) {
1646
+ console.log(`[AMT] Reusing existing subscription to ${keyStr}`);
1647
+ return keyStr;
1648
+ }
1649
+ try {
1650
+ const relayAddress = config.relayAddress;
1651
+ const relayPort = config.relayPort || DEFAULT_AMT_RELAY_PORT;
1652
+ if (!relayAddress) {
1653
+ throw new Error(`AMT relay address required: this manager does no relay discovery. For RFC 8777 DRIAD discovery, join through window.multicast with amtDiscovery: "driad".`);
1654
+ }
1655
+ console.log(`[AMT] Using configured relay ${relayAddress}:${relayPort}`);
1656
+ const subscriptionId = keyStr;
1657
+ this.pendingPackets.set(subscriptionId, []);
1658
+ const subscription = {
1659
+ key,
1660
+ subscriptionId,
1661
+ config,
1662
+ handshakeComplete: false,
1663
+ relay: {
1664
+ address: relayAddress,
1665
+ port: relayPort,
1666
+ discoveryMethod: "manual",
1667
+ discoveredAt: Date.now()
1668
+ }
1669
+ };
1670
+ this.subscriptions.set(keyStr, subscription);
1671
+ console.log(`[AMT] Subscription created for ${keyStr} via ${relayAddress}:${relayPort}`);
1672
+ return keyStr;
1673
+ } catch (error) {
1674
+ const subscription = this.subscriptions.get(keyStr);
1675
+ if (subscription) {
1676
+ this.subscriptions.delete(keyStr);
1677
+ this.pendingPackets.delete(subscription.subscriptionId);
1678
+ }
1679
+ throw new Error(`Failed to subscribe via AMT: ${error instanceof Error ? error.message : String(error)}`);
1680
+ }
1681
+ }
1682
+ /**
1683
+ * Unsubscribe from AMT tunnel
1684
+ */
1685
+ async unsubscribe(handle) {
1686
+ const subscription = this.subscriptions.get(handle);
1687
+ if (!subscription) {
1688
+ throw new Error(`Subscription ${handle} not found`);
1689
+ }
1690
+ try {
1691
+ if (subscription.keepAliveTimer) {
1692
+ clearInterval(subscription.keepAliveTimer);
1693
+ }
1694
+ console.log(`[AMT] Unsubscribed from ${handle}`);
1695
+ } catch (error) {
1696
+ console.error("[AMT] Error during unsubscribe:", error);
1697
+ } finally {
1698
+ this.subscriptions.delete(handle);
1699
+ this.pendingPackets.delete(subscription.subscriptionId);
1700
+ }
1701
+ }
1702
+ /**
1703
+ * Get list of active subscriptions
1704
+ */
1705
+ getSubscriptions() {
1706
+ return Array.from(this.subscriptions.keys());
1707
+ }
1708
+ /**
1709
+ * Handle packet from service worker
1710
+ */
1711
+ handlePacket(message) {
1712
+ const { subscriptionId, data } = message;
1713
+ if (!subscriptionId)
1714
+ return;
1715
+ const subscription = this.subscriptions.get(subscriptionId);
1716
+ if (!subscription) {
1717
+ console.warn(`[AMT] Received packet for unknown subscription: ${subscriptionId}`);
1718
+ return;
1719
+ }
1720
+ if (!subscription.handshakeComplete) {
1721
+ const queue = this.pendingPackets.get(subscriptionId);
1722
+ const packetData2 = data;
1723
+ if (queue) {
1724
+ queue.push({
1725
+ data: packetData2.data,
1726
+ remoteAddress: packetData2.remoteAddress,
1727
+ remotePort: packetData2.remotePort
1728
+ });
1729
+ }
1730
+ return;
1731
+ }
1732
+ const packetData = data;
1733
+ const metadata = {
1734
+ sourceAddress: subscription.relay?.address || "unknown",
1735
+ sourcePort: subscription.relay?.port || 0,
1736
+ transport: "tunnel",
1737
+ timestamp: performance.now()
1738
+ };
1739
+ subscription.config.onPacket(packetData.data, metadata);
1740
+ }
1741
+ /**
1742
+ * Handle socket error from service worker
1743
+ */
1744
+ handleSocketError(message) {
1745
+ const { subscriptionId, error } = message;
1746
+ if (!subscriptionId)
1747
+ return;
1748
+ const subscription = this.subscriptions.get(subscriptionId);
1749
+ if (!subscription) {
1750
+ console.warn(`[AMT] Received error for unknown subscription: ${subscriptionId}`);
1751
+ return;
1752
+ }
1753
+ subscription.config.onError(new Error(error || "Unknown error"));
1754
+ }
1755
+ /**
1756
+ * Cleanup on destroy
1757
+ */
1758
+ destroy() {
1759
+ if (this.messageHandler && typeof navigator !== "undefined" && navigator.serviceWorker) {
1760
+ navigator.serviceWorker.removeEventListener("message", this.messageHandler);
1761
+ }
1762
+ const handles = Array.from(this.subscriptions.keys());
1763
+ for (const handle of handles) {
1764
+ this.unsubscribe(handle).catch((err) => {
1765
+ console.error(`[AMT] Error unsubscribing ${handle}:`, err);
1766
+ });
1767
+ }
1768
+ }
1769
+ /**
1770
+ * Get key string for HashMap
1771
+ */
1772
+ getKeyString(key) {
1773
+ const source = key.source ? `@${key.source}` : "";
1774
+ return `${key.group}:${key.port}${source}`;
1775
+ }
1776
+ };
1777
+ var amtGatewayManager = new AMTGatewayManager();
1778
+
380
1779
  // src/mfu-reassembler.ts
381
1780
  function fragmentProvenance(fragment) {
382
1781
  if (fragment.deliveryProvenance !== void 0) return fragment.deliveryProvenance;
@@ -8183,7 +9582,7 @@ function decideGap(input) {
8183
9582
 
8184
9583
  // src/duplicate-ledger.ts
8185
9584
  var COUNT_BOUNDED_GENERATION = 2e3;
8186
- function serial32Precedes2(a, b) {
9585
+ function serial32Precedes3(a, b) {
8187
9586
  const distance = b - a >>> 0;
8188
9587
  return distance !== 0 && distance < 2147483648;
8189
9588
  }
@@ -8359,12 +9758,12 @@ var StreamDuplicateLedgers = class {
8359
9758
  predatesHorizon(packetSequenceNumber, ssId) {
8360
9759
  if (this.#retentionMs === null) return false;
8361
9760
  const seqFloor = this.sourceSeqs.horizonFloor;
8362
- if (seqFloor !== void 0 && serial32Precedes2(packetSequenceNumber, seqFloor) && !this.sourceSeqs.has(packetSequenceNumber)) {
9761
+ if (seqFloor !== void 0 && serial32Precedes3(packetSequenceNumber, seqFloor) && !this.sourceSeqs.has(packetSequenceNumber)) {
8363
9762
  return true;
8364
9763
  }
8365
9764
  if (ssId === void 0) return false;
8366
9765
  const ssIdFloor = this.parsedSymbols.horizonFloor;
8367
- return ssIdFloor !== void 0 && serial32Precedes2(ssId, ssIdFloor) && !this.parsedSymbols.has(ssId);
9766
+ return ssIdFloor !== void 0 && serial32Precedes3(ssId, ssIdFloor) && !this.parsedSymbols.has(ssId);
8368
9767
  }
8369
9768
  /** Whether the stream keeps ledgers, for its FEC horizon or by count. */
8370
9769
  get retaining() {
@@ -9571,10 +10970,11 @@ var MmtpRouter = class {
9571
10970
  if (!entry) return;
9572
10971
  entry.receiver.release();
9573
10972
  entry.protected = false;
10973
+ entry.userAgent = false;
9574
10974
  this.#assistBlocks.clear();
9575
10975
  this.#assistFailures.clear();
9576
10976
  }
9577
- /** MoQ packets of a track a protected flow lists, dropped on its unicast path: duplicate, overflow, or listed by more than one flow. */
10977
+ /** Packets of a track a protected flow lists, dropped unread: a MoQ copy (duplicate, overflow, or listed by more than one flow) or a multicast source datagram that names no flow, of a track a user-agent-admitted flow lists. */
9578
10978
  get unadmittedListedDropCount() {
9579
10979
  return this.#unadmittedListedDrops;
9580
10980
  }
@@ -9615,6 +11015,13 @@ var MmtpRouter = class {
9615
11015
  }
9616
11016
  return false;
9617
11017
  }
11018
+ /** Whether a protected flow the user agent admitted lists `packetId`. */
11019
+ #userAgentGoverns(packetId) {
11020
+ for (const entry of this.#provenance.values()) {
11021
+ if (entry.protected && entry.userAgent && ingressHasPacketId(entry.ingress, packetId)) return true;
11022
+ }
11023
+ return false;
11024
+ }
9618
11025
  /**
9619
11026
  * A MoQ repair symbol no protected flow lists, owned by a source track one
9620
11027
  * does: its FEC instance is governed (7.2.7 step 2) and takes only admitted
@@ -9705,7 +11112,7 @@ var MmtpRouter = class {
9705
11112
  fec.cancelBlockTimeout(blockStart, ownerPacketId, catalogTrackName);
9706
11113
  fec.countRecovery(ownerPacketId, blockStart, catalogTrackName);
9707
11114
  fec.markBlockCompleted(blockStart, ownerPacketId, catalogTrackName);
9708
- })) {
11115
+ }, true)) {
9709
11116
  this.#unlistedAssistedRecoveries++;
9710
11117
  this.#assistBlocks.delete(key);
9711
11118
  return;
@@ -10861,6 +12268,12 @@ var MmtpRouter = class {
10861
12268
  debugRouter(`[MmtpRouter] Dropping multicast packet pid=${info.packetId}: flow ${ingress.flow} has no receiver`);
10862
12269
  return;
10863
12270
  }
12271
+ if (ingress.admittedBy === USER_AGENT_VERIFIED) {
12272
+ this.#noteFlowAdmitted(ingress.flow);
12273
+ protectedFlow.userAgent = true;
12274
+ this.#processMMTP(packet, source, true, ingress, overlapCopy);
12275
+ return;
12276
+ }
10864
12277
  const { verdict } = protectedFlow.receiver.onDatagram(packet, "multicast");
10865
12278
  if (verdict === "admitted") {
10866
12279
  this.#noteFlowAdmitted(ingress.flow);
@@ -10878,6 +12291,11 @@ var MmtpRouter = class {
10878
12291
  return;
10879
12292
  }
10880
12293
  }
12294
+ const flowless = source === "multicast" && !manifestAdmitted && ingress?.flow === void 0;
12295
+ if (flowless && !info.isRepair && this.#userAgentGoverns(info.packetId)) {
12296
+ this.#unadmittedListedDrops++;
12297
+ return;
12298
+ }
10881
12299
  if (info.isRepair) {
10882
12300
  const overlay = this.#overlayRepairTarget(info.packetId, catalogTrackNameForPacket(ingress, info.packetId));
10883
12301
  if (overlay !== void 0) {
@@ -10895,7 +12313,7 @@ var MmtpRouter = class {
10895
12313
  );
10896
12314
  if (!repair) return;
10897
12315
  if (ownerPacketId != null && this.#fecManager) {
10898
- if (source === "moq" && !manifestAdmitted && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
12316
+ if ((flowless && this.#userAgentGoverns(ownerPacketId) || source === "moq" && !manifestAdmitted) && this.#setAsideUnlistedRepair(ownerPacketId, catalogTrackNameForPacket(ingress, ownerPacketId), repair)) return;
10899
12317
  this.#repairPidCounts[info.packetId] = (this.#repairPidCounts[info.packetId] || 0) + 1;
10900
12318
  const count = this.#repairPidCounts[info.packetId];
10901
12319
  if (count <= 2 || count % 500 === 0) {
@@ -11474,7 +12892,7 @@ var MmtpRouter = class {
11474
12892
  }
11475
12893
  // ── Private: FEC recovery routing ───────────────────────────────
11476
12894
  /** Route WASM-recovered block through appropriate path based on container kind. */
11477
- #routeRecoveredBlock(blockId, recovered, ownerPacketId, catalogTrackName, complete) {
12895
+ #routeRecoveredBlock(blockId, recovered, ownerPacketId, catalogTrackName, complete, assisted = false) {
11478
12896
  const packetSymbolSize = this.#symbolSizeForPacket(ownerPacketId);
11479
12897
  if (ownerPacketId === void 0) {
11480
12898
  throw new Error("[MmtpRouter] a recovered FEC block needs its owner packetId to read its fec.blockProfile");
@@ -11491,7 +12909,7 @@ var MmtpRouter = class {
11491
12909
  ownerPacketId,
11492
12910
  blockProfile
11493
12911
  });
11494
- return this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete);
12912
+ return this.#routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted);
11495
12913
  }
11496
12914
  /**
11497
12915
  * A recovered source packet of a protected flow is admitted on its own
@@ -11503,9 +12921,24 @@ var MmtpRouter = class {
11503
12921
  * recovered packets is refused is unrecovered (7.2.7): its caller leaves it
11504
12922
  * open, so it reaches its FEC deadline and fails by class. Always true
11505
12923
  * outside a protected flow.
12924
+ *
12925
+ * On a flow the user agent admitted, the live decoder's recoveries are kept
12926
+ * without a record: while the flow is protected that decoder takes only
12927
+ * symbols the user agent or a record verified (a flow-less multicast
12928
+ * datagram of a listed track is dropped or set aside in #processMMTP), so
12929
+ * what it recovers is as verified as they are. An `assisted` (scratch-decoder) recovery mixes in
12930
+ * unlisted MoQ repair and still needs a record.
12931
+ * ponytail: per-flow flag; per-block provenance only if a protected flow
12932
+ * ever mixes verified and unverified live inputs.
12933
+ * ponytail: a worker frame computed before the protection reset can still
12934
+ * arrive after it (frames carry no epoch); its inputs are MoQ copies read
12935
+ * and played before protection, so it admits nothing new. Drop pre-reset
12936
+ * frames by epoch only if pre-protection input ever matters.
11506
12937
  */
11507
- #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete) {
11508
- const receiver = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
12938
+ #routeVerifiedFecSymbols(blockId, result, ownerPacketId, catalogTrackName, complete, assisted = false) {
12939
+ const entry = ownerPacketId == null ? void 0 : this.#provenanceFor(ownerPacketId, catalogTrackName);
12940
+ const receiver = entry === void 0 || entry === "ambiguous" ? entry : entry.receiver;
12941
+ const userAgent = !assisted && entry !== void 0 && entry !== "ambiguous" && entry.protected === true && entry.userAgent === true;
11509
12942
  let recovered = true;
11510
12943
  if (receiver) {
11511
12944
  const parsed = this.#stream(ownerPacketId, catalogTrackName).duplicates.parsedSymbols;
@@ -11517,6 +12950,8 @@ var MmtpRouter = class {
11517
12950
  let admitted = false;
11518
12951
  if (receiver === "ambiguous") {
11519
12952
  this.#ambiguousRecoveredDrops++;
12953
+ } else if (userAgent) {
12954
+ admitted = true;
11520
12955
  } else {
11521
12956
  const wire = new Uint8Array(sym.rawSymbol.byteLength + 4);
11522
12957
  wire.set(sym.rawSymbol);
@@ -11544,12 +12979,12 @@ var MmtpRouter = class {
11544
12979
  catalogTrackName === void 0 || !byName ? byName?.values() : byName.has(catalogTrackName) ? [byName.get(catalogTrackName)] : []
11545
12980
  );
11546
12981
  if (flows.size > 1) return "ambiguous";
11547
- for (const bound of flows) return this.#provenance.get(bound)?.receiver ?? "ambiguous";
12982
+ for (const bound of flows) return this.#provenance.get(bound) ?? "ambiguous";
11548
12983
  let match;
11549
- for (const { receiver, ingress } of this.#provenance.values()) {
11550
- if (ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === void 0 || t.name === catalogTrackName))) {
12984
+ for (const entry of this.#provenance.values()) {
12985
+ if (entry.ingress.tracks.some((t) => t.packetId === packetId && (catalogTrackName === void 0 || t.name === catalogTrackName))) {
11551
12986
  if (match) return "ambiguous";
11552
- match = receiver;
12987
+ match = entry;
11553
12988
  }
11554
12989
  }
11555
12990
  return match;