@blockcast/mmt-transport 0.2.1 → 0.2.2-main.0399efef1f07

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 (107) hide show
  1. package/README.md +20 -54
  2. package/dist/driad-discovery.d.ts.map +1 -1
  3. package/dist/driad-discovery.js +1 -5
  4. package/dist/driad-discovery.js.map +1 -1
  5. package/dist/endpoint-config.d.ts +30 -0
  6. package/dist/endpoint-config.d.ts.map +1 -1
  7. package/dist/endpoint-config.js +40 -0
  8. package/dist/endpoint-config.js.map +1 -1
  9. package/dist/index.d.ts +8 -7
  10. package/dist/index.d.ts.map +1 -1
  11. package/dist/index.js +6 -10
  12. package/dist/index.js.map +1 -1
  13. package/dist/mmt-transport.no-modules.js +571 -14
  14. package/dist/mmt-transport.no-modules.js.map +4 -4
  15. package/dist/moqt-priority.d.ts +28 -0
  16. package/dist/moqt-priority.d.ts.map +1 -0
  17. package/dist/moqt-priority.js +30 -0
  18. package/dist/moqt-priority.js.map +1 -0
  19. package/dist/multicast-catalog-policy.d.ts +64 -0
  20. package/dist/multicast-catalog-policy.d.ts.map +1 -0
  21. package/dist/multicast-catalog-policy.js +377 -0
  22. package/dist/multicast-catalog-policy.js.map +1 -0
  23. package/dist/multicast-orchestrator.d.ts +4 -0
  24. package/dist/multicast-orchestrator.d.ts.map +1 -1
  25. package/dist/multicast-orchestrator.js +55 -3
  26. package/dist/multicast-orchestrator.js.map +1 -1
  27. package/dist/multicast-signaling-reconciler.d.ts +37 -0
  28. package/dist/multicast-signaling-reconciler.d.ts.map +1 -0
  29. package/dist/multicast-signaling-reconciler.js +158 -0
  30. package/dist/multicast-signaling-reconciler.js.map +1 -0
  31. package/dist/multicast-subscription-pool.d.ts.map +1 -1
  32. package/dist/multicast-subscription-pool.js +3 -4
  33. package/dist/multicast-subscription-pool.js.map +1 -1
  34. package/dist/multicast-tier.d.ts +19 -0
  35. package/dist/multicast-tier.d.ts.map +1 -1
  36. package/dist/multicast-tier.js +21 -4
  37. package/dist/multicast-tier.js.map +1 -1
  38. package/dist/no-modules.d.ts +37 -2
  39. package/dist/no-modules.d.ts.map +1 -1
  40. package/dist/no-modules.js +27 -2
  41. package/dist/no-modules.js.map +1 -1
  42. package/dist/stall-detector.d.ts +10 -0
  43. package/dist/stall-detector.d.ts.map +1 -1
  44. package/dist/stall-detector.js +21 -0
  45. package/dist/stall-detector.js.map +1 -1
  46. package/dist/takeover.d.ts +3 -0
  47. package/dist/takeover.d.ts.map +1 -1
  48. package/dist/takeover.js +35 -2
  49. package/dist/takeover.js.map +1 -1
  50. package/dist/transport-manager.d.ts +1 -11
  51. package/dist/transport-manager.d.ts.map +1 -1
  52. package/dist/transport-manager.js +3 -11
  53. package/dist/transport-manager.js.map +1 -1
  54. package/dist/types.d.ts +35 -112
  55. package/dist/types.d.ts.map +1 -1
  56. package/dist/types.js +12 -45
  57. package/dist/types.js.map +1 -1
  58. package/package.json +7 -9
  59. package/src/driad-discovery.ts +1 -5
  60. package/src/endpoint-config.ts +70 -0
  61. package/src/index.ts +46 -32
  62. package/src/moqt-priority.ts +40 -0
  63. package/src/multicast-catalog-policy.ts +468 -0
  64. package/src/multicast-orchestrator.ts +55 -4
  65. package/src/multicast-signaling-reconciler.ts +153 -0
  66. package/src/multicast-subscription-pool.ts +7 -4
  67. package/src/multicast-tier.ts +30 -3
  68. package/src/no-modules.ts +50 -1
  69. package/src/stall-detector.ts +37 -0
  70. package/src/takeover.ts +41 -3
  71. package/src/transport-manager.ts +4 -13
  72. package/src/types.ts +38 -148
  73. package/dist/endpoint-config.test.d.ts +0 -2
  74. package/dist/endpoint-config.test.d.ts.map +0 -1
  75. package/dist/endpoint-config.test.js +0 -39
  76. package/dist/endpoint-config.test.js.map +0 -1
  77. package/dist/fec-client.d.ts +0 -442
  78. package/dist/fec-client.d.ts.map +0 -1
  79. package/dist/fec-client.js +0 -789
  80. package/dist/fec-client.js.map +0 -1
  81. package/dist/fec-client.test.d.ts +0 -8
  82. package/dist/fec-client.test.d.ts.map +0 -1
  83. package/dist/fec-client.test.js +0 -112
  84. package/dist/fec-client.test.js.map +0 -1
  85. package/dist/multicast-subscription-pool.test.d.ts +0 -2
  86. package/dist/multicast-subscription-pool.test.d.ts.map +0 -1
  87. package/dist/multicast-subscription-pool.test.js +0 -108
  88. package/dist/multicast-subscription-pool.test.js.map +0 -1
  89. package/dist/multicast-tier.test.d.ts +0 -2
  90. package/dist/multicast-tier.test.d.ts.map +0 -1
  91. package/dist/multicast-tier.test.js +0 -75
  92. package/dist/multicast-tier.test.js.map +0 -1
  93. package/dist/stall-detector.test.d.ts +0 -2
  94. package/dist/stall-detector.test.d.ts.map +0 -1
  95. package/dist/stall-detector.test.js +0 -33
  96. package/dist/stall-detector.test.js.map +0 -1
  97. package/dist/transport-manager.test.d.ts +0 -2
  98. package/dist/transport-manager.test.d.ts.map +0 -1
  99. package/dist/transport-manager.test.js +0 -155
  100. package/dist/transport-manager.test.js.map +0 -1
  101. package/src/endpoint-config.test.ts +0 -54
  102. package/src/fec-client.test.ts +0 -140
  103. package/src/fec-client.ts +0 -1103
  104. package/src/multicast-subscription-pool.test.ts +0 -115
  105. package/src/multicast-tier.test.ts +0 -80
  106. package/src/stall-detector.test.ts +0 -34
  107. package/src/transport-manager.test.ts +0 -192
@@ -4,10 +4,14 @@
4
4
  function endpointKey(endpoint) {
5
5
  return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
6
6
  }
7
+ function carriesMedia(endpoint) {
8
+ return endpoint.carriesMedia !== false;
9
+ }
7
10
  function selectMulticastTier(endpoints, estimate) {
8
- if (endpoints.length <= 1) return endpoints[0];
9
- const ranked = endpoints.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > 0).sort((a, b) => a.bandwidth - b.bandwidth);
10
- if (ranked.length < 2) return endpoints[0];
11
+ const media = endpoints.filter(carriesMedia);
12
+ if (media.length <= 1) return media[0];
13
+ const ranked = media.filter((endpoint) => typeof endpoint.bandwidth === "number" && endpoint.bandwidth > 0).sort((a, b) => a.bandwidth - b.bandwidth);
14
+ if (ranked.length < 2) return media[0];
11
15
  if (estimate === void 0) return ranked[0];
12
16
  const budget = estimate * 0.8;
13
17
  let selected;
@@ -163,6 +167,38 @@
163
167
  };
164
168
 
165
169
  // src/endpoint-config.ts
170
+ function toWindowMulticastSubscribeConfig(input) {
171
+ if (input.mode !== void 0 && !["auto", "native", "tunnel"].includes(input.mode)) {
172
+ throw new TypeError(`Unsupported multicast mode: ${String(input.mode)}`);
173
+ }
174
+ const base = {
175
+ group: input.group,
176
+ port: input.port,
177
+ ...input.source?.trim() ? { source: input.source.trim() } : {},
178
+ consume: "bytes",
179
+ ...input.packetIds?.length ? { packetIds: [...input.packetIds] } : {}
180
+ };
181
+ const relay = input.amtRelay?.trim();
182
+ const wantsAmt = input.mode === "tunnel" || input.mode !== "native" && relay !== void 0 && relay !== "";
183
+ if (!wantsAmt) {
184
+ const native = {
185
+ ...base,
186
+ origin: "ip-multicast",
187
+ ...input.tracks?.length ? { tracks: input.tracks.map(({ name, packetId }) => ({ name, packetId })) } : {}
188
+ };
189
+ return native;
190
+ }
191
+ const relayPort = input.amtRelayPort;
192
+ if (!relay || relayPort === void 0 || !isPositivePort(relayPort)) {
193
+ throw new TypeError("AMT requires a resolved relay and a valid relay port");
194
+ }
195
+ return {
196
+ ...base,
197
+ origin: "amt",
198
+ relay,
199
+ relayPort
200
+ };
201
+ }
166
202
  function isValidMulticastGroupAddress(address) {
167
203
  const value = address?.trim().toLowerCase();
168
204
  if (!value) return false;
@@ -291,19 +327,57 @@
291
327
  }
292
328
  onGoodput(sample) {
293
329
  const bitrate = sample.bitrate;
294
- this.#estimate = bitrate;
295
330
  if (!this.#current || this.options.adaptive === false) return void 0;
296
331
  if (this.#state === "joining") return this.poll();
332
+ if (bitrate === void 0 || !Number.isFinite(bitrate)) return void 0;
333
+ this.#estimate = bitrate;
297
334
  const desired = selectMulticastTier(this.options.endpoints, bitrate);
298
335
  if (!desired) return void 0;
299
336
  const desiredKey = endpointKey(desired);
337
+ if (desiredKey === endpointKey(this.#current)) {
338
+ if (this.#favored?.source === "goodput") this.#favored = void 0;
339
+ return void 0;
340
+ }
341
+ if (typeof desired.bandwidth !== "number" || typeof this.#current.bandwidth !== "number" || desired.bandwidth >= this.#current.bandwidth) {
342
+ if (this.#favored?.source === "goodput") this.#favored = void 0;
343
+ return void 0;
344
+ }
345
+ const now = this.#now();
346
+ if (!this.#favored || this.#favored.key !== desiredKey || this.#favored.source !== "goodput") {
347
+ this.#favored = { key: desiredKey, since: now, source: "goodput" };
348
+ return void 0;
349
+ }
350
+ if (now - this.#favored.since < this.#dwellMs) return void 0;
351
+ this.#state = "joining";
352
+ this.#target = desired;
353
+ this.#joinStartedAt = now;
354
+ this.#favored = void 0;
355
+ return { kind: "join-target", current: this.#current, target: desired };
356
+ }
357
+ onHeadroom(sample) {
358
+ if (!this.#current || this.options.adaptive === false || this.#state === "joining") return void 0;
359
+ if (!sample.healthy) {
360
+ if (this.#favored?.source === "headroom") this.#favored = void 0;
361
+ return void 0;
362
+ }
363
+ if (this.#favored?.source === "goodput") return void 0;
364
+ const currentBandwidth = this.#current.bandwidth;
365
+ if (typeof currentBandwidth !== "number") return void 0;
366
+ const desired = this.options.endpoints.filter(
367
+ (endpoint) => carriesMedia(endpoint) && typeof endpoint.bandwidth === "number" && endpoint.bandwidth > currentBandwidth
368
+ ).sort((a, b) => a.bandwidth - b.bandwidth)[0];
369
+ if (!desired) {
370
+ this.#favored = void 0;
371
+ return void 0;
372
+ }
373
+ const desiredKey = endpointKey(desired);
300
374
  if (desiredKey === endpointKey(this.#current)) {
301
375
  this.#favored = void 0;
302
376
  return void 0;
303
377
  }
304
378
  const now = this.#now();
305
379
  if (!this.#favored || this.#favored.key !== desiredKey) {
306
- this.#favored = { key: desiredKey, since: now };
380
+ this.#favored = { key: desiredKey, since: now, source: "headroom" };
307
381
  return void 0;
308
382
  }
309
383
  if (now - this.#favored.since < this.#dwellMs) return void 0;
@@ -356,6 +430,390 @@
356
430
  }
357
431
  };
358
432
 
433
+ // src/multicast-signaling-reconciler.ts
434
+ function createMulticastSignalingReconciler(catalog, options = {}) {
435
+ const initial = normalizeCatalogEndpoints(catalog);
436
+ const endpoints = new Map(initial.map((endpoint) => [endpoint.endpointId, copyEndpoint(endpoint)]));
437
+ const versions = new Map(initial.map((endpoint) => [endpoint.endpointId, endpoint.endpointVersion]));
438
+ const seen = /* @__PURE__ */ new Set();
439
+ const dormant = /* @__PURE__ */ new Set();
440
+ let catalogVersion = Number(catalog?.multicast?.version ?? catalog?.version ?? 0) || 0;
441
+ const snapshot = (now = Date.now()) => ({
442
+ catalogVersion,
443
+ endpoints: [...endpoints.values()].filter((endpoint) => !dormant.has(endpoint.endpointId) && !isExpired(endpoint, now)).map(copyEndpoint),
444
+ dormantEndpointIds: [...dormant].sort()
445
+ });
446
+ return {
447
+ apply(signal, now = Date.now()) {
448
+ if (!isObject(signal) || typeof signal.type !== "string" || typeof signal.msgId !== "string") return { applied: false, reason: "invalid-message" };
449
+ if (seen.has(signal.msgId)) return { applied: false, reason: "duplicate-message" };
450
+ if (signal.expiresAt != null && Number(signal.expiresAt) < now) return { applied: false, reason: "expired" };
451
+ const signalCatalogVersion = Number(signal.catalogVersion ?? 0);
452
+ if (!Number.isFinite(signalCatalogVersion)) return { applied: false, reason: "invalid-message" };
453
+ if (signalCatalogVersion < catalogVersion) return { applied: false, reason: "stale-catalog" };
454
+ const result = applyFresh(signal, now);
455
+ if (result.applied) {
456
+ seen.add(signal.msgId);
457
+ if (signal.type !== "heartbeat") {
458
+ catalogVersion = Math.max(catalogVersion, signalCatalogVersion);
459
+ }
460
+ }
461
+ return result;
462
+ },
463
+ snapshot,
464
+ toCatalog(now = Date.now()) {
465
+ const current = snapshot(now);
466
+ return { ...catalog, multicast: { ...catalog.multicast, version: current.catalogVersion, endpoints: current.endpoints } };
467
+ }
468
+ };
469
+ function applyFresh(signal, now) {
470
+ switch (signal.type) {
471
+ case "snapshot": {
472
+ const next = signal.payload?.endpoints;
473
+ if (!Array.isArray(next)) return { applied: false, reason: "invalid-message" };
474
+ const normalized = next.map((endpoint, index) => normalizeEndpoint(endpoint, index));
475
+ if (normalized.some((endpoint) => !endpoint || !isValidEndpoint(endpoint, options.catalog))) return { applied: false, reason: "invalid-endpoint" };
476
+ const ids = new Set(normalized.map((endpoint) => endpoint.endpointId));
477
+ if (ids.size !== normalized.length) return { applied: false, reason: "duplicate-endpoint" };
478
+ endpoints.clear();
479
+ versions.clear();
480
+ dormant.clear();
481
+ for (const endpoint of normalized) {
482
+ versions.set(endpoint.endpointId, endpoint.endpointVersion);
483
+ if (!isExpired(endpoint, now)) endpoints.set(endpoint.endpointId, copyEndpoint(endpoint));
484
+ }
485
+ return { applied: true, action: "snapshot" };
486
+ }
487
+ case "add":
488
+ return upsert(signal.payload?.endpoint, now);
489
+ case "update": {
490
+ const id = signal.payload?.endpointId;
491
+ const fields = signal.payload?.fields;
492
+ if (!endpoints.has(id)) return { applied: false, reason: "unknown-endpoint" };
493
+ if (isStale(id, signal.payload?.endpointVersion)) return { applied: false, reason: "stale-endpoint" };
494
+ if (!isObject(fields) || ["protocol", "sourceAddress", "groupAddress", "port"].some((key) => Object.hasOwn(fields, key))) return { applied: false, reason: "invalid-update" };
495
+ return upsert({ ...endpoints.get(id), ...fields, endpointVersion: signal.payload.endpointVersion }, now);
496
+ }
497
+ case "remove": {
498
+ const id = signal.payload?.endpointId;
499
+ if (!endpoints.has(id)) return { applied: false, reason: "unknown-endpoint" };
500
+ const endpointVersion = Number(signal.payload?.endpointVersion);
501
+ if (!Number.isFinite(endpointVersion)) return { applied: false, reason: "invalid-message" };
502
+ if (isStale(id, endpointVersion)) return { applied: false, reason: "stale-endpoint" };
503
+ endpoints.delete(id);
504
+ dormant.delete(id);
505
+ versions.set(id, endpointVersion);
506
+ return { applied: true, action: "drop" };
507
+ }
508
+ case "invalidate": {
509
+ const id = signal.payload?.endpointId;
510
+ if (!endpoints.has(id)) return { applied: false, reason: "unknown-endpoint" };
511
+ dormant.add(id);
512
+ return { applied: true, action: "drop" };
513
+ }
514
+ case "heartbeat":
515
+ return { applied: true, action: "heartbeat" };
516
+ default:
517
+ return { applied: false, reason: "unknown-message-type" };
518
+ }
519
+ }
520
+ function upsert(value, now) {
521
+ const endpoint = normalizeEndpoint(value, endpoints.size);
522
+ if (!endpoint || !isValidEndpoint(endpoint, options.catalog)) return { applied: false, reason: "invalid-endpoint" };
523
+ if (isStale(endpoint.endpointId, endpoint.endpointVersion)) return { applied: false, reason: "stale-endpoint" };
524
+ versions.set(endpoint.endpointId, endpoint.endpointVersion);
525
+ dormant.delete(endpoint.endpointId);
526
+ if (isExpired(endpoint, now)) endpoints.delete(endpoint.endpointId);
527
+ else endpoints.set(endpoint.endpointId, copyEndpoint(endpoint));
528
+ return { applied: true, action: isExpired(endpoint, now) ? "drop" : "candidate" };
529
+ }
530
+ function isStale(id, version) {
531
+ const current = versions.get(id);
532
+ return current !== void 0 && Number(version) <= current;
533
+ }
534
+ }
535
+ function normalizeCatalogEndpoints(catalog) {
536
+ const endpoints = catalog?.multicast?.endpoints;
537
+ if (!Array.isArray(endpoints)) return [];
538
+ return endpoints.map(normalizeEndpoint).filter((endpoint) => !!endpoint && isValidEndpoint(endpoint, catalog));
539
+ }
540
+ function normalizeEndpoint(value, index) {
541
+ if (!isObject(value)) return void 0;
542
+ const endpoint = value;
543
+ const tracks = Array.isArray(endpoint.tracks) ? endpoint.tracks.map((track) => typeof track === "string" ? { name: track } : { ...track }).filter((track) => track.name) : [];
544
+ return { ...endpoint, endpointId: endpoint.endpointId || `${endpoint.sourceAddress || ""}|${endpoint.groupAddress || ""}|${endpoint.port || ""}|${index}`, endpointVersion: Number(endpoint.endpointVersion ?? 0), tracks };
545
+ }
546
+ function isValidEndpoint(endpoint, catalog) {
547
+ if (!endpoint.endpointId || !Number.isFinite(endpoint.endpointVersion)) return false;
548
+ if (!["ssm", "asm", "amt"].includes(endpoint.protocol)) return false;
549
+ if (endpoint.protocol === "ssm" && (typeof endpoint.sourceAddress !== "string" || endpoint.sourceAddress.trim().length === 0)) return false;
550
+ if (!isValidMulticastGroupAddress(endpoint.groupAddress) || !Number.isInteger(Number(endpoint.port)) || endpoint.port <= 0 || endpoint.port > 65535 || !endpoint.tracks.length) return false;
551
+ const catalogTracks = /* @__PURE__ */ new Set([...Object.keys(catalog?.video?.renditions ?? {}), ...Object.keys(catalog?.audio?.renditions ?? {})]);
552
+ return endpoint.tracks.every((track) => !!track.name && Number.isInteger(Number(track.packetId)) && (catalogTracks.size === 0 || catalogTracks.has(track.name) || catalogTracks.has(track.name.replace(/\/repair$/, ""))));
553
+ }
554
+ function copyEndpoint(endpoint) {
555
+ return { ...endpoint, tracks: endpoint.tracks.map((track) => ({ ...track })) };
556
+ }
557
+ function isExpired(endpoint, now) {
558
+ return endpoint.validUntil != null && Number(endpoint.validUntil) < now;
559
+ }
560
+ function isObject(value) {
561
+ return value !== null && typeof value === "object";
562
+ }
563
+
564
+ // src/multicast-catalog-policy.ts
565
+ function hasMulticastCatalogBaseline(catalog) {
566
+ const multicast = catalog?.multicast;
567
+ return normalizeCatalogEndpoints(catalog).length > 0 || Boolean(multicast?.groupAddress && multicast?.port);
568
+ }
569
+ function hasUnicastMediaRenditions(catalog) {
570
+ return Object.keys(catalog?.video?.renditions ?? {}).length > 0 || Object.keys(catalog?.audio?.renditions ?? {}).length > 0;
571
+ }
572
+ function isMulticastOnlyCatalog(catalog) {
573
+ return hasMulticastCatalogBaseline(catalog) && !hasUnicastMediaRenditions(catalog);
574
+ }
575
+ function requiresMulticastCapability(catalog, capabilities = {}) {
576
+ return isMulticastOnlyCatalog(catalog) && !capabilities.multicast;
577
+ }
578
+ function isRecoverableMulticastSignalReadError(error) {
579
+ const candidate = error;
580
+ const name = String(candidate?.name ?? "");
581
+ const message = String(candidate?.message ?? error ?? "");
582
+ return name === "SyntaxError" || /not valid JSON|unexpected token|JSON\.parse|encoded data was not valid|malformed/i.test(message);
583
+ }
584
+ function withMulticastEndpoints(catalog, endpoints, version) {
585
+ if (!catalog?.multicast) return catalog;
586
+ return {
587
+ ...catalog,
588
+ multicast: {
589
+ ...catalog.multicast,
590
+ version,
591
+ endpoints: endpoints.map(copyEndpoint2)
592
+ }
593
+ };
594
+ }
595
+ function selectMulticastCandidate(catalog, endpoints = normalizeCatalogEndpoints(catalog), search = currentSearchParams()) {
596
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search);
597
+ return selectMulticastCandidateForTracks(catalog, endpoints, {
598
+ containerKind: params.get("packaging") || params.get("container") || "mmtp",
599
+ rendition: params.get("rendition") || void 0
600
+ });
601
+ }
602
+ function selectMulticastCandidateForTracks(catalog, endpoints = normalizeCatalogEndpoints(catalog), selection = {}) {
603
+ const packaging = selection.containerKind || "mmtp";
604
+ const renditionTrack = selection.rendition || "";
605
+ const preferredTrack = packaging === "mmtp" ? "video" : `video.${packaging}`;
606
+ const usableEndpoints = endpoints.filter(isUsableMulticastEndpoint);
607
+ const defaultRenditionTrack = renditionTrack ? "" : lowestServedVideoRendition(catalog, usableEndpoints);
608
+ return renditionTrack && usableEndpoints.find((endpoint) => endpoint.tracks?.some((track) => matchesPreferredTrack(track.name, renditionTrack))) || defaultRenditionTrack && usableEndpoints.find((endpoint) => endpoint.tracks?.some((track) => matchesPreferredTrack(track.name, defaultRenditionTrack))) || usableEndpoints.find((endpoint) => endpoint.tracks?.some((track) => matchesPreferredTrack(track.name, preferredTrack))) || usableEndpoints[0] || null;
609
+ }
610
+ function endpointToMulticastConfig(endpoint, catalog, selection) {
611
+ if (!endpoint || !isUsableMulticastEndpoint(endpoint)) return null;
612
+ const config = {
613
+ group: endpoint.groupAddress,
614
+ source: endpoint.sourceAddress || "",
615
+ port: Number(endpoint.port)
616
+ };
617
+ const networkSource = endpoint.networkSource ?? catalog?.multicast?.networkSource;
618
+ const amt = findAmtRelay(networkSource);
619
+ if (endpoint.protocol === "amt" || amt) {
620
+ config.mode = "tunnel";
621
+ if (amt) {
622
+ config.amtRelay = amt.relay;
623
+ if (amt.port) config.amtRelayPort = amt.port;
624
+ }
625
+ }
626
+ const packetIds = selection === void 0 ? selectEndpointPacketIds(endpoint, catalog) : selectEndpointPacketIdsForTracks(endpoint, catalog, selection);
627
+ if (packetIds.length > 0) config.packetIds = packetIds;
628
+ return config;
629
+ }
630
+ function selectEndpointPacketIds(endpoint, catalog, search = currentSearchParams()) {
631
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search);
632
+ return selectEndpointPacketIdsForTracks(endpoint, catalog, {
633
+ containerKind: params.get("packaging") || params.get("container") || "mmtp",
634
+ rendition: params.get("rendition") || void 0
635
+ });
636
+ }
637
+ function selectEndpointPacketIdsForTracks(endpoint, catalog, selection = {}) {
638
+ if (!endpoint || !Array.isArray(endpoint.tracks)) return [];
639
+ const tracks = endpoint.tracks.map((track) => ({
640
+ name: typeof track?.name === "string" ? track.name : "",
641
+ packetId: validPacketId(track?.packetId)
642
+ })).filter((track) => track.name.length > 0 && track.packetId !== void 0);
643
+ if (tracks.length === 0) return [];
644
+ const packaging = selection.containerKind || "mmtp";
645
+ const renditionTrack = selection.rendition || "";
646
+ const videoRenditions = catalogRenditions(catalog, "video");
647
+ const audioRenditions = catalogRenditions(catalog, "audio");
648
+ const videoTracks = tracks.filter((track) => Object.hasOwn(videoRenditions, track.name));
649
+ const audioTracks = tracks.filter((track) => Object.hasOwn(audioRenditions, track.name));
650
+ const preferredVideo = packaging === "mmtp" ? "video" : `video.${packaging}`;
651
+ const preferredAudio = packaging === "mmtp" ? "audio" : `audio.${packaging}`;
652
+ const video = (renditionTrack ? videoTracks.find((track) => track.name === renditionTrack) : void 0) ?? videoTracks.find((track) => track.name === preferredVideo) ?? [...videoTracks].sort((a, b) => videoRenditionRank(videoRenditions, a.name) - videoRenditionRank(videoRenditions, b.name))[0];
653
+ const audio = audioTracks.find((track) => track.name === preferredAudio) ?? audioTracks[0];
654
+ const selected = [video, audio].filter(
655
+ (track) => track !== void 0
656
+ );
657
+ if (selected.length === 0) return normalizePacketIds(tracks.map((track) => track.packetId));
658
+ const selectedRepairNames = new Set(selected.flatMap((track) => catalogRepairTracks(catalog, track.name)));
659
+ const selectedRepairTracks = tracks.filter((track) => selectedRepairNames.has(track.name));
660
+ return normalizePacketIds([...selected, ...selectedRepairTracks].map((track) => track.packetId));
661
+ }
662
+ function readPlayerMulticastConfig(search = currentSearchParams()) {
663
+ const params = search instanceof URLSearchParams ? search : new URLSearchParams(search || "");
664
+ const group = params.get("mc_group") || "";
665
+ if (!isValidMulticastGroupAddress(group)) return null;
666
+ const port = positivePort2(params.get("mc_port"));
667
+ if (!port) return null;
668
+ const mode = params.get("mc_mode") || "";
669
+ const amtRelay = params.get("mc_amt_relay") || params.get("amt_relay") || "";
670
+ const amtRelayPort = positivePort2(params.get("mc_amt_relay_port") || params.get("amt_relay_port"));
671
+ const config = {
672
+ group,
673
+ source: params.get("mc_source") || "",
674
+ port
675
+ };
676
+ if (mode) config.mode = mode;
677
+ if (amtRelay) {
678
+ config.amtRelay = amtRelay;
679
+ config.mode = "tunnel";
680
+ }
681
+ if (amtRelayPort) config.amtRelayPort = amtRelayPort;
682
+ return config;
683
+ }
684
+ function normalizeMulticastConfig(config) {
685
+ if (!config?.group) return null;
686
+ const amt = findAmtRelay(config.amtNetworkSource);
687
+ const amtRelay = config.amtRelay || amt?.relay || "";
688
+ const amtRelayPort = config.amtRelayPort ?? amt?.port;
689
+ const packetIds = normalizePacketIds(config.packetIds);
690
+ return {
691
+ group: config.group,
692
+ source: config.source || "",
693
+ port: Number(config.port),
694
+ mode: amtRelay ? "tunnel" : config.mode || "auto",
695
+ amtRelay,
696
+ ...amtRelayPort ? { amtRelayPort } : {},
697
+ ...packetIds.length > 0 ? { packetIds } : {}
698
+ };
699
+ }
700
+ function sameMulticastConfig(a, b) {
701
+ const left = normalizeMulticastConfig(a);
702
+ const right = normalizeMulticastConfig(b);
703
+ return Boolean(left && right && left.group === right.group && left.source === right.source && left.port === right.port && left.mode === right.mode && left.amtRelay === right.amtRelay && (left.amtRelayPort ?? 0) === (right.amtRelayPort ?? 0) && JSON.stringify(left.packetIds ?? []) === JSON.stringify(right.packetIds ?? []));
704
+ }
705
+ function urlOverrideBlocksMulticastCandidate(candidateConfig, urlConfig = readPlayerMulticastConfig()) {
706
+ if (!urlConfig) return false;
707
+ const candidate = normalizeMulticastConfig(candidateConfig);
708
+ const explicit = normalizeMulticastConfig(urlConfig);
709
+ return !candidate || !explicit || candidate.group !== explicit.group || candidate.source !== explicit.source || candidate.port !== explicit.port;
710
+ }
711
+ function mergeUrlMulticastPolicy(candidateConfig, urlConfig = readPlayerMulticastConfig()) {
712
+ const candidate = normalizeMulticastConfig(candidateConfig);
713
+ if (!candidate || !urlConfig || urlOverrideBlocksMulticastCandidate(candidate, urlConfig)) return candidate;
714
+ const merged = { ...candidate };
715
+ if (urlConfig.mode !== void 0) {
716
+ merged.mode = urlConfig.mode;
717
+ if (urlConfig.mode !== "tunnel" && urlConfig.amtRelay === void 0) {
718
+ merged.amtRelay = "";
719
+ delete merged.amtRelayPort;
720
+ }
721
+ }
722
+ if (urlConfig.amtRelay !== void 0) {
723
+ merged.amtRelay = urlConfig.amtRelay;
724
+ merged.mode = "tunnel";
725
+ }
726
+ if (urlConfig.amtRelayPort !== void 0) merged.amtRelayPort = urlConfig.amtRelayPort;
727
+ return normalizeMulticastConfig(merged);
728
+ }
729
+ function currentSearchParams() {
730
+ return typeof location === "undefined" ? new URLSearchParams() : new URLSearchParams(location.search);
731
+ }
732
+ function positivePort2(value) {
733
+ const port = Number(value);
734
+ return Number.isInteger(port) && port > 0 && port <= 65535 ? port : null;
735
+ }
736
+ function copyEndpoint2(endpoint) {
737
+ return { ...endpoint, tracks: endpoint.tracks.map((track) => ({ ...track })) };
738
+ }
739
+ function findAmtRelay(networkSource) {
740
+ const sources = Array.isArray(networkSource) ? networkSource : networkSource ? [networkSource] : [];
741
+ const source = sources.find((candidate) => candidate?.type === "amt" && typeof candidate?.relay === "string" && candidate.relay.trim());
742
+ if (!source) return void 0;
743
+ const port = positivePort2(String(source.port ?? ""));
744
+ const relay = source.relay.trim();
745
+ return port ? { relay, port } : { relay };
746
+ }
747
+ function validPacketId(value) {
748
+ const packetId = typeof value === "number" ? value : Number(value);
749
+ return Number.isInteger(packetId) && packetId >= 0 && packetId <= 65535 ? packetId : void 0;
750
+ }
751
+ function normalizePacketIds(packetIds) {
752
+ if (!Array.isArray(packetIds)) return [];
753
+ return [...new Set(packetIds.map(validPacketId).filter((id) => id !== void 0))].sort(
754
+ (a, b) => a - b
755
+ );
756
+ }
757
+ function matchesPreferredTrack(trackName, preferredTrack) {
758
+ return trackName === preferredTrack || trackName.startsWith(`${preferredTrack}/`);
759
+ }
760
+ function catalogRenditions(catalog, role) {
761
+ const renditions = { ...catalog?.[role]?.renditions ?? {} };
762
+ for (const track of Array.isArray(catalog?.tracks) ? catalog.tracks : []) {
763
+ if (track?.role === role && typeof track.name === "string" && track.name.length > 0) {
764
+ renditions[track.name] = track;
765
+ }
766
+ }
767
+ return renditions;
768
+ }
769
+ function catalogRepairTracks(catalog, name) {
770
+ const tracks = Array.isArray(catalog?.tracks) ? catalog.tracks : [];
771
+ const track = tracks.find((candidate) => candidate?.name === name);
772
+ const rendition = catalog?.video?.renditions?.[name] ?? catalog?.audio?.renditions?.[name];
773
+ const fec = track?.fec ?? rendition?.fec;
774
+ if (!fec || fec.algorithm === "none") return [];
775
+ const names = /* @__PURE__ */ new Set();
776
+ if (typeof fec.repairTrack === "string" && fec.repairTrack.length > 0) names.add(fec.repairTrack);
777
+ const dependsOn = (entry) => Array.isArray(entry?.depends) && entry.depends.length === 1 && entry.depends[0] === name;
778
+ const common = catalog?.commonTrackFields ?? {};
779
+ for (const candidate of tracks) {
780
+ const packaging = candidate?.packaging ?? common?.packaging;
781
+ if (packaging === "fec-repair" && typeof candidate?.name === "string" && candidate.name.length > 0 && dependsOn(candidate)) {
782
+ names.add(candidate.name);
783
+ }
784
+ }
785
+ const repairRenditions = catalog?.repair?.renditions;
786
+ if (repairRenditions && typeof repairRenditions === "object") {
787
+ for (const [repairName, entry] of Object.entries(repairRenditions)) {
788
+ if (repairName.length > 0 && dependsOn(entry)) names.add(repairName);
789
+ }
790
+ }
791
+ return [...names];
792
+ }
793
+ function videoRenditionRank(config, name) {
794
+ if (typeof config?.bitrate === "number" && config.bitrate > 0) return config.bitrate;
795
+ const width = typeof config?.codedWidth === "number" ? config.codedWidth : 0;
796
+ const height = typeof config?.codedHeight === "number" ? config.codedHeight : 0;
797
+ if (width > 0 && height > 0) return width * height;
798
+ const match = /(?:^|[/_.-])(\d{3,4})p(?:$|[/_.-])/i.exec(name);
799
+ return match ? Number(match[1]) : Number.POSITIVE_INFINITY;
800
+ }
801
+ function lowestServedVideoRendition(catalog, endpoints) {
802
+ const renditions = catalog?.video?.renditions ?? {};
803
+ const servedTracks = new Set(endpoints.flatMap((endpoint) => endpoint.tracks?.map((track) => track.name) ?? []));
804
+ let selected = "";
805
+ let selectedRank = Number.POSITIVE_INFINITY;
806
+ for (const [name, config] of Object.entries(renditions)) {
807
+ if (!name || !servedTracks.has(name)) continue;
808
+ const rank = videoRenditionRank(config, name);
809
+ if (!selected || rank < selectedRank) {
810
+ selected = name;
811
+ selectedRank = rank;
812
+ }
813
+ }
814
+ return selected;
815
+ }
816
+
359
817
  // src/multicast-subscription-pool.ts
360
818
  var MulticastSubscriptionPool = class {
361
819
  #entries = /* @__PURE__ */ new Map();
@@ -420,15 +878,14 @@
420
878
  return this.#entries.size;
421
879
  }
422
880
  async #createEntry(gateway, endpoint, onClosed) {
423
- const subscription = await gateway.subscribe({
881
+ const subscription = await gateway.subscribe(toWindowMulticastSubscribeConfig({
424
882
  group: endpoint.groupAddress,
425
883
  ...endpoint.sourceAddress ? { source: endpoint.sourceAddress } : {},
426
884
  port: endpoint.port,
427
- consume: "bytes",
428
885
  ...endpoint.mode ? { mode: endpoint.mode } : {},
429
886
  ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
430
887
  ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
431
- });
888
+ }));
432
889
  const consumers = /* @__PURE__ */ new Map();
433
890
  let entry;
434
891
  const bytesListener = (event) => {
@@ -477,7 +934,59 @@
477
934
  };
478
935
  var multicastSubscriptionPool = new MulticastSubscriptionPool();
479
936
 
937
+ // src/moqt-priority.ts
938
+ var MAX_MOQT_PRIORITY = 255;
939
+ function moqtPriority(value, field) {
940
+ if (!Number.isInteger(value) || value < 0 || value > MAX_MOQT_PRIORITY) {
941
+ throw new RangeError(`${field} must be an integer in [0, ${MAX_MOQT_PRIORITY}], got ${value}`);
942
+ }
943
+ return value;
944
+ }
945
+ function moqtSubscriberPriority(value) {
946
+ return moqtPriority(value, "MOQT subscriber priority");
947
+ }
948
+ function moqtPublisherPriority(value) {
949
+ return moqtPriority(value, "MOQT publisher priority");
950
+ }
951
+ var MOQT_SUBSCRIBER_PRIORITY = Object.freeze({
952
+ catalog: moqtSubscriberPriority(0),
953
+ deadlineRepair: moqtSubscriberPriority(0),
954
+ audio: moqtSubscriberPriority(1),
955
+ video: moqtSubscriberPriority(2),
956
+ backgroundRepair: moqtSubscriberPriority(3)
957
+ });
958
+ var MOQT_PUBLISHER_PRIORITY = Object.freeze({
959
+ catalog: moqtPublisherPriority(32),
960
+ source: moqtPublisherPriority(128),
961
+ repair: moqtPublisherPriority(240)
962
+ });
963
+
480
964
  // src/stall-detector.ts
965
+ function classifyStall({
966
+ liveQ = null,
967
+ decodeCallsDelta = null,
968
+ fps = null
969
+ } = {}) {
970
+ if (liveQ != null && liveQ >= 20) {
971
+ return {
972
+ verdict: "DECODE-BOUND",
973
+ reason: `decode queue backlogged now (liveQ=${liveQ})`
974
+ };
975
+ }
976
+ if (liveQ != null && liveQ <= 2 && decodeCallsDelta != null && decodeCallsDelta <= 1) {
977
+ return {
978
+ verdict: "PIPELINE-STARVED",
979
+ reason: `queue empty (liveQ=${liveQ}) and decode flatlined (\u0394calls=${decodeCallsDelta}) \u2014 nothing reaching the decoder; suspect delivery/FEC/failback, not decode perf`
980
+ };
981
+ }
982
+ if (fps != null && fps < 45) {
983
+ return {
984
+ verdict: "STARVED-OR-SLOW",
985
+ reason: `low decode rate (fps=${fps}) without a queue/flatline signal to disambiguate`
986
+ };
987
+ }
988
+ return { verdict: "INDETERMINATE", reason: "no signal supports a verdict" };
989
+ }
481
990
  var TransportStallDetector = class {
482
991
  constructor(config) {
483
992
  this.config = config;
@@ -553,13 +1062,39 @@
553
1062
  }
554
1063
  async function wireStarvationDetector(args) {
555
1064
  if (!args.session || args.fecInterleaveMs <= 0 || args.fecK <= 0) return null;
1065
+ const windowMs = args.deliveryWindowMs ?? Math.ceil(args.fecInterleaveMs * 3);
1066
+ if (!Number.isFinite(windowMs) || windowMs <= 0) {
1067
+ args.warn?.(`Unable to create starvation detector for ${args.trackName}: invalid delivery window ${windowMs}`);
1068
+ return null;
1069
+ }
556
1070
  const detector = wireStallDetector({
557
1071
  session: args.session,
558
- windowMs: Math.ceil(args.fecInterleaveMs * 3),
1072
+ windowMs,
559
1073
  makeDetector: args.makeDetector
560
1074
  });
561
1075
  if (!detector) args.warn?.(`Unable to create starvation detector for ${args.trackName}`);
562
- return detector;
1076
+ if (!detector || typeof args.session.state !== "string") return detector;
1077
+ let active = false;
1078
+ return {
1079
+ update(snapshot) {
1080
+ const state = args.session.state;
1081
+ const shouldObserve = state === "multicast" || state === "amt" || state === "failing";
1082
+ if (!shouldObserve) {
1083
+ if (active) detector.reset();
1084
+ active = false;
1085
+ return;
1086
+ }
1087
+ if (!active) {
1088
+ detector.reset();
1089
+ active = true;
1090
+ }
1091
+ detector.update(snapshot);
1092
+ },
1093
+ reset() {
1094
+ active = false;
1095
+ detector.reset();
1096
+ }
1097
+ };
563
1098
  }
564
1099
 
565
1100
  // src/driad-discovery.ts
@@ -619,10 +1154,7 @@
619
1154
  if (dohRelay) {
620
1155
  return [dohRelay];
621
1156
  }
622
- return [
623
- { host: "amt-relay.m2icast.net", port: 2268, priority: 10, weight: 100, asn: 0 },
624
- { host: "amt.akamaistream.net", port: 2268, priority: 20, weight: 50, asn: 0 }
625
- ];
1157
+ return [];
626
1158
  }
627
1159
  /**
628
1160
  * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
@@ -1030,6 +1562,9 @@
1030
1562
  recordMulticastGoodput(bitrate) {
1031
1563
  return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onGoodput({ bitrate }));
1032
1564
  }
1565
+ recordMulticastHeadroom(healthy) {
1566
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onHeadroom({ healthy }));
1567
+ }
1033
1568
  recordMulticastTierPacket(packet) {
1034
1569
  return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onTierPacket(packet));
1035
1570
  }
@@ -1127,8 +1662,19 @@
1127
1662
  // src/no-modules.ts
1128
1663
  var api = {
1129
1664
  AdaptiveBitrateController,
1665
+ classifyStall,
1666
+ createMulticastSignalingReconciler,
1667
+ endpointToMulticastConfig,
1668
+ hasMulticastCatalogBaseline,
1669
+ hasUnicastMediaRenditions,
1670
+ isRecoverableMulticastSignalReadError,
1671
+ isMulticastOnlyCatalog,
1130
1672
  MulticastOrchestrator,
1131
1673
  MulticastSubscriptionPool,
1674
+ MOQT_PUBLISHER_PRIORITY,
1675
+ MOQT_SUBSCRIBER_PRIORITY,
1676
+ moqtPublisherPriority,
1677
+ moqtSubscriberPriority,
1132
1678
  TransportManager,
1133
1679
  TransportStallDetector,
1134
1680
  endpointKey,
@@ -1136,11 +1682,22 @@
1136
1682
  isUsableMulticastEndpoint,
1137
1683
  isValidMulticastGroupAddress,
1138
1684
  makeSourceSwitchHandler,
1685
+ mergeUrlMulticastPolicy,
1139
1686
  multicastEndpointKey,
1687
+ normalizeCatalogEndpoints,
1688
+ normalizeMulticastConfig,
1140
1689
  normalizeMulticastEndpoint,
1690
+ readPlayerMulticastConfig,
1141
1691
  readUrlMulticastConfig,
1692
+ toWindowMulticastSubscribeConfig,
1693
+ requiresMulticastCapability,
1142
1694
  runUnicastFallback,
1695
+ sameMulticastConfig,
1696
+ selectEndpointPacketIds,
1697
+ selectMulticastCandidate,
1143
1698
  selectMulticastTier,
1699
+ urlOverrideBlocksMulticastCandidate,
1700
+ withMulticastEndpoints,
1144
1701
  wireStarvationDetector
1145
1702
  };
1146
1703
  Object.defineProperty(globalThis, "__MmtTransport", {