@blockcast/mmt-transport 0.2.0 → 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 (98) hide show
  1. package/README.md +230 -0
  2. package/dist/.build-stamp +0 -0
  3. package/dist/abr-controller.d.ts +3 -0
  4. package/dist/abr-controller.d.ts.map +1 -1
  5. package/dist/abr-controller.js +5 -0
  6. package/dist/abr-controller.js.map +1 -1
  7. package/dist/amt-gateway.d.ts.map +1 -1
  8. package/dist/amt-gateway.js +2 -1
  9. package/dist/amt-gateway.js.map +1 -1
  10. package/dist/driad-discovery.d.ts.map +1 -1
  11. package/dist/driad-discovery.js +1 -5
  12. package/dist/driad-discovery.js.map +1 -1
  13. package/dist/endpoint-config.d.ts +50 -0
  14. package/dist/endpoint-config.d.ts.map +1 -0
  15. package/dist/endpoint-config.js +143 -0
  16. package/dist/endpoint-config.js.map +1 -0
  17. package/dist/index.d.ts +12 -4
  18. package/dist/index.d.ts.map +1 -1
  19. package/dist/index.js +11 -8
  20. package/dist/index.js.map +1 -1
  21. package/dist/mmt-transport.no-modules.js +1711 -0
  22. package/dist/mmt-transport.no-modules.js.map +7 -0
  23. package/dist/moqt-priority.d.ts +28 -0
  24. package/dist/moqt-priority.d.ts.map +1 -0
  25. package/dist/moqt-priority.js +30 -0
  26. package/dist/moqt-priority.js.map +1 -0
  27. package/dist/multicast-catalog-policy.d.ts +64 -0
  28. package/dist/multicast-catalog-policy.d.ts.map +1 -0
  29. package/dist/multicast-catalog-policy.js +377 -0
  30. package/dist/multicast-catalog-policy.js.map +1 -0
  31. package/dist/multicast-orchestrator.d.ts +60 -0
  32. package/dist/multicast-orchestrator.d.ts.map +1 -0
  33. package/dist/multicast-orchestrator.js +175 -0
  34. package/dist/multicast-orchestrator.js.map +1 -0
  35. package/dist/multicast-signaling-reconciler.d.ts +37 -0
  36. package/dist/multicast-signaling-reconciler.d.ts.map +1 -0
  37. package/dist/multicast-signaling-reconciler.js +158 -0
  38. package/dist/multicast-signaling-reconciler.js.map +1 -0
  39. package/dist/multicast-subscription-pool.d.ts +18 -0
  40. package/dist/multicast-subscription-pool.d.ts.map +1 -0
  41. package/dist/multicast-subscription-pool.js +129 -0
  42. package/dist/multicast-subscription-pool.js.map +1 -0
  43. package/dist/multicast-tier.d.ts +33 -0
  44. package/dist/multicast-tier.d.ts.map +1 -0
  45. package/dist/multicast-tier.js +39 -0
  46. package/dist/multicast-tier.js.map +1 -0
  47. package/dist/no-modules.d.ts +64 -0
  48. package/dist/no-modules.d.ts.map +1 -0
  49. package/dist/no-modules.js +60 -0
  50. package/dist/no-modules.js.map +1 -0
  51. package/dist/stall-detector.d.ts +32 -0
  52. package/dist/stall-detector.d.ts.map +1 -0
  53. package/dist/stall-detector.js +67 -0
  54. package/dist/stall-detector.js.map +1 -0
  55. package/dist/takeover.d.ts +52 -0
  56. package/dist/takeover.d.ts.map +1 -0
  57. package/dist/takeover.js +76 -0
  58. package/dist/takeover.js.map +1 -0
  59. package/dist/transport-manager.d.ts +29 -29
  60. package/dist/transport-manager.d.ts.map +1 -1
  61. package/dist/transport-manager.js +195 -149
  62. package/dist/transport-manager.js.map +1 -1
  63. package/dist/types.d.ts +65 -142
  64. package/dist/types.d.ts.map +1 -1
  65. package/dist/types.js +12 -45
  66. package/dist/types.js.map +1 -1
  67. package/dist/unicast-fallback.d.ts +36 -0
  68. package/dist/unicast-fallback.d.ts.map +1 -0
  69. package/dist/unicast-fallback.js +53 -0
  70. package/dist/unicast-fallback.js.map +1 -0
  71. package/package.json +12 -11
  72. package/src/abr-controller.ts +9 -0
  73. package/src/amt-gateway.ts +2 -1
  74. package/src/driad-discovery.ts +1 -5
  75. package/src/endpoint-config.ts +191 -0
  76. package/src/index.ts +118 -34
  77. package/src/moqt-priority.ts +40 -0
  78. package/src/multicast-catalog-policy.ts +468 -0
  79. package/src/multicast-orchestrator.ts +201 -0
  80. package/src/multicast-signaling-reconciler.ts +153 -0
  81. package/src/multicast-subscription-pool.ts +167 -0
  82. package/src/multicast-tier.ts +59 -0
  83. package/src/no-modules.ts +93 -0
  84. package/src/stall-detector.ts +100 -0
  85. package/src/takeover.ts +109 -0
  86. package/src/transport-manager.ts +207 -166
  87. package/src/types.ts +81 -172
  88. package/src/unicast-fallback.ts +57 -0
  89. package/dist/fec-client.d.ts +0 -442
  90. package/dist/fec-client.d.ts.map +0 -1
  91. package/dist/fec-client.js +0 -784
  92. package/dist/fec-client.js.map +0 -1
  93. package/dist/fec-client.test.d.ts +0 -8
  94. package/dist/fec-client.test.d.ts.map +0 -1
  95. package/dist/fec-client.test.js +0 -112
  96. package/dist/fec-client.test.js.map +0 -1
  97. package/src/fec-client.test.ts +0 -140
  98. package/src/fec-client.ts +0 -1097
@@ -0,0 +1,1711 @@
1
+ "use strict";
2
+ (() => {
3
+ // src/multicast-tier.ts
4
+ function endpointKey(endpoint) {
5
+ return `${endpoint.sourceAddress ?? ""}|${endpoint.groupAddress}|${endpoint.port}`;
6
+ }
7
+ function carriesMedia(endpoint) {
8
+ return endpoint.carriesMedia !== false;
9
+ }
10
+ function selectMulticastTier(endpoints, estimate) {
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];
15
+ if (estimate === void 0) return ranked[0];
16
+ const budget = estimate * 0.8;
17
+ let selected;
18
+ for (const endpoint of ranked) {
19
+ if (endpoint.bandwidth <= budget) selected = endpoint;
20
+ }
21
+ return selected ?? ranked[0];
22
+ }
23
+
24
+ // src/abr-controller.ts
25
+ var QUALITY_LEVELS = [
26
+ { name: "240p", bitrate: 3e5, width: 426, height: 240, fps: 15 },
27
+ { name: "360p", bitrate: 5e5, width: 640, height: 360, fps: 24 },
28
+ { name: "480p", bitrate: 1e6, width: 854, height: 480, fps: 30 },
29
+ { name: "720p", bitrate: 25e5, width: 1280, height: 720, fps: 30 },
30
+ { name: "1080p", bitrate: 5e6, width: 1920, height: 1080, fps: 30 },
31
+ { name: "1440p", bitrate: 8e6, width: 2560, height: 1440, fps: 30 },
32
+ { name: "4K", bitrate: 15e6, width: 3840, height: 2160, fps: 30 }
33
+ ];
34
+ var AdaptiveBitrateController = class {
35
+ currentQualityIndex;
36
+ history = [];
37
+ historyWindow = 1e4;
38
+ // 10 second window
39
+ upgradeThreshold = 0.8;
40
+ // 80% of target bitrate sustained
41
+ downgradeThreshold = 0.5;
42
+ // 50% of target bitrate triggers downgrade
43
+ stabilityPeriod = 5e3;
44
+ // Wait 5s before upgrading
45
+ lastQualityChange = 0;
46
+ onQualityChange;
47
+ // FEC stats for effective loss rate calculation
48
+ fecStats = {
49
+ rawLossRate: 0,
50
+ effectiveLossRate: 0,
51
+ recoveryRate: 1,
52
+ fecEnabled: false
53
+ };
54
+ constructor(initialQuality) {
55
+ this.currentQualityIndex = initialQuality ? QUALITY_LEVELS.findIndex((q) => q.name === initialQuality.name) : 0;
56
+ if (this.currentQualityIndex < 0) this.currentQualityIndex = 0;
57
+ }
58
+ setCallback(callback) {
59
+ this.onQualityChange = callback;
60
+ }
61
+ getCurrentQuality() {
62
+ return QUALITY_LEVELS[this.currentQualityIndex];
63
+ }
64
+ /** Selects the multicast (S,G) tier without replacing a player's unicast ABR manager. */
65
+ selectMulticastTier(endpoints, estimate = this.getMetrics().measuredBitrate || void 0) {
66
+ return selectMulticastTier(endpoints, estimate);
67
+ }
68
+ /**
69
+ * Record network sample for bitrate adaptation
70
+ *
71
+ * @param bytesReceived - Bytes received in this sample
72
+ * @param packetsLost - Packets lost (raw, before FEC recovery)
73
+ */
74
+ recordSample(bytesReceived, packetsLost) {
75
+ const now = Date.now();
76
+ this.history.push({ timestamp: now, bytesReceived, packetsLost });
77
+ this.history = this.history.filter((s) => now - s.timestamp < this.historyWindow);
78
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
79
+ const currentQuality = this.getCurrentQuality();
80
+ const effectiveLossRate = this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate;
81
+ if (now - this.lastQualityChange < this.stabilityPeriod) {
82
+ return;
83
+ }
84
+ if (effectiveLossRate > 0.05 || measuredBitrate < currentQuality.bitrate * this.downgradeThreshold) {
85
+ this.downgrade();
86
+ return;
87
+ }
88
+ if (measuredBitrate > currentQuality.bitrate * this.upgradeThreshold && effectiveLossRate < 0.01 && this.currentQualityIndex < QUALITY_LEVELS.length - 1) {
89
+ this.upgrade();
90
+ }
91
+ }
92
+ /**
93
+ * Update FEC statistics for ABR decisions
94
+ *
95
+ * Per draft-ramadan-moq-fec-00, ABR should use the effective loss rate
96
+ * (after FEC recovery) rather than raw transport loss rate.
97
+ *
98
+ * @param stats - FEC statistics from the FEC decoder
99
+ */
100
+ setFecStats(stats) {
101
+ this.fecStats = stats;
102
+ }
103
+ /**
104
+ * Get current FEC statistics
105
+ */
106
+ getFecStats() {
107
+ return { ...this.fecStats };
108
+ }
109
+ calculateMetrics() {
110
+ if (this.history.length < 2) {
111
+ return { measuredBitrate: 0, lossRate: 0 };
112
+ }
113
+ const totalBytes = this.history.reduce((sum, s) => sum + s.bytesReceived, 0);
114
+ const totalLost = this.history.reduce((sum, s) => sum + s.packetsLost, 0);
115
+ const duration = (this.history[this.history.length - 1].timestamp - this.history[0].timestamp) / 1e3;
116
+ const measuredBitrate = duration > 0 ? totalBytes * 8 / duration : 0;
117
+ const lossRate = totalLost / (this.history.length + totalLost);
118
+ return { measuredBitrate, lossRate };
119
+ }
120
+ upgrade() {
121
+ if (this.currentQualityIndex >= QUALITY_LEVELS.length - 1) return;
122
+ this.currentQualityIndex++;
123
+ this.lastQualityChange = Date.now();
124
+ const newQuality = this.getCurrentQuality();
125
+ console.log(`[ABR] Upgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
126
+ this.onQualityChange?.(newQuality);
127
+ }
128
+ downgrade() {
129
+ if (this.currentQualityIndex <= 0) return;
130
+ this.currentQualityIndex--;
131
+ this.lastQualityChange = Date.now();
132
+ const newQuality = this.getCurrentQuality();
133
+ console.log(`[ABR] Downgrading to ${newQuality.name} (${newQuality.bitrate / 1e6}Mbps)`);
134
+ this.onQualityChange?.(newQuality);
135
+ }
136
+ /**
137
+ * Force quality level (for testing)
138
+ */
139
+ setQuality(name) {
140
+ const index = QUALITY_LEVELS.findIndex((q) => q.name === name);
141
+ if (index >= 0) {
142
+ this.currentQualityIndex = index;
143
+ this.lastQualityChange = Date.now();
144
+ this.onQualityChange?.(this.getCurrentQuality());
145
+ }
146
+ }
147
+ /**
148
+ * Get current metrics including both raw and effective loss rates
149
+ */
150
+ getMetrics() {
151
+ const { measuredBitrate, lossRate: rawLossRate } = this.calculateMetrics();
152
+ return {
153
+ measuredBitrate,
154
+ rawLossRate,
155
+ effectiveLossRate: this.fecStats.fecEnabled ? this.fecStats.effectiveLossRate : rawLossRate,
156
+ fecEnabled: this.fecStats.fecEnabled,
157
+ sampleCount: this.history.length
158
+ };
159
+ }
160
+ /**
161
+ * Reset history and start fresh
162
+ */
163
+ reset() {
164
+ this.history = [];
165
+ this.lastQualityChange = 0;
166
+ }
167
+ };
168
+
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
+ }
202
+ function isValidMulticastGroupAddress(address) {
203
+ const value = address?.trim().toLowerCase();
204
+ if (!value) return false;
205
+ if (value.startsWith("ff")) return isValidIpv6MulticastAddress(value);
206
+ const parts = value.split(".");
207
+ if (parts.length !== 4) return false;
208
+ const octets = parts.map((part) => {
209
+ if (!/^\d+$/.test(part)) return Number.NaN;
210
+ const octet = Number(part);
211
+ return Number.isInteger(octet) && octet >= 0 && octet <= 255 ? octet : Number.NaN;
212
+ });
213
+ return octets.every(Number.isInteger) && octets[0] >= 224 && octets[0] <= 239;
214
+ }
215
+ function normalizeMulticastEndpoint(endpoint) {
216
+ const groupAddress = endpoint.groupAddress.trim().toLowerCase();
217
+ const sourceAddress = endpoint.sourceAddress?.trim().toLowerCase() || void 0;
218
+ const amtRelay = endpoint.amtRelay?.trim().toLowerCase() || void 0;
219
+ if (!isValidMulticastGroupAddress(groupAddress) || !isPositivePort(endpoint.port)) return void 0;
220
+ if (endpoint.mode && !["auto", "native", "tunnel"].includes(endpoint.mode)) return void 0;
221
+ if (endpoint.amtRelayPort !== void 0 && !isPositivePort(endpoint.amtRelayPort)) return void 0;
222
+ return {
223
+ groupAddress,
224
+ ...sourceAddress ? { sourceAddress } : {},
225
+ port: endpoint.port,
226
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
227
+ ...amtRelay ? { amtRelay } : {},
228
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
229
+ };
230
+ }
231
+ function multicastEndpointKey(endpoint) {
232
+ const normalized = normalizeMulticastEndpoint(endpoint);
233
+ if (!normalized) throw new Error("Invalid multicast endpoint");
234
+ return JSON.stringify([
235
+ normalized.sourceAddress ?? "",
236
+ normalized.groupAddress,
237
+ normalized.port,
238
+ normalized.mode ?? "auto",
239
+ normalized.amtRelay ?? "",
240
+ normalized.amtRelayPort ?? ""
241
+ ]);
242
+ }
243
+ function isUsableMulticastEndpoint(endpoint) {
244
+ const port = Number(endpoint?.port);
245
+ return isValidMulticastGroupAddress(endpoint?.groupAddress) && isPositivePort(port);
246
+ }
247
+ function readUrlMulticastConfig(search = typeof location === "undefined" ? "" : location.search) {
248
+ const params = typeof search === "string" ? new URLSearchParams(search) : search;
249
+ const groupAddress = params.get("mc_group") || "";
250
+ const port = positivePort(params.get("mc_port"));
251
+ if (!groupAddress || !port) return void 0;
252
+ const amtRelay = params.get("mc_amt_relay") || params.get("amt_relay") || void 0;
253
+ const amtRelayPort = positivePort(params.get("mc_amt_relay_port") || params.get("amt_relay_port"));
254
+ const requestedMode = params.get("mc_mode");
255
+ const mode = amtRelay ? "tunnel" : multicastMode(requestedMode);
256
+ return normalizeMulticastEndpoint({
257
+ groupAddress,
258
+ sourceAddress: params.get("mc_source") || void 0,
259
+ port,
260
+ ...mode ? { mode } : {},
261
+ ...amtRelay ? { amtRelay } : {},
262
+ ...amtRelayPort ? { amtRelayPort } : {}
263
+ });
264
+ }
265
+ function isMulticastExplicitlyDisabled(search = typeof location === "undefined" ? "" : location.search) {
266
+ const params = typeof search === "string" ? new URLSearchParams(search) : search;
267
+ const multicast = params.get("multicast")?.trim().toLowerCase();
268
+ const transport = params.get("transport")?.trim().toLowerCase();
269
+ return transport === "moq-only" || ["0", "false", "no", "off"].includes(multicast || "");
270
+ }
271
+ function isValidIpv6MulticastAddress(value) {
272
+ if (!/^[0-9a-f:]+$/.test(value)) return false;
273
+ const compressed = value.includes("::");
274
+ if (value.indexOf("::") !== value.lastIndexOf("::")) return false;
275
+ const groups = value.split(":").filter(Boolean);
276
+ if (groups.length === 0 || groups.length > 8) return false;
277
+ if (!compressed && groups.length !== 8) return false;
278
+ return groups.every((group) => /^[0-9a-f]{1,4}$/.test(group));
279
+ }
280
+ function multicastMode(value) {
281
+ return value === "native" || value === "tunnel" || value === "auto" ? value : void 0;
282
+ }
283
+ function positivePort(value) {
284
+ const port = Number(value);
285
+ return isPositivePort(port) ? port : void 0;
286
+ }
287
+ function isPositivePort(port) {
288
+ return Number.isInteger(port) && port > 0 && port <= 65535;
289
+ }
290
+
291
+ // src/multicast-orchestrator.ts
292
+ var DEFAULT_DWELL_MS = 3e3;
293
+ var DEFAULT_JOIN_DEADLINE_MS = 5e3;
294
+ var MulticastOrchestrator = class {
295
+ constructor(options) {
296
+ this.options = options;
297
+ this.#dwellMs = options.dwellMs ?? DEFAULT_DWELL_MS;
298
+ this.#joinDeadlineMs = options.joinDeadlineMs ?? DEFAULT_JOIN_DEADLINE_MS;
299
+ if (!Number.isFinite(this.#dwellMs) || !Number.isFinite(this.#joinDeadlineMs) || this.#dwellMs <= 0 || this.#joinDeadlineMs <= 0) {
300
+ throw new Error("Multicast dwell and join deadline must be positive");
301
+ }
302
+ }
303
+ #state = "stable";
304
+ #current;
305
+ #target;
306
+ #estimate;
307
+ #favored;
308
+ #joinStartedAt = 0;
309
+ #lastCommittedTimestamp = Number.NEGATIVE_INFINITY;
310
+ #dwellMs;
311
+ #joinDeadlineMs;
312
+ get state() {
313
+ return this.#state;
314
+ }
315
+ get current() {
316
+ return this.#current;
317
+ }
318
+ get target() {
319
+ return this.#target;
320
+ }
321
+ get estimate() {
322
+ return this.#estimate;
323
+ }
324
+ start() {
325
+ this.#current ??= this.options.initialEndpoint ?? selectMulticastTier(this.options.endpoints, void 0);
326
+ return this.#current;
327
+ }
328
+ onGoodput(sample) {
329
+ const bitrate = sample.bitrate;
330
+ if (!this.#current || this.options.adaptive === false) return void 0;
331
+ if (this.#state === "joining") return this.poll();
332
+ if (bitrate === void 0 || !Number.isFinite(bitrate)) return void 0;
333
+ this.#estimate = bitrate;
334
+ const desired = selectMulticastTier(this.options.endpoints, bitrate);
335
+ if (!desired) return void 0;
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);
374
+ if (desiredKey === endpointKey(this.#current)) {
375
+ this.#favored = void 0;
376
+ return void 0;
377
+ }
378
+ const now = this.#now();
379
+ if (!this.#favored || this.#favored.key !== desiredKey) {
380
+ this.#favored = { key: desiredKey, since: now, source: "headroom" };
381
+ return void 0;
382
+ }
383
+ if (now - this.#favored.since < this.#dwellMs) return void 0;
384
+ this.#state = "joining";
385
+ this.#target = desired;
386
+ this.#joinStartedAt = now;
387
+ this.#favored = void 0;
388
+ return { kind: "join-target", current: this.#current, target: desired };
389
+ }
390
+ onTierPacket(packet) {
391
+ if (!this.#current) return void 0;
392
+ if (packet.endpointKey === endpointKey(this.#current) && Number.isFinite(packet.timestamp)) {
393
+ this.#lastCommittedTimestamp = Math.max(this.#lastCommittedTimestamp, packet.timestamp);
394
+ }
395
+ if (this.#state !== "joining" || !this.#target) return void 0;
396
+ const expired = this.poll();
397
+ if (expired) return expired;
398
+ if (packet.endpointKey !== endpointKey(this.#target) || !packet.keyframe || !packet.hasValidCodecConfig || !Number.isFinite(packet.timestamp) || packet.timestamp < this.#lastCommittedTimestamp) return void 0;
399
+ const command = {
400
+ kind: "commit-swap",
401
+ target: this.#target,
402
+ old: this.#current
403
+ };
404
+ this.#lastCommittedTimestamp = packet.timestamp;
405
+ this.#current = this.#target;
406
+ this.#target = void 0;
407
+ this.#state = "stable";
408
+ return command;
409
+ }
410
+ poll() {
411
+ if (this.#state !== "joining" || !this.#target || !this.#current) return void 0;
412
+ if (this.#now() - this.#joinStartedAt < this.#joinDeadlineMs) return void 0;
413
+ return this.cancel();
414
+ }
415
+ cancel() {
416
+ if (this.#state !== "joining" || !this.#target || !this.#current) return void 0;
417
+ const command = {
418
+ kind: "abandon-join",
419
+ current: this.#current,
420
+ target: this.#target
421
+ };
422
+ this.#target = void 0;
423
+ this.#state = "stable";
424
+ return command;
425
+ }
426
+ #now() {
427
+ const now = this.options.now();
428
+ if (!Number.isFinite(now)) throw new Error("Multicast orchestrator clock must be finite");
429
+ return now;
430
+ }
431
+ };
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
+
817
+ // src/multicast-subscription-pool.ts
818
+ var MulticastSubscriptionPool = class {
819
+ #entries = /* @__PURE__ */ new Map();
820
+ #gatewayIds = /* @__PURE__ */ new WeakMap();
821
+ #nextGatewayId = 1;
822
+ async acquire(gateway, config, consumer) {
823
+ const endpoint = normalizeMulticastEndpoint({
824
+ groupAddress: config.group,
825
+ sourceAddress: config.source,
826
+ port: config.port,
827
+ mode: config.mode,
828
+ amtRelay: config.amtRelay,
829
+ amtRelayPort: config.amtRelayPort
830
+ });
831
+ if (!endpoint) throw new Error("Invalid multicast endpoint");
832
+ if (typeof gateway.subscribe !== "function") throw new Error("window.multicast.subscribe unavailable");
833
+ const key = multicastEndpointKey(endpoint);
834
+ const internalKey = `${this.#gatewayId(gateway)}|${key}`;
835
+ let record = this.#entries.get(internalKey);
836
+ if (!record) {
837
+ record = { claims: 0, entry: Promise.resolve(null) };
838
+ const createdRecord = record;
839
+ record.entry = this.#createEntry(gateway, endpoint, (entry2) => {
840
+ if (this.#entries.get(internalKey) === createdRecord) this.#entries.delete(internalKey);
841
+ this.#detach(entry2);
842
+ }).catch((error) => {
843
+ if (this.#entries.get(internalKey) === createdRecord) this.#entries.delete(internalKey);
844
+ throw error;
845
+ });
846
+ this.#entries.set(internalKey, record);
847
+ }
848
+ record.claims++;
849
+ let entry;
850
+ try {
851
+ entry = await record.entry;
852
+ } catch (error) {
853
+ record.claims--;
854
+ throw error;
855
+ }
856
+ if (entry.closed) {
857
+ record.claims--;
858
+ return this.acquire(gateway, config, consumer);
859
+ }
860
+ const token = Symbol(key);
861
+ entry.consumers.set(token, consumer);
862
+ let released = false;
863
+ return {
864
+ key,
865
+ release: async () => {
866
+ if (released) return;
867
+ released = true;
868
+ entry.consumers.delete(token);
869
+ record.claims--;
870
+ if (record.claims > 0) return;
871
+ if (this.#entries.get(internalKey) === record) this.#entries.delete(internalKey);
872
+ this.#detach(entry);
873
+ if (!entry.closed) await entry.subscription.unsubscribe();
874
+ }
875
+ };
876
+ }
877
+ get size() {
878
+ return this.#entries.size;
879
+ }
880
+ async #createEntry(gateway, endpoint, onClosed) {
881
+ const subscription = await gateway.subscribe(toWindowMulticastSubscribeConfig({
882
+ group: endpoint.groupAddress,
883
+ ...endpoint.sourceAddress ? { source: endpoint.sourceAddress } : {},
884
+ port: endpoint.port,
885
+ ...endpoint.mode ? { mode: endpoint.mode } : {},
886
+ ...endpoint.amtRelay ? { amtRelay: endpoint.amtRelay } : {},
887
+ ...endpoint.amtRelayPort ? { amtRelayPort: endpoint.amtRelayPort } : {}
888
+ }));
889
+ const consumers = /* @__PURE__ */ new Map();
890
+ let entry;
891
+ const bytesListener = (event) => {
892
+ this.#dispatch(consumers, (consumer) => consumer.onBytes(event.detail));
893
+ };
894
+ const stateListener = (event) => {
895
+ this.#dispatch(consumers, (consumer) => consumer.onState?.(event.detail));
896
+ if (event.detail === "closed" && !entry.closed) {
897
+ entry.closed = true;
898
+ onClosed(entry);
899
+ }
900
+ };
901
+ const errorListener = (event) => {
902
+ const error = event.detail instanceof Error ? event.detail : new Error(String(event.detail));
903
+ this.#dispatch(consumers, (consumer) => consumer.onError?.(error));
904
+ };
905
+ entry = { subscription, consumers, bytesListener, stateListener, errorListener, closed: false };
906
+ subscription.addEventListener("bytes", bytesListener);
907
+ subscription.addEventListener("state", stateListener);
908
+ subscription.addEventListener("error", errorListener);
909
+ return entry;
910
+ }
911
+ #gatewayId(gateway) {
912
+ const object = gateway;
913
+ let id = this.#gatewayIds.get(object);
914
+ if (!id) {
915
+ id = this.#nextGatewayId++;
916
+ this.#gatewayIds.set(object, id);
917
+ }
918
+ return id;
919
+ }
920
+ #detach(entry) {
921
+ entry.subscription.removeEventListener("bytes", entry.bytesListener);
922
+ entry.subscription.removeEventListener("state", entry.stateListener);
923
+ entry.subscription.removeEventListener("error", entry.errorListener);
924
+ }
925
+ #dispatch(consumers, callback) {
926
+ for (const consumer of consumers.values()) {
927
+ try {
928
+ callback(consumer);
929
+ } catch (error) {
930
+ console.error("[Transport] multicast consumer callback failed", error);
931
+ }
932
+ }
933
+ }
934
+ };
935
+ var multicastSubscriptionPool = new MulticastSubscriptionPool();
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
+
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
+ }
990
+ var TransportStallDetector = class {
991
+ constructor(config) {
992
+ this.config = config;
993
+ if (config.windowMs <= 0) throw new Error("Stall window must be positive and catalog-derived");
994
+ this.#now = config.now ?? Date.now;
995
+ }
996
+ #last = null;
997
+ #lastSampleAt = 0;
998
+ #starvedSince = null;
999
+ #latched = false;
1000
+ #now;
1001
+ get isStarved() {
1002
+ return this.#latched;
1003
+ }
1004
+ update(snapshot) {
1005
+ const previous = this.#last;
1006
+ const previousAt = this.#lastSampleAt;
1007
+ const now = this.#now();
1008
+ this.#last = { ...snapshot };
1009
+ this.#lastSampleAt = now;
1010
+ if (!previous) return;
1011
+ const blockDelta = snapshot.blocksComplete - previous.blocksComplete + snapshot.blocksRecovered - previous.blocksRecovered;
1012
+ const mediaDelta = (snapshot.mediaFrames ?? 0) - (previous.mediaFrames ?? 0);
1013
+ if (blockDelta <= 0 && mediaDelta <= 0) {
1014
+ this.#starvedSince ??= previousAt;
1015
+ if (!this.#latched && now - this.#starvedSince >= this.config.windowMs) {
1016
+ this.#latched = true;
1017
+ this.config.onStarvation();
1018
+ }
1019
+ return;
1020
+ }
1021
+ this.#starvedSince = null;
1022
+ if (this.#latched) {
1023
+ this.#latched = false;
1024
+ this.config.onRecovery();
1025
+ }
1026
+ }
1027
+ reset() {
1028
+ this.#last = null;
1029
+ this.#starvedSince = null;
1030
+ this.#latched = false;
1031
+ }
1032
+ };
1033
+
1034
+ // src/takeover.ts
1035
+ function makeSourceSwitchHandler(options) {
1036
+ const log = options.log ?? console.log;
1037
+ const warn = options.warn ?? console.warn;
1038
+ return async (source) => {
1039
+ if (source !== "multicast") return;
1040
+ if (!options.multicastBridgeAvailable) {
1041
+ warn("[MoqWatch] MediaRouter requested multicast without bridge; keeping MoQ active");
1042
+ return;
1043
+ }
1044
+ const sessions = await options.sessionsReady;
1045
+ if (!sessions) {
1046
+ warn("[MoqWatch] SessionManager unavailable; aborting multicast takeover, staying on MoQ");
1047
+ options.onAbortTakeover?.();
1048
+ return;
1049
+ }
1050
+ log("[MoqWatch] MediaRouter -> multicast; activating via SessionManager");
1051
+ sessions.activateMulticast();
1052
+ options.onMulticastConfirmed?.();
1053
+ };
1054
+ }
1055
+ function wireStallDetector(args) {
1056
+ if (!args.session || args.windowMs <= 0) return null;
1057
+ return args.makeDetector({
1058
+ windowMs: args.windowMs,
1059
+ onStarvation: () => args.session.lossDetected(),
1060
+ onRecovery: () => args.session.lossRecovered()
1061
+ });
1062
+ }
1063
+ async function wireStarvationDetector(args) {
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
+ }
1070
+ const detector = wireStallDetector({
1071
+ session: args.session,
1072
+ windowMs,
1073
+ makeDetector: args.makeDetector
1074
+ });
1075
+ if (!detector) args.warn?.(`Unable to create starvation detector for ${args.trackName}`);
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
+ };
1098
+ }
1099
+
1100
+ // src/driad-discovery.ts
1101
+ var DRIADDiscovery = class {
1102
+ cache = /* @__PURE__ */ new Map();
1103
+ cacheExpiry = 3e5;
1104
+ // 5 minutes
1105
+ /**
1106
+ * Discover AMT relays for a multicast source address (RFC 8777)
1107
+ *
1108
+ * @param source - The multicast source IP address (NOT the group!)
1109
+ * @returns Array of discovered AMT relays that can tunnel traffic from this source
1110
+ */
1111
+ async discoverRelays(source) {
1112
+ const cached = this.cache.get(source);
1113
+ if (cached) {
1114
+ return cached;
1115
+ }
1116
+ try {
1117
+ const reversedSource = source.split(".").reverse().join(".");
1118
+ const queryDomain = `${reversedSource}.amt.in-addr.arpa`;
1119
+ console.log(`[DRIAD] Discovering relays for source ${source} via ${queryDomain}`);
1120
+ const relays = await this.queryDRIADProxy(source);
1121
+ if (relays.length > 0) {
1122
+ this.cache.set(source, relays);
1123
+ setTimeout(() => this.cache.delete(source), this.cacheExpiry);
1124
+ }
1125
+ return relays;
1126
+ } catch (error) {
1127
+ console.warn(`[DRIAD] Discovery failed for source ${source}:`, error);
1128
+ return [];
1129
+ }
1130
+ }
1131
+ /**
1132
+ * Query DRIAD proxy service (browser-compatible)
1133
+ */
1134
+ async queryDRIADProxy(source) {
1135
+ const proxyEndpoints = [
1136
+ "https://driad.amt.net/api/v1/relays",
1137
+ "https://multicast-gateway.cloudflare.com/driad"
1138
+ ];
1139
+ for (const endpoint of proxyEndpoints) {
1140
+ try {
1141
+ const response = await fetch(`${endpoint}?source=${encodeURIComponent(source)}`, {
1142
+ method: "GET",
1143
+ headers: { Accept: "application/json" },
1144
+ signal: AbortSignal.timeout(5e3)
1145
+ });
1146
+ if (response.ok) {
1147
+ const data = await response.json();
1148
+ return data.relays || [];
1149
+ }
1150
+ } catch {
1151
+ }
1152
+ }
1153
+ const dohRelay = await this.queryDNSOverHTTPS(source);
1154
+ if (dohRelay) {
1155
+ return [dohRelay];
1156
+ }
1157
+ return [];
1158
+ }
1159
+ /**
1160
+ * Query DNS-over-HTTPS for DRIAD relay based on source address (RFC 8777)
1161
+ */
1162
+ async queryDNSOverHTTPS(source) {
1163
+ try {
1164
+ const reversedSource = source.split(".").reverse().join(".");
1165
+ const queryName = `${reversedSource}.amt.in-addr.arpa`;
1166
+ const dohUrl = `https://cloudflare-dns.com/dns-query?name=${queryName}&type=A`;
1167
+ const response = await fetch(dohUrl, {
1168
+ headers: { Accept: "application/dns-json" },
1169
+ signal: AbortSignal.timeout(3e3)
1170
+ });
1171
+ if (!response.ok) {
1172
+ return null;
1173
+ }
1174
+ const result = await response.json();
1175
+ if (result.Answer && result.Answer.length > 0) {
1176
+ return {
1177
+ host: result.Answer[0].data,
1178
+ port: 2268,
1179
+ priority: 10,
1180
+ weight: 100,
1181
+ asn: 0
1182
+ };
1183
+ }
1184
+ return null;
1185
+ } catch (error) {
1186
+ console.warn("[DRIAD] DNS-over-HTTPS query failed:", error);
1187
+ return null;
1188
+ }
1189
+ }
1190
+ /**
1191
+ * Select best relay based on RTT measurements
1192
+ */
1193
+ async selectBestRelay(relays) {
1194
+ if (relays.length === 0) return null;
1195
+ const measured = await Promise.all(
1196
+ relays.map(async (relay) => {
1197
+ const rtt = await this.measureRTT(relay.host, relay.port);
1198
+ return { ...relay, rtt };
1199
+ })
1200
+ );
1201
+ measured.sort((a, b) => {
1202
+ if (a.priority !== b.priority) return a.priority - b.priority;
1203
+ return (a.rtt || Infinity) - (b.rtt || Infinity);
1204
+ });
1205
+ console.log(`[DRIAD] Selected relay: ${measured[0].host} (RTT: ${measured[0].rtt}ms)`);
1206
+ return measured[0];
1207
+ }
1208
+ async measureRTT(host, _port) {
1209
+ const start = performance.now();
1210
+ try {
1211
+ await fetch(`https://${host}/health`, {
1212
+ method: "HEAD",
1213
+ signal: AbortSignal.timeout(2e3),
1214
+ mode: "no-cors"
1215
+ });
1216
+ return performance.now() - start;
1217
+ } catch {
1218
+ return Infinity;
1219
+ }
1220
+ }
1221
+ /**
1222
+ * Clear the relay cache
1223
+ */
1224
+ clearCache() {
1225
+ this.cache.clear();
1226
+ }
1227
+ /**
1228
+ * Get cached relays for a source address
1229
+ */
1230
+ getCached(source) {
1231
+ return this.cache.get(source);
1232
+ }
1233
+ };
1234
+ var driadDiscovery = new DRIADDiscovery();
1235
+
1236
+ // src/transport-manager.ts
1237
+ var TransportManager = class {
1238
+ state = {
1239
+ mode: "disconnected",
1240
+ connected: false,
1241
+ packetsReceived: 0,
1242
+ bytesReceived: 0,
1243
+ lastPacketTime: 0
1244
+ };
1245
+ capabilities = null;
1246
+ subscription = null;
1247
+ driad = new DRIADDiscovery();
1248
+ abr;
1249
+ multicastOrchestrator = null;
1250
+ onOrchestratorCommand;
1251
+ connectionGeneration = 0;
1252
+ onPacket;
1253
+ onError;
1254
+ onStateChange;
1255
+ constructor() {
1256
+ this.abr = new AdaptiveBitrateController();
1257
+ }
1258
+ getWindow() {
1259
+ return typeof window === "undefined" ? void 0 : window;
1260
+ }
1261
+ getWindowMulticastGateway() {
1262
+ return this.getWindow()?.multicast;
1263
+ }
1264
+ async getGatewayCapabilities(gateway) {
1265
+ if (!gateway?.capabilities) return void 0;
1266
+ try {
1267
+ return typeof gateway.capabilities === "function" ? await gateway.capabilities() : gateway.capabilities;
1268
+ } catch (error) {
1269
+ console.warn("[Transport] window.multicast capabilities failed:", error);
1270
+ return void 0;
1271
+ }
1272
+ }
1273
+ async gatewaySupportsBytes(gateway) {
1274
+ if (typeof gateway?.subscribe !== "function") return false;
1275
+ if (!gateway.capabilities) return true;
1276
+ const capabilities = await this.getGatewayCapabilities(gateway);
1277
+ if (!capabilities) return false;
1278
+ const consumeModes = capabilities.consumeModes;
1279
+ return !consumeModes || consumeModes.includes("bytes");
1280
+ }
1281
+ /**
1282
+ * Detect available transport capabilities
1283
+ */
1284
+ async detectCapabilities() {
1285
+ if (this.capabilities) return this.capabilities;
1286
+ const gateway = this.getWindowMulticastGateway();
1287
+ const hasGatewayBytes = await this.gatewaySupportsBytes(gateway);
1288
+ const win = this.getWindow();
1289
+ this.capabilities = {
1290
+ nativeSSM: hasGatewayBytes,
1291
+ nativeIGMP: hasGatewayBytes,
1292
+ directSockets: typeof win?.UDPSocket !== "undefined",
1293
+ amt: false,
1294
+ driad: true,
1295
+ // DRIAD uses HTTP proxy, always available
1296
+ fecDecode: false
1297
+ };
1298
+ console.log("[Transport] Capabilities:", this.capabilities);
1299
+ return this.capabilities;
1300
+ }
1301
+ /**
1302
+ * Connect using best available transport
1303
+ *
1304
+ * Promotion hierarchy:
1305
+ * 1. window.multicast gateway bytes
1306
+ * 2. AMT proxy (specified or discovered via DRIAD)
1307
+ * 3. MOQ WebTransport (final fallback)
1308
+ */
1309
+ async connect(config) {
1310
+ const generation = ++this.connectionGeneration;
1311
+ this.subscription?.close();
1312
+ this.subscription = null;
1313
+ this.state = {
1314
+ mode: "disconnected",
1315
+ connected: false,
1316
+ packetsReceived: 0,
1317
+ bytesReceived: 0,
1318
+ lastPacketTime: 0
1319
+ };
1320
+ this.onStateChange?.(this.state);
1321
+ const endpoint = normalizeMulticastEndpoint({
1322
+ groupAddress: config.group,
1323
+ sourceAddress: config.source,
1324
+ port: config.port,
1325
+ mode: config.mode,
1326
+ amtRelay: config.amtRelay,
1327
+ amtRelayPort: config.amtRelayPort
1328
+ });
1329
+ if (!endpoint) {
1330
+ const error = new Error("Invalid multicast endpoint configuration");
1331
+ this.onError?.(error);
1332
+ return false;
1333
+ }
1334
+ config = {
1335
+ ...config,
1336
+ group: endpoint.groupAddress,
1337
+ source: endpoint.sourceAddress ?? "",
1338
+ mode: endpoint.mode,
1339
+ amtRelay: endpoint.amtRelay,
1340
+ amtRelayPort: endpoint.amtRelayPort
1341
+ };
1342
+ const caps = await this.detectCapabilities();
1343
+ if (generation !== this.connectionGeneration) return false;
1344
+ if (config.initialQuality) {
1345
+ this.abr = new AdaptiveBitrateController(config.initialQuality);
1346
+ }
1347
+ this.abr.setCallback((quality) => {
1348
+ this.state.quality = quality;
1349
+ this.subscription?.onqualitychange?.(quality);
1350
+ this.onStateChange?.(this.state);
1351
+ });
1352
+ let connected = false;
1353
+ if (caps.nativeSSM || caps.nativeIGMP) {
1354
+ console.log("[Transport] Attempting window.multicast...");
1355
+ connected = await this.connectWindowMulticast(config, generation);
1356
+ if (connected) {
1357
+ if (generation !== this.connectionGeneration) return false;
1358
+ this.state.mode = "multicast";
1359
+ return true;
1360
+ }
1361
+ }
1362
+ if (!connected) {
1363
+ console.log("[Transport] Attempting AMT tunnel...");
1364
+ connected = await this.connectAmt(config, generation);
1365
+ if (connected) {
1366
+ if (generation !== this.connectionGeneration) return false;
1367
+ this.state.mode = "amt";
1368
+ return true;
1369
+ }
1370
+ }
1371
+ console.log("[Transport] All multicast transports failed, falling back to MOQ");
1372
+ return false;
1373
+ }
1374
+ /**
1375
+ * Connect via the lowercase window.multicast bytes gateway.
1376
+ */
1377
+ async connectWindowMulticast(config, generation) {
1378
+ try {
1379
+ const gateway = this.getWindowMulticastGateway();
1380
+ if (typeof gateway?.subscribe !== "function") return false;
1381
+ const lease = await multicastSubscriptionPool.acquire(gateway, config, {
1382
+ onBytes: (data) => {
1383
+ if (generation === this.connectionGeneration) this.handlePacket(data);
1384
+ },
1385
+ onState: (state) => {
1386
+ if (generation !== this.connectionGeneration) return;
1387
+ this.state.connected = state !== "closed";
1388
+ this.onStateChange?.(this.state);
1389
+ },
1390
+ onError: (error) => {
1391
+ if (generation !== this.connectionGeneration) return;
1392
+ console.error("[Transport] window.multicast error:", error);
1393
+ this.onError?.(error);
1394
+ }
1395
+ });
1396
+ if (generation !== this.connectionGeneration) {
1397
+ await lease.release();
1398
+ return false;
1399
+ }
1400
+ this.subscription = {
1401
+ id: lease.key,
1402
+ config,
1403
+ close: () => {
1404
+ void lease.release();
1405
+ }
1406
+ };
1407
+ this.state = {
1408
+ mode: "multicast",
1409
+ connected: true,
1410
+ group: config.group,
1411
+ source: config.source,
1412
+ quality: this.abr.getCurrentQuality(),
1413
+ packetsReceived: 0,
1414
+ bytesReceived: 0,
1415
+ lastPacketTime: 0
1416
+ };
1417
+ console.log(`[Transport] Connected via window.multicast: (${config.source}, ${config.group})`);
1418
+ this.onStateChange?.(this.state);
1419
+ return true;
1420
+ } catch (error) {
1421
+ console.warn("[Transport] window.multicast failed:", error);
1422
+ return false;
1423
+ }
1424
+ }
1425
+ /**
1426
+ * Connect via AMT proxy (with optional DRIAD discovery)
1427
+ */
1428
+ async connectAmt(config, generation) {
1429
+ try {
1430
+ let amtRelay = config.amtRelay;
1431
+ if (!amtRelay && config.driadEnabled !== false && config.source) {
1432
+ console.log(`[Transport] Discovering AMT relay via DRIAD for source ${config.source}...`);
1433
+ const relays = await this.driad.discoverRelays(config.source);
1434
+ if (generation !== this.connectionGeneration) return false;
1435
+ const bestRelay = await this.driad.selectBestRelay(relays);
1436
+ if (generation !== this.connectionGeneration) return false;
1437
+ if (bestRelay) {
1438
+ amtRelay = bestRelay.host;
1439
+ this.state.amtRelay = amtRelay;
1440
+ }
1441
+ }
1442
+ if (!amtRelay) {
1443
+ console.warn("[Transport] No AMT relay available (DRIAD requires source address for SSM)");
1444
+ return false;
1445
+ }
1446
+ return await this.connectAmtProxy(config, amtRelay, generation);
1447
+ } catch (error) {
1448
+ console.warn("[Transport] AMT connection failed:", error);
1449
+ return false;
1450
+ }
1451
+ }
1452
+ /**
1453
+ * Connect via WebSocket-based AMT proxy (browser fallback)
1454
+ */
1455
+ async connectAmtProxy(config, amtRelay, generation) {
1456
+ try {
1457
+ const relayHost = amtRelay.includes(":") && !amtRelay.startsWith("[") ? `[${amtRelay}]` : amtRelay;
1458
+ const relayAuthority = config.amtRelayPort ? `${relayHost}:${config.amtRelayPort}` : relayHost;
1459
+ const wsUrl = new URL(`wss://${relayAuthority}/amt-proxy`);
1460
+ wsUrl.searchParams.set("group", config.group);
1461
+ wsUrl.searchParams.set("source", config.source || "");
1462
+ wsUrl.searchParams.set("port", String(config.port));
1463
+ const ws = new WebSocket(wsUrl);
1464
+ return new Promise((resolve, reject) => {
1465
+ ws.binaryType = "arraybuffer";
1466
+ const timeout = setTimeout(() => {
1467
+ ws.close();
1468
+ reject(new Error("AMT proxy connection timeout"));
1469
+ }, 1e4);
1470
+ ws.onopen = () => {
1471
+ clearTimeout(timeout);
1472
+ if (generation !== this.connectionGeneration) {
1473
+ ws.close();
1474
+ resolve(false);
1475
+ return;
1476
+ }
1477
+ console.log(`[Transport] Connected to AMT proxy: ${amtRelay}`);
1478
+ this.subscription = {
1479
+ id: `amt-proxy-${Date.now()}`,
1480
+ config,
1481
+ close: () => ws.close()
1482
+ };
1483
+ this.state = {
1484
+ mode: "amt",
1485
+ connected: true,
1486
+ group: config.group,
1487
+ source: config.source,
1488
+ amtRelay,
1489
+ quality: this.abr.getCurrentQuality(),
1490
+ packetsReceived: 0,
1491
+ bytesReceived: 0,
1492
+ lastPacketTime: 0
1493
+ };
1494
+ this.onStateChange?.(this.state);
1495
+ resolve(true);
1496
+ };
1497
+ ws.onmessage = (event) => {
1498
+ if (generation === this.connectionGeneration && event.data instanceof ArrayBuffer) {
1499
+ this.handlePacket(event.data);
1500
+ }
1501
+ };
1502
+ ws.onerror = (error) => {
1503
+ clearTimeout(timeout);
1504
+ if (generation !== this.connectionGeneration) {
1505
+ resolve(false);
1506
+ return;
1507
+ }
1508
+ console.error("[Transport] AMT proxy error:", error);
1509
+ reject(error);
1510
+ };
1511
+ ws.onclose = () => {
1512
+ clearTimeout(timeout);
1513
+ if (generation !== this.connectionGeneration) {
1514
+ resolve(false);
1515
+ return;
1516
+ }
1517
+ this.state.connected = false;
1518
+ this.onStateChange?.(this.state);
1519
+ resolve(false);
1520
+ };
1521
+ });
1522
+ } catch (error) {
1523
+ console.warn("[Transport] AMT proxy failed:", error);
1524
+ return false;
1525
+ }
1526
+ }
1527
+ /**
1528
+ * Handle received packet
1529
+ */
1530
+ handlePacket(data) {
1531
+ this.state.packetsReceived++;
1532
+ this.state.bytesReceived += data.byteLength;
1533
+ this.state.lastPacketTime = Date.now();
1534
+ this.abr.recordSample(data.byteLength, 0);
1535
+ this.onPacket?.(data);
1536
+ }
1537
+ /**
1538
+ * Get current transport state
1539
+ */
1540
+ getState() {
1541
+ return { ...this.state };
1542
+ }
1543
+ /**
1544
+ * Get current quality level
1545
+ */
1546
+ getQuality() {
1547
+ return this.abr.getCurrentQuality();
1548
+ }
1549
+ /**
1550
+ * Force quality level
1551
+ */
1552
+ setQuality(name) {
1553
+ this.abr.setQuality(name);
1554
+ }
1555
+ /** Configures multicast-only ABR while leaving the caller's MoQ ABR untouched. */
1556
+ configureMulticastTiers(options, onCommand) {
1557
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
1558
+ this.multicastOrchestrator = new MulticastOrchestrator(options);
1559
+ this.onOrchestratorCommand = onCommand;
1560
+ return this.multicastOrchestrator.start();
1561
+ }
1562
+ recordMulticastGoodput(bitrate) {
1563
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onGoodput({ bitrate }));
1564
+ }
1565
+ recordMulticastHeadroom(healthy) {
1566
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onHeadroom({ healthy }));
1567
+ }
1568
+ recordMulticastTierPacket(packet) {
1569
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.onTierPacket(packet));
1570
+ }
1571
+ pollMulticastTierSwitch() {
1572
+ return this.dispatchOrchestratorCommand(this.multicastOrchestrator?.poll());
1573
+ }
1574
+ /**
1575
+ * Set packet callback
1576
+ */
1577
+ setPacketCallback(callback) {
1578
+ this.onPacket = callback;
1579
+ }
1580
+ /**
1581
+ * Set error callback
1582
+ */
1583
+ setErrorCallback(callback) {
1584
+ this.onError = callback;
1585
+ }
1586
+ /**
1587
+ * Set state change callback
1588
+ */
1589
+ setStateCallback(callback) {
1590
+ this.onStateChange = callback;
1591
+ }
1592
+ /**
1593
+ * Disconnect
1594
+ */
1595
+ disconnect() {
1596
+ this.connectionGeneration++;
1597
+ this.subscription?.close();
1598
+ this.subscription = null;
1599
+ this.dispatchOrchestratorCommand(this.multicastOrchestrator?.cancel());
1600
+ this.multicastOrchestrator = null;
1601
+ this.onOrchestratorCommand = void 0;
1602
+ this.state = {
1603
+ mode: "disconnected",
1604
+ connected: false,
1605
+ packetsReceived: 0,
1606
+ bytesReceived: 0,
1607
+ lastPacketTime: 0
1608
+ };
1609
+ this.onStateChange?.(this.state);
1610
+ }
1611
+ dispatchOrchestratorCommand(command) {
1612
+ if (command) this.onOrchestratorCommand?.(command);
1613
+ return command;
1614
+ }
1615
+ };
1616
+ var transportManager = new TransportManager();
1617
+
1618
+ // src/unicast-fallback.ts
1619
+ function runUnicastFallback(input) {
1620
+ input.sessions.enterUnicastFallback();
1621
+ const tracks = Array.from(new Map(input.tracks.map((track) => [track.name, track])).values());
1622
+ let resolveAbort;
1623
+ const aborted = new Promise((resolve) => {
1624
+ resolveAbort = resolve;
1625
+ if (input.signal.aborted) resolve(void 0);
1626
+ });
1627
+ const onAbort = () => resolveAbort(void 0);
1628
+ if (!input.signal.aborted) input.signal.addEventListener("abort", onAbort, { once: true });
1629
+ const drainers = tracks.map(async (track) => {
1630
+ const subscription = input.broadcast.subscribe(track.name, input.priority);
1631
+ try {
1632
+ while (!input.signal.aborted) {
1633
+ const nextGroup = subscription.nextGroup();
1634
+ const group = await Promise.race([nextGroup, aborted]);
1635
+ if (!group && input.signal.aborted) void nextGroup.then((lateGroup) => lateGroup?.close());
1636
+ if (!group) break;
1637
+ try {
1638
+ while (!input.signal.aborted) {
1639
+ const frame = await Promise.race([group.readFrame(), aborted]);
1640
+ if (!frame) break;
1641
+ input.onPacket(frame);
1642
+ }
1643
+ } finally {
1644
+ group.close();
1645
+ }
1646
+ }
1647
+ } catch (error) {
1648
+ if (!input.signal.aborted) {
1649
+ if (input.onError) input.onError(track.name, error);
1650
+ else console.warn(`[unicast-fallback] drainer error on ${track.name}:`, error);
1651
+ }
1652
+ } finally {
1653
+ subscription.close();
1654
+ }
1655
+ });
1656
+ const done = Promise.all(drainers).then(() => void 0).finally(() => {
1657
+ input.signal.removeEventListener("abort", onAbort);
1658
+ });
1659
+ return { done };
1660
+ }
1661
+
1662
+ // src/no-modules.ts
1663
+ var api = {
1664
+ AdaptiveBitrateController,
1665
+ classifyStall,
1666
+ createMulticastSignalingReconciler,
1667
+ endpointToMulticastConfig,
1668
+ hasMulticastCatalogBaseline,
1669
+ hasUnicastMediaRenditions,
1670
+ isRecoverableMulticastSignalReadError,
1671
+ isMulticastOnlyCatalog,
1672
+ MulticastOrchestrator,
1673
+ MulticastSubscriptionPool,
1674
+ MOQT_PUBLISHER_PRIORITY,
1675
+ MOQT_SUBSCRIBER_PRIORITY,
1676
+ moqtPublisherPriority,
1677
+ moqtSubscriberPriority,
1678
+ TransportManager,
1679
+ TransportStallDetector,
1680
+ endpointKey,
1681
+ isMulticastExplicitlyDisabled,
1682
+ isUsableMulticastEndpoint,
1683
+ isValidMulticastGroupAddress,
1684
+ makeSourceSwitchHandler,
1685
+ mergeUrlMulticastPolicy,
1686
+ multicastEndpointKey,
1687
+ normalizeCatalogEndpoints,
1688
+ normalizeMulticastConfig,
1689
+ normalizeMulticastEndpoint,
1690
+ readPlayerMulticastConfig,
1691
+ readUrlMulticastConfig,
1692
+ toWindowMulticastSubscribeConfig,
1693
+ requiresMulticastCapability,
1694
+ runUnicastFallback,
1695
+ sameMulticastConfig,
1696
+ selectEndpointPacketIds,
1697
+ selectMulticastCandidate,
1698
+ selectMulticastTier,
1699
+ urlOverrideBlocksMulticastCandidate,
1700
+ withMulticastEndpoints,
1701
+ wireStarvationDetector
1702
+ };
1703
+ Object.defineProperty(globalThis, "__MmtTransport", {
1704
+ configurable: true,
1705
+ enumerable: false,
1706
+ writable: false,
1707
+ value: Object.freeze(api)
1708
+ });
1709
+ var no_modules_default = api;
1710
+ })();
1711
+ //# sourceMappingURL=mmt-transport.no-modules.js.map