@moq/watch 0.2.16 → 0.2.18

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 (58) hide show
  1. package/README.md +21 -9
  2. package/audio/backend.d.ts +1 -1
  3. package/audio/backend.d.ts.map +1 -1
  4. package/audio/buffer.d.ts +10 -1
  5. package/audio/buffer.d.ts.map +1 -1
  6. package/audio/decoder.d.ts +2 -1
  7. package/audio/decoder.d.ts.map +1 -1
  8. package/audio/emitter.d.ts.map +1 -1
  9. package/audio/mse.d.ts +1 -1
  10. package/audio/mse.d.ts.map +1 -1
  11. package/audio/render.d.ts +6 -1
  12. package/audio/render.d.ts.map +1 -1
  13. package/audio/ring-buffer.d.ts +2 -0
  14. package/audio/ring-buffer.d.ts.map +1 -1
  15. package/audio/shared-ring-buffer.d.ts +8 -1
  16. package/audio/shared-ring-buffer.d.ts.map +1 -1
  17. package/audio/source.d.ts.map +1 -1
  18. package/backend.d.ts +19 -18
  19. package/backend.d.ts.map +1 -1
  20. package/broadcast-oQKyLEQ1.js +1679 -0
  21. package/broadcast-oQKyLEQ1.js.map +1 -0
  22. package/broadcast.d.ts +33 -4
  23. package/broadcast.d.ts.map +1 -1
  24. package/buffered.d.ts +19 -0
  25. package/buffered.d.ts.map +1 -0
  26. package/element.d.ts +26 -4
  27. package/element.d.ts.map +1 -1
  28. package/element.js +72 -32
  29. package/element.js.map +1 -1
  30. package/index.d.ts +2 -0
  31. package/index.d.ts.map +1 -1
  32. package/index.js +7 -5
  33. package/mse.d.ts.map +1 -1
  34. package/package.json +6 -6
  35. package/support/element.d.ts.map +1 -1
  36. package/support/element.js.map +1 -1
  37. package/support/index.js.map +1 -1
  38. package/sync-D67IxmxJ.js +128 -0
  39. package/sync-D67IxmxJ.js.map +1 -0
  40. package/sync.d.ts +27 -5
  41. package/sync.d.ts.map +1 -1
  42. package/sync.test.d.ts +2 -0
  43. package/sync.test.d.ts.map +1 -0
  44. package/ui/components/latency.d.ts.map +1 -1
  45. package/ui/element.d.ts.map +1 -1
  46. package/ui/element.js +215 -178
  47. package/ui/element.js.map +1 -1
  48. package/video/backend.d.ts +1 -1
  49. package/video/backend.d.ts.map +1 -1
  50. package/video/decoder.d.ts +1 -1
  51. package/video/decoder.d.ts.map +1 -1
  52. package/video/mse.d.ts +3 -3
  53. package/video/mse.d.ts.map +1 -1
  54. package/video/renderer.d.ts +18 -0
  55. package/video/renderer.d.ts.map +1 -1
  56. package/video/source.d.ts.map +1 -1
  57. package/broadcast-CG8jZRfA.js +0 -1651
  58. package/broadcast-CG8jZRfA.js.map +0 -1
@@ -0,0 +1,1679 @@
1
+ import { t as e } from "./sync-D67IxmxJ.js";
2
+ import * as t from "@moq/net";
3
+ import { Path as n, Time as r } from "@moq/net";
4
+ import { Effect as i, Signal as a } from "@moq/signals";
5
+ import * as o from "@moq/hang/catalog";
6
+ import { u53 as s } from "@moq/hang/catalog";
7
+ import * as c from "@moq/hang/container";
8
+ import * as l from "@moq/hang/util";
9
+ import * as u from "@moq/msf";
10
+ //#region \0rolldown/runtime.js
11
+ var d = Object.defineProperty, f = (e, t) => {
12
+ let n = {};
13
+ for (var r in e) d(n, r, {
14
+ get: e[r],
15
+ enumerable: !0
16
+ });
17
+ return t || d(n, Symbol.toStringTag, { value: "Module" }), n;
18
+ };
19
+ //#endregion
20
+ //#region src/base64.ts
21
+ function p(e) {
22
+ let t = atob(e), n = new Uint8Array(t.length);
23
+ for (let e = 0; e < t.length; e++) n[e] = t.charCodeAt(e);
24
+ return n;
25
+ }
26
+ //#endregion
27
+ //#region src/audio/shared-ring-buffer.ts
28
+ var m = 0, h = 1, g = 2, _ = 3, v = 4;
29
+ function y(e, t, n, r = !1) {
30
+ if (e <= 0) throw Error("invalid channels");
31
+ if (t <= 0) throw Error("invalid capacity");
32
+ if (n <= 0) throw Error("invalid sample rate");
33
+ let i = new SharedArrayBuffer(e * t * Float32Array.BYTES_PER_ELEMENT), a = new SharedArrayBuffer(v * Int32Array.BYTES_PER_ELEMENT), o = new Int32Array(a);
34
+ return Atomics.store(o, _, 1), {
35
+ channels: e,
36
+ capacity: t,
37
+ rate: n,
38
+ samples: i,
39
+ control: a,
40
+ buffered: r
41
+ };
42
+ }
43
+ function b(e, t) {
44
+ return (e - t | 0) > 0 ? e : t;
45
+ }
46
+ function x(e, t) {
47
+ return (e % t + t) % t;
48
+ }
49
+ function S(e, t, n) {
50
+ for (;;) {
51
+ let r = Atomics.load(e, t);
52
+ if ((n - r | 0) <= 0) return r;
53
+ if (Atomics.compareExchange(e, t, r, n) === r) return n;
54
+ }
55
+ }
56
+ var C = class e {
57
+ channels;
58
+ capacity;
59
+ rate;
60
+ buffered;
61
+ init;
62
+ #e;
63
+ #t;
64
+ #n = !1;
65
+ constructor(e) {
66
+ this.channels = e.channels, this.capacity = e.capacity, this.rate = e.rate, this.buffered = e.buffered, this.init = e, this.#e = new Int32Array(e.control), this.#t = [];
67
+ for (let t = 0; t < this.channels; t++) this.#t.push(new Float32Array(e.samples, t * this.capacity * Float32Array.BYTES_PER_ELEMENT, this.capacity));
68
+ }
69
+ insert(e, t) {
70
+ if (t.length !== this.channels) throw Error("wrong number of channels");
71
+ let n = Math.round(r.Second.fromMicro(e) * this.rate), i = t[0].length, a = 0;
72
+ this.buffered && !this.#n && (Atomics.store(this.#e, h, n | 0), Atomics.store(this.#e, m, n | 0), this.#n = !0);
73
+ let o = n + i | 0, s = Atomics.load(this.#e, h), c = s - n | 0;
74
+ if (c > 0) {
75
+ if (c >= i) return;
76
+ a = c, n = n + c | 0;
77
+ }
78
+ let l = i - a;
79
+ (o - s | 0) > this.capacity && S(this.#e, h, o - this.capacity | 0);
80
+ let u = Atomics.load(this.#e, m), d = n - u | 0;
81
+ if (d > 0) {
82
+ let e = Math.min(d, this.capacity);
83
+ for (let t = 0; t < this.channels; t++) {
84
+ let n = this.#t[t];
85
+ for (let t = 0; t < e; t++) n[x(u + t | 0, this.capacity)] = 0;
86
+ }
87
+ }
88
+ for (let e = 0; e < this.channels; e++) {
89
+ let r = t[e], i = this.#t[e];
90
+ for (let e = 0; e < l; e++) i[x(n + e | 0, this.capacity)] = r[a + e];
91
+ }
92
+ Atomics.store(this.#e, m, b(Atomics.load(this.#e, m), o));
93
+ let f = Atomics.load(this.#e, h), p = Atomics.load(this.#e, m), v = Atomics.load(this.#e, g);
94
+ (p - f | 0) >= v && v > 0 && Atomics.store(this.#e, _, 0);
95
+ }
96
+ read(e) {
97
+ if (Atomics.load(this.#e, _) === 1) return 0;
98
+ let t = Atomics.load(this.#e, h), n = Atomics.load(this.#e, m), r = Atomics.load(this.#e, g), i = n - t | 0;
99
+ if (!this.buffered && r > 0 && i > r) {
100
+ let e = n - r | 0;
101
+ t = S(this.#e, h, e);
102
+ }
103
+ let a = n - t | 0, o = Math.min(a, e[0].length);
104
+ if (o <= 0) return 0;
105
+ for (let n = 0; n < this.channels; n++) {
106
+ let r = this.#t[n], i = e[n];
107
+ for (let e = 0; e < o; e++) i[e] = r[x(t + e | 0, this.capacity)];
108
+ }
109
+ return S(this.#e, h, t + o | 0), o;
110
+ }
111
+ setLatency(e) {
112
+ Atomics.store(this.#e, g, e);
113
+ }
114
+ reset() {
115
+ this.#n = !1, Atomics.store(this.#e, _, 1);
116
+ let e = Atomics.load(this.#e, m);
117
+ Atomics.store(this.#e, h, e);
118
+ }
119
+ resize(t) {
120
+ let n = new e(y(this.channels, t, this.rate, this.buffered));
121
+ n.#n = this.#n;
122
+ let r = Atomics.load(this.#e, h), i = Atomics.load(this.#e, m), a = Atomics.load(this.#e, g), o = Atomics.load(this.#e, _), s = i - r | 0, c = Math.max(0, Math.min(s, n.capacity)), l = i - c | 0;
123
+ for (let e = 0; e < this.channels; e++) {
124
+ let t = this.#t[e], r = n.#t[e];
125
+ for (let e = 0; e < c; e++) {
126
+ let i = l + e | 0;
127
+ r[x(i, n.capacity)] = t[x(i, this.capacity)];
128
+ }
129
+ }
130
+ return Atomics.store(n.#e, h, l), Atomics.store(n.#e, m, i), Atomics.store(n.#e, g, a), Atomics.store(n.#e, _, o), n;
131
+ }
132
+ get timestamp() {
133
+ let e = Atomics.load(this.#e, h);
134
+ return r.Micro.fromSecond(e / this.rate);
135
+ }
136
+ get stalled() {
137
+ return Atomics.load(this.#e, _) === 1;
138
+ }
139
+ get length() {
140
+ return Atomics.load(this.#e, m) - Atomics.load(this.#e, h) | 0;
141
+ }
142
+ }, w = class {
143
+ #e;
144
+ #t;
145
+ #n = [];
146
+ constructor(e, t) {
147
+ this.#e = e, this.#t = t;
148
+ }
149
+ setHeadroom(e) {
150
+ this.#t = e;
151
+ }
152
+ wait(e, t) {
153
+ return !this.#e || t >= (e - this.#t | 0) ? Promise.resolve() : new Promise((t) => this.#n.push({
154
+ timestamp: e,
155
+ resolve: t
156
+ }));
157
+ }
158
+ advance(e) {
159
+ this.#n.length !== 0 && (this.#n = this.#n.filter(({ timestamp: t, resolve: n }) => e < (t - this.#t | 0) ? !0 : (n(), !1)));
160
+ }
161
+ flush() {
162
+ for (let { resolve: e } of this.#n) e();
163
+ this.#n = [];
164
+ }
165
+ };
166
+ function T(e, t) {
167
+ return r.Micro.fromSecond(e / t);
168
+ }
169
+ function E() {
170
+ return !(typeof SharedArrayBuffer > "u" || typeof crossOriginIsolated < "u" && !crossOriginIsolated);
171
+ }
172
+ function ee(e, t, n, r, i = !1) {
173
+ return E() ? (console.log("[audio] using SharedArrayBuffer audio buffer"), new te(e, t, n, r, i)) : (console.log("[audio] using postMessage audio buffer (SharedArrayBuffer unavailable)"), new ne(e, t, n, r, i));
174
+ }
175
+ var te = class {
176
+ rate;
177
+ channels;
178
+ #e;
179
+ #t;
180
+ #n = new a(0);
181
+ timestamp = this.#n;
182
+ #r = new a(!0);
183
+ stalled = this.#r;
184
+ #i;
185
+ #a = new i();
186
+ constructor(e, t, n, r, i) {
187
+ this.#e = e, this.channels = t, this.rate = n;
188
+ let a = Math.max(n, r * 2);
189
+ this.#i = new w(i, T(r, n));
190
+ let o = y(t, a, n, i);
191
+ this.#t = new C(o), this.#t.setLatency(r);
192
+ let s = {
193
+ type: "init-shared",
194
+ ...o
195
+ };
196
+ e.port.postMessage(s), this.#a.interval(() => {
197
+ let e = this.#t.stalled;
198
+ this.#n.set(this.#t.timestamp), this.#r.set(e), e ? this.#i.flush() : this.#i.advance(this.#t.timestamp);
199
+ }, 50);
200
+ }
201
+ insert(e, t) {
202
+ this.#t.insert(e, t);
203
+ }
204
+ setLatency(e) {
205
+ if (this.#i.setHeadroom(T(e, this.rate)), this.#t.capacity < e * 1.5) {
206
+ let t = Math.max(this.rate, e * 2);
207
+ this.#t = this.#t.resize(t), this.#t.setLatency(e);
208
+ let n = {
209
+ type: "init-shared",
210
+ ...this.#t.init
211
+ };
212
+ this.#e.port.postMessage(n);
213
+ } else this.#t.setLatency(e);
214
+ }
215
+ reset() {
216
+ this.#t.reset(), this.#i.flush();
217
+ }
218
+ wait(e) {
219
+ return this.#t.stalled ? Promise.resolve() : this.#i.wait(e, this.#t.timestamp);
220
+ }
221
+ close() {
222
+ this.#i.flush(), this.#a.close();
223
+ }
224
+ }, ne = class {
225
+ rate;
226
+ channels;
227
+ #e;
228
+ #t = new a(0);
229
+ timestamp = this.#t;
230
+ #n = new a(!0);
231
+ stalled = this.#n;
232
+ #r;
233
+ #i = new i();
234
+ constructor(e, t, n, i, a) {
235
+ this.#e = e, this.channels = t, this.rate = n, this.#r = new w(a, T(i, n));
236
+ let o = {
237
+ type: "init-post",
238
+ channels: t,
239
+ rate: n,
240
+ latency: r.Milli.fromSecond(i / n),
241
+ buffered: a
242
+ };
243
+ e.port.postMessage(o), this.#i.event(e.port, "message", (e) => {
244
+ let t = e.data;
245
+ t?.type === "state" && (this.#t.set(t.timestamp), this.#n.set(t.stalled), t.stalled ? this.#r.flush() : this.#r.advance(t.timestamp));
246
+ }), e.port.start();
247
+ }
248
+ insert(e, t) {
249
+ let n = {
250
+ type: "data",
251
+ data: t,
252
+ timestamp: e
253
+ };
254
+ this.#e.port.postMessage(n, t.map((e) => e.buffer));
255
+ }
256
+ setLatency(e) {
257
+ this.#r.setHeadroom(T(e, this.rate));
258
+ let t = {
259
+ type: "latency",
260
+ latency: r.Milli.fromSecond(e / this.rate)
261
+ };
262
+ this.#e.port.postMessage(t);
263
+ }
264
+ reset() {
265
+ this.#e.port.postMessage({ type: "reset" }), this.#r.flush();
266
+ }
267
+ wait(e) {
268
+ return this.#n.peek() ? Promise.resolve() : this.#r.wait(e, this.#t.peek());
269
+ }
270
+ close() {
271
+ this.#r.flush(), this.#i.close();
272
+ }
273
+ }, re = new Blob(["var __defProp = Object.defineProperty;\nvar __getOwnPropNames = Object.getOwnPropertyNames;\nvar __esm = (fn, res, err) => function __init() {\n if (err) throw err[0];\n try {\n return fn && (res = (0, fn[__getOwnPropNames(fn)[0]])(fn = 0)), res;\n } catch (e) {\n throw err = [e], e;\n }\n};\nvar __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\n\n// ../net/src/path.ts\nvar init_path = __esm({\n \"../net/src/path.ts\"() {\n \"use strict\";\n }\n});\n\n// ../net/src/varint.ts\nvar MAX_U6, MAX_U14, MAX_U30, MAX_U53, MAX_U64, MAX_U62;\nvar init_varint = __esm({\n \"../net/src/varint.ts\"() {\n \"use strict\";\n MAX_U6 = 2 ** 6 - 1;\n MAX_U14 = 2 ** 14 - 1;\n MAX_U30 = 2 ** 30 - 1;\n MAX_U53 = Number.MAX_SAFE_INTEGER;\n MAX_U64 = (1n << 64n) - 1n;\n MAX_U62 = 2n ** 62n - 1n;\n }\n});\n\n// ../net/src/index.ts\ninit_path();\n\n// ../net/src/time.ts\nvar time_exports = {};\n__export(time_exports, {\n Micro: () => Micro,\n Milli: () => Milli,\n Nano: () => Nano,\n Second: () => Second\n});\nvar Nano = {\n zero: 0,\n fromMicro: (us) => us * 1e3,\n fromMilli: (ms) => ms * 1e6,\n fromSecond: (s) => s * 1e9,\n toMicro: (ns) => ns / 1e3,\n toMilli: (ns) => ns / 1e6,\n toSecond: (ns) => ns / 1e9,\n now: () => performance.now() * 1e6,\n add: (a, b) => a + b,\n sub: (a, b) => a - b,\n mul: (a, b) => a * b,\n div: (a, b) => a / b,\n max: (a, b) => Math.max(a, b),\n min: (a, b) => Math.min(a, b)\n};\nvar Micro = {\n zero: 0,\n fromNano: (ns) => ns / 1e3,\n fromMilli: (ms) => ms * 1e3,\n fromSecond: (s) => s * 1e6,\n toNano: (us) => us * 1e3,\n toMilli: (us) => us / 1e3,\n toSecond: (us) => us / 1e6,\n now: () => performance.now() * 1e3,\n add: (a, b) => a + b,\n sub: (a, b) => a - b,\n mul: (a, b) => a * b,\n div: (a, b) => a / b,\n max: (a, b) => Math.max(a, b),\n min: (a, b) => Math.min(a, b)\n};\nvar Milli = {\n zero: 0,\n fromNano: (ns) => ns / 1e6,\n fromMicro: (us) => us / 1e3,\n fromSecond: (s) => s * 1e3,\n toNano: (ms) => ms * 1e6,\n toMicro: (ms) => ms * 1e3,\n toSecond: (ms) => ms / 1e3,\n now: () => performance.now(),\n add: (a, b) => a + b,\n sub: (a, b) => a - b,\n mul: (a, b) => a * b,\n div: (a, b) => a / b,\n max: (a, b) => Math.max(a, b),\n min: (a, b) => Math.min(a, b)\n};\nvar Second = {\n zero: 0,\n fromNano: (ns) => ns / 1e9,\n fromMicro: (us) => us / 1e6,\n fromMilli: (ms) => ms / 1e3,\n toNano: (s) => s * 1e9,\n toMicro: (s) => s * 1e6,\n toMilli: (s) => s * 1e3,\n now: () => performance.now() / 1e3,\n add: (a, b) => a + b,\n sub: (a, b) => a - b,\n mul: (a, b) => a * b,\n div: (a, b) => a / b,\n max: (a, b) => Math.max(a, b),\n min: (a, b) => Math.min(a, b)\n};\n\n// ../net/src/index.ts\ninit_varint();\n\n// src/audio/ring-buffer.ts\nvar AudioRingBuffer = class {\n #buffer;\n #writeIndex = 0;\n #readIndex = 0;\n rate;\n channels;\n #stalled = true;\n // Buffered mode: anchor to the first sample, play through without skipping ahead.\n #buffered;\n // Un-stall threshold in samples (how much to buffer before playback starts).\n #latencySamples;\n // Whether the read/write indices have been anchored to the first inserted sample.\n #anchored = false;\n constructor(props) {\n if (props.channels <= 0) throw new Error(\"invalid channels\");\n if (props.rate <= 0) throw new Error(\"invalid sample rate\");\n if (props.latency <= 0) throw new Error(\"invalid latency\");\n this.#latencySamples = Math.ceil(props.rate * time_exports.Second.fromMilli(props.latency));\n if (this.#latencySamples === 0) throw new Error(\"empty buffer\");\n this.rate = props.rate;\n this.channels = props.channels;\n this.#buffered = props.buffered ?? false;\n const capacity = this.#capacityFor(this.#latencySamples);\n this.#buffer = [];\n for (let i = 0; i < this.channels; i++) {\n this.#buffer[i] = new Float32Array(capacity);\n }\n }\n #capacityFor(latencySamples) {\n return this.#buffered ? latencySamples * 2 : latencySamples;\n }\n get stalled() {\n return this.#stalled;\n }\n get timestamp() {\n return time_exports.Micro.fromSecond(this.#readIndex / this.rate);\n }\n get length() {\n return this.#writeIndex - this.#readIndex;\n }\n get capacity() {\n return this.#buffer[0]?.length;\n }\n resize(latency) {\n this.#latencySamples = Math.ceil(this.rate * time_exports.Second.fromMilli(latency));\n const newCapacity = this.#capacityFor(this.#latencySamples);\n if (newCapacity === this.capacity) return;\n if (newCapacity === 0) throw new Error(\"empty buffer\");\n const newBuffer = [];\n for (let i = 0; i < this.channels; i++) {\n newBuffer[i] = new Float32Array(newCapacity);\n }\n const samplesToKeep = Math.min(this.length, newCapacity);\n if (samplesToKeep > 0) {\n const copyStart = this.#writeIndex - samplesToKeep;\n for (let channel = 0; channel < this.channels; channel++) {\n const src = this.#buffer[channel];\n const dst = newBuffer[channel];\n for (let i = 0; i < samplesToKeep; i++) {\n const srcPos = (copyStart + i) % src.length;\n const dstPos = (copyStart + i) % dst.length;\n dst[dstPos] = src[srcPos];\n }\n }\n }\n this.#buffer = newBuffer;\n this.#readIndex = this.#writeIndex - samplesToKeep;\n if (samplesToKeep === 0) this.#stalled = true;\n }\n write(timestamp, data) {\n if (data.length !== this.channels) throw new Error(\"wrong number of channels\");\n let start = Math.round(time_exports.Second.fromMicro(timestamp) * this.rate);\n let samples = data[0].length;\n if (this.#buffered && !this.#anchored) {\n this.#readIndex = start;\n this.#writeIndex = start;\n this.#anchored = true;\n }\n let offset = this.#readIndex - start;\n if (offset > samples) {\n return;\n } else if (offset > 0) {\n samples -= offset;\n start += offset;\n } else {\n offset = 0;\n }\n const end = start + samples;\n const overflow = end - this.#readIndex - this.#buffer[0].length;\n if (overflow >= 0) {\n this.#stalled = false;\n this.#readIndex += overflow;\n }\n if (start > this.#writeIndex) {\n const gapSize = Math.min(start - this.#writeIndex, this.#buffer[0].length);\n if (gapSize === 1) {\n console.warn(\"floating point inaccuracy detected\");\n }\n for (let channel = 0; channel < this.channels; channel++) {\n const dst = this.#buffer[channel];\n for (let i = 0; i < gapSize; i++) {\n const writePos = (this.#writeIndex + i) % dst.length;\n dst[writePos] = 0;\n }\n }\n }\n for (let channel = 0; channel < this.channels; channel++) {\n let src = data[channel];\n src = src.subarray(src.length - samples);\n const dst = this.#buffer[channel];\n if (src.length !== samples) throw new Error(\"mismatching number of samples\");\n for (let i = 0; i < samples; i++) {\n const writePos = (start + i) % dst.length;\n dst[writePos] = src[i];\n }\n }\n if (end > this.#writeIndex) {\n this.#writeIndex = end;\n }\n if (this.#buffered && this.length >= this.#latencySamples) {\n this.#stalled = false;\n }\n }\n // Flush all buffered samples and re-stall, ready to anchor the next utterance.\n reset() {\n this.#readIndex = 0;\n this.#writeIndex = 0;\n this.#stalled = true;\n this.#anchored = false;\n }\n read(output) {\n if (output.length !== this.channels) throw new Error(\"wrong number of channels\");\n if (this.#stalled) return 0;\n const samples = Math.min(this.#writeIndex - this.#readIndex, output[0].length);\n if (samples === 0) return 0;\n for (let channel = 0; channel < this.channels; channel++) {\n const dst = output[channel];\n const src = this.#buffer[channel];\n if (dst.length !== output[0].length) throw new Error(\"mismatching number of samples\");\n for (let i = 0; i < samples; i++) {\n const readPos = (this.#readIndex + i) % src.length;\n dst[i] = src[readPos];\n }\n }\n this.#readIndex += samples;\n return samples;\n }\n};\n\n// src/audio/shared-ring-buffer.ts\nvar WRITE = 0;\nvar READ = 1;\nvar LATENCY = 2;\nvar STALLED = 3;\nvar CONTROL_SLOTS = 4;\nfunction allocSharedRingBuffer(channels, capacity, rate, buffered = false) {\n if (channels <= 0) throw new Error(\"invalid channels\");\n if (capacity <= 0) throw new Error(\"invalid capacity\");\n if (rate <= 0) throw new Error(\"invalid sample rate\");\n const samples = new SharedArrayBuffer(channels * capacity * Float32Array.BYTES_PER_ELEMENT);\n const control = new SharedArrayBuffer(CONTROL_SLOTS * Int32Array.BYTES_PER_ELEMENT);\n const ctrl = new Int32Array(control);\n Atomics.store(ctrl, STALLED, 1);\n return { channels, capacity, rate, samples, control, buffered };\n}\nfunction i32Max(a, b) {\n return (a - b | 0) > 0 ? a : b;\n}\nfunction slot(idx, capacity) {\n return (idx % capacity + capacity) % capacity;\n}\nfunction casAdvance(arr, idx, candidate) {\n for (; ; ) {\n const current = Atomics.load(arr, idx);\n if ((candidate - current | 0) <= 0) return current;\n const witnessed = Atomics.compareExchange(arr, idx, current, candidate);\n if (witnessed === current) return candidate;\n }\n}\nvar SharedRingBuffer = class _SharedRingBuffer {\n channels;\n capacity;\n rate;\n buffered;\n init;\n #control;\n #samples;\n // Whether READ/WRITE have been anchored to the first inserted sample (buffered mode).\n #anchored = false;\n constructor(init) {\n this.channels = init.channels;\n this.capacity = init.capacity;\n this.rate = init.rate;\n this.buffered = init.buffered;\n this.init = init;\n this.#control = new Int32Array(init.control);\n this.#samples = [];\n for (let i = 0; i < this.channels; i++) {\n this.#samples.push(\n new Float32Array(init.samples, i * this.capacity * Float32Array.BYTES_PER_ELEMENT, this.capacity)\n );\n }\n }\n /**\n * Insert audio samples at the given timestamp.\n * Main thread only. Handles out-of-order writes, gap filling, and overflow.\n */\n insert(timestamp, data) {\n if (data.length !== this.channels) throw new Error(\"wrong number of channels\");\n let start = Math.round(time_exports.Second.fromMicro(timestamp) * this.rate);\n const originalLength = data[0].length;\n let offset = 0;\n if (this.buffered && !this.#anchored) {\n Atomics.store(this.#control, READ, start | 0);\n Atomics.store(this.#control, WRITE, start | 0);\n this.#anchored = true;\n }\n const end = start + originalLength | 0;\n const read = Atomics.load(this.#control, READ);\n const behind = read - start | 0;\n if (behind > 0) {\n if (behind >= originalLength) {\n return;\n }\n offset = behind;\n start = start + behind | 0;\n }\n const samples = originalLength - offset;\n if ((end - read | 0) > this.capacity) {\n casAdvance(this.#control, READ, end - this.capacity | 0);\n }\n const write = Atomics.load(this.#control, WRITE);\n const gap = start - write | 0;\n if (gap > 0) {\n const gapSize = Math.min(gap, this.capacity);\n for (let channel = 0; channel < this.channels; channel++) {\n const dst = this.#samples[channel];\n for (let i = 0; i < gapSize; i++) {\n dst[slot(write + i | 0, this.capacity)] = 0;\n }\n }\n }\n for (let channel = 0; channel < this.channels; channel++) {\n const src = data[channel];\n const dst = this.#samples[channel];\n for (let i = 0; i < samples; i++) {\n dst[slot(start + i | 0, this.capacity)] = src[offset + i];\n }\n }\n Atomics.store(this.#control, WRITE, i32Max(Atomics.load(this.#control, WRITE), end));\n const currentRead = Atomics.load(this.#control, READ);\n const currentWrite = Atomics.load(this.#control, WRITE);\n const latency = Atomics.load(this.#control, LATENCY);\n if ((currentWrite - currentRead | 0) >= latency && latency > 0) {\n Atomics.store(this.#control, STALLED, 0);\n }\n }\n /**\n * Read audio samples into the output buffers.\n * AudioWorklet only. Returns the number of samples read.\n */\n read(output) {\n if (Atomics.load(this.#control, STALLED) === 1) return 0;\n let read = Atomics.load(this.#control, READ);\n const write = Atomics.load(this.#control, WRITE);\n const latency = Atomics.load(this.#control, LATENCY);\n const buffered = write - read | 0;\n if (!this.buffered && latency > 0 && buffered > latency) {\n const skipTo = write - latency | 0;\n read = casAdvance(this.#control, READ, skipTo);\n }\n const available = write - read | 0;\n const count = Math.min(available, output[0].length);\n if (count <= 0) return 0;\n for (let channel = 0; channel < this.channels; channel++) {\n const src = this.#samples[channel];\n const dst = output[channel];\n for (let i = 0; i < count; i++) {\n dst[i] = src[slot(read + i | 0, this.capacity)];\n }\n }\n casAdvance(this.#control, READ, read + count | 0);\n return count;\n }\n /** Update the target latency in samples. */\n setLatency(samples) {\n Atomics.store(this.#control, LATENCY, samples);\n }\n /**\n * Flush buffered samples and re-stall, ready to anchor the next utterance (buffered mode).\n * Main thread only. The worklet reader sees STALLED and stops until the next insert.\n */\n reset() {\n this.#anchored = false;\n Atomics.store(this.#control, STALLED, 1);\n const write = Atomics.load(this.#control, WRITE);\n Atomics.store(this.#control, READ, write);\n }\n /**\n * Allocate a new ring with `newCapacity` samples and copy the unread window\n * [READ, WRITE) plus control state into it. Used when growing capacity so\n * we don't drop buffered audio. If `newCapacity` is smaller than the unread\n * span, the oldest samples are truncated.\n *\n * Main thread only. `resize()` reads from the source `SharedRingBuffer` and\n * writes into a freshly allocated buffer from `allocSharedRingBuffer`, so it\n * relies on the same invariant as `insert()`: no concurrent main-thread\n * writers. The AudioWorklet reader is tolerated via the CAS discipline used\n * by READ/WRITE elsewhere.\n */\n resize(newCapacity) {\n const init = allocSharedRingBuffer(this.channels, newCapacity, this.rate, this.buffered);\n const dst = new _SharedRingBuffer(init);\n dst.#anchored = this.#anchored;\n const read = Atomics.load(this.#control, READ);\n const write = Atomics.load(this.#control, WRITE);\n const latency = Atomics.load(this.#control, LATENCY);\n const stalled = Atomics.load(this.#control, STALLED);\n const available = write - read | 0;\n const copyCount = Math.max(0, Math.min(available, dst.capacity));\n const copyStart = write - copyCount | 0;\n for (let channel = 0; channel < this.channels; channel++) {\n const src = this.#samples[channel];\n const out = dst.#samples[channel];\n for (let i = 0; i < copyCount; i++) {\n const idx = copyStart + i | 0;\n out[slot(idx, dst.capacity)] = src[slot(idx, this.capacity)];\n }\n }\n Atomics.store(dst.#control, READ, copyStart);\n Atomics.store(dst.#control, WRITE, write);\n Atomics.store(dst.#control, LATENCY, latency);\n Atomics.store(dst.#control, STALLED, stalled);\n return dst;\n }\n /** Current playback timestamp derived from READ position. */\n get timestamp() {\n const read = Atomics.load(this.#control, READ);\n return time_exports.Micro.fromSecond(read / this.rate);\n }\n /** Whether the buffer is stalled (waiting to fill). */\n get stalled() {\n return Atomics.load(this.#control, STALLED) === 1;\n }\n /**\n * Number of buffered samples (WRITE - READ).\n *\n * Non-atomic: WRITE and READ are loaded separately, so a concurrent\n * writer/reader can make the two loads inconsistent. Intended for\n * tests and diagnostics, not control-flow decisions.\n */\n get length() {\n return Atomics.load(this.#control, WRITE) - Atomics.load(this.#control, READ) | 0;\n }\n};\n\n// src/audio/render-worklet.ts\nvar Render = class extends AudioWorkletProcessor {\n // Set after init, depending on which path the main thread chose.\n #backend;\n #underflow = 0;\n #stateCounter = 0;\n constructor() {\n super();\n this.port.onmessage = (event) => {\n const msg = event.data;\n if (msg.type === \"init-shared\") {\n console.log(\"[audio-worklet] init-shared: using SharedArrayBuffer path\");\n this.#backend = new SharedRingBuffer(msg);\n this.#underflow = 0;\n } else if (msg.type === \"init-post\") {\n console.log(\"[audio-worklet] init-post: using postMessage path\");\n this.#backend = new AudioRingBuffer(msg);\n this.#underflow = 0;\n } else if (msg.type === \"data\") {\n if (this.#backend instanceof AudioRingBuffer) this.#backend.write(msg.timestamp, msg.data);\n } else if (msg.type === \"latency\") {\n if (this.#backend instanceof AudioRingBuffer) this.#backend.resize(msg.latency);\n } else if (msg.type === \"reset\") {\n if (this.#backend instanceof AudioRingBuffer) this.#backend.reset();\n }\n };\n }\n process(_inputs, outputs, _parameters) {\n const output = outputs[0];\n const backend = this.#backend;\n const samplesRead = backend?.read(output) ?? 0;\n if (samplesRead < output[0].length) {\n this.#underflow += output[0].length - samplesRead;\n } else if (this.#underflow > 0 && backend) {\n console.debug(`audio underflow: ${Math.round(1e3 * this.#underflow / backend.rate)}ms`);\n this.#underflow = 0;\n }\n if (backend instanceof AudioRingBuffer) {\n this.#stateCounter++;\n if (this.#stateCounter >= 5) {\n this.#stateCounter = 0;\n const state = {\n type: \"state\",\n timestamp: backend.timestamp,\n stalled: backend.stalled\n };\n this.port.postMessage(state);\n }\n }\n return true;\n }\n};\nregisterProcessor(\"render\", Render);\n"], { type: "application/javascript" }), D = URL.createObjectURL(re), O = class {
274
+ source;
275
+ enabled;
276
+ #e = new a(void 0);
277
+ context = this.#e;
278
+ #t = new a(void 0);
279
+ root = this.#t;
280
+ #n = new a(void 0);
281
+ sampleRate = this.#n;
282
+ #r = new a(void 0);
283
+ stats = this.#r;
284
+ #i = new a(void 0);
285
+ timestamp = this.#i;
286
+ #a = new a(!0);
287
+ stalled = this.#a;
288
+ #o = new a([]);
289
+ #s = new a([]);
290
+ buffered = this.#s;
291
+ #c;
292
+ #l = 0;
293
+ #u = new i();
294
+ #d = new a(r.Milli.zero);
295
+ constructor(e, t) {
296
+ this.source = e, this.source.supported.set(k), this.enabled = a.from(t?.enabled ?? !1), this.#u.run((e) => {
297
+ this.#d.set(e.get(this.source.sync.maxBuffer));
298
+ }), this.#u.run(this.#f.bind(this)), this.#u.run(this.#p.bind(this)), this.#u.run(this.#m.bind(this)), this.#u.run(this.#h.bind(this));
299
+ }
300
+ #f(e) {
301
+ let t = e.get(this.source.config);
302
+ if (!t) return;
303
+ let n = t.sampleRate, i = t.numberOfChannels, a = new AudioContext({
304
+ latencyHint: "interactive",
305
+ sampleRate: n
306
+ });
307
+ e.set(this.#e, a), e.cleanup(() => a.close()), e.spawn(async () => {
308
+ if (await a.audioWorklet.addModule(D), a.state === "closed") return;
309
+ let t = new AudioWorkletNode(a, "render", {
310
+ channelCount: i,
311
+ channelCountMode: "explicit",
312
+ outputChannelCount: [i]
313
+ });
314
+ e.cleanup(() => t.disconnect());
315
+ let o = this.source.sync.buffer.peek(), s = ee(t, i, n, Math.ceil(n * r.Second.fromMilli(o)), this.source.sync.buffered.peek());
316
+ this.#c = s, e.cleanup(() => {
317
+ s.close(), this.#c = void 0;
318
+ }), e.run((e) => {
319
+ let t = r.Milli.fromMicro(e.get(s.timestamp));
320
+ this.#i.set(t), this.#b(t);
321
+ }), e.run((e) => {
322
+ this.#a.set(e.get(s.stalled));
323
+ }), e.set(this.#t, t);
324
+ });
325
+ }
326
+ #p(e) {
327
+ let t = e.getAll([this.enabled, this.#e]);
328
+ if (!t) return;
329
+ let [n, r] = t;
330
+ r.resume();
331
+ }
332
+ #m(e) {
333
+ if (!e.get(this.#t)) return;
334
+ let t = this.#c;
335
+ if (!t) return;
336
+ let n = e.get(this.source.sync.buffer), i = Math.ceil(t.rate * r.Second.fromMilli(n));
337
+ t.setLatency(i);
338
+ }
339
+ #h(e) {
340
+ if (!e.get(this.enabled)) return;
341
+ let t = e.get(this.source.broadcast);
342
+ if (!t) return;
343
+ let n = e.get(this.source.track);
344
+ if (!n) return;
345
+ let r = e.get(this.source.config);
346
+ if (!r) return;
347
+ let i = e.get(t.active);
348
+ if (!i) return;
349
+ let a = i.subscribe(n, o.PRIORITY.audio);
350
+ e.cleanup(() => a.close()), r.container.kind === "cmaf" ? this.#_(e, a, r) : this.#g(e, a, r);
351
+ }
352
+ #g(e, t, n) {
353
+ let i = n.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), a = new c.Consumer(t, {
354
+ format: i,
355
+ latency: this.#d
356
+ });
357
+ e.cleanup(() => a.close()), e.run((e) => {
358
+ let t = e.get(a.buffered), n = e.get(this.#o);
359
+ this.#s.update(() => c.mergeBufferedRanges(t, n));
360
+ }), e.spawn(async () => {
361
+ if (!await l.Libav.polyfill()) return;
362
+ let t = 0, i = new AudioDecoder({
363
+ output: (e) => {
364
+ if (t++, t <= 3) {
365
+ e.close();
366
+ return;
367
+ }
368
+ this.#v(e);
369
+ },
370
+ error: (e) => console.error(e)
371
+ });
372
+ e.cleanup(() => {
373
+ i.state !== "closed" && i.close();
374
+ });
375
+ let o = n.codec === "opus" ? void 0 : n.description ? l.Hex.toBytes(n.description) : void 0;
376
+ for (i.configure({
377
+ ...n,
378
+ description: o
379
+ });;) {
380
+ let e = await a.next();
381
+ if (!e) break;
382
+ this.#x(e.discontinuity);
383
+ let { frame: t } = e;
384
+ if (!t) continue;
385
+ let n = r.Milli.fromMicro(t.timestamp);
386
+ this.source.sync.received(n, "audio"), this.#r.update((e) => ({ bytesReceived: (e?.bytesReceived ?? 0) + t.data.byteLength })), await this.#c?.wait(t.timestamp);
387
+ let o = new EncodedAudioChunk({
388
+ type: t.keyframe ? "key" : "delta",
389
+ data: t.data,
390
+ timestamp: t.timestamp
391
+ });
392
+ i.decode(o);
393
+ }
394
+ });
395
+ }
396
+ #_(e, t, n) {
397
+ if (n.container.kind !== "cmaf") return;
398
+ let i = p(n.container.init), a = c.Cmaf.decodeInitSegment(i), o = n.codec === "opus" ? void 0 : n.description ? l.Hex.toBytes(n.description) : a.description, s = new c.Consumer(t, {
399
+ format: new c.Cmaf.Format(a),
400
+ latency: this.#d
401
+ });
402
+ e.cleanup(() => s.close()), e.run((e) => {
403
+ let t = e.get(s.buffered), n = e.get(this.#o);
404
+ this.#s.update(() => c.mergeBufferedRanges(t, n));
405
+ }), e.spawn(async () => {
406
+ if (!await l.Libav.polyfill()) return;
407
+ let t = new AudioDecoder({
408
+ output: (e) => this.#v(e),
409
+ error: (e) => console.error(e)
410
+ });
411
+ for (e.cleanup(() => {
412
+ t.state !== "closed" && t.close();
413
+ }), t.configure({
414
+ codec: n.codec,
415
+ sampleRate: n.sampleRate,
416
+ numberOfChannels: n.numberOfChannels,
417
+ description: o
418
+ });;) {
419
+ let e = await s.next();
420
+ if (!e) break;
421
+ this.#x(e.discontinuity);
422
+ let { frame: n } = e;
423
+ if (!n) continue;
424
+ let i = r.Milli.fromMicro(n.timestamp);
425
+ if (this.source.sync.received(i, "audio"), this.#r.update((e) => ({ bytesReceived: (e?.bytesReceived ?? 0) + n.data.byteLength })), await this.#c?.wait(n.timestamp), t.state === "closed") break;
426
+ t.decode(new EncodedAudioChunk({
427
+ type: n.keyframe ? "key" : "delta",
428
+ data: n.data,
429
+ timestamp: n.timestamp
430
+ }));
431
+ }
432
+ });
433
+ }
434
+ #v(e) {
435
+ let t = e.timestamp, n = r.Milli.fromMicro(t), i = this.#c;
436
+ if (!i) {
437
+ e.close();
438
+ return;
439
+ }
440
+ let a = e.numberOfFrames / e.sampleRate * 1e6, o = r.Milli.fromMicro(a), s = r.Milli.add(n, o);
441
+ this.#y(n, s);
442
+ let c = Math.min(e.numberOfChannels, i.channels), l = [];
443
+ for (let t = 0; t < c; t++) {
444
+ let n = new Float32Array(e.numberOfFrames);
445
+ e.copyTo(n, {
446
+ format: "f32-planar",
447
+ planeIndex: t
448
+ }), l.push(n);
449
+ }
450
+ i.insert(t, l), e.close();
451
+ }
452
+ #y(e, t) {
453
+ e > t || this.#o.mutate((n) => {
454
+ for (let i of n) if (e <= i.end + 1 && t >= i.start) {
455
+ i.start = r.Milli.min(i.start, e), i.end = r.Milli.max(i.end, t);
456
+ return;
457
+ }
458
+ n.push({
459
+ start: e,
460
+ end: t
461
+ }), n.sort((e, t) => e.start - t.start);
462
+ });
463
+ }
464
+ #b(e) {
465
+ this.#o.mutate((t) => {
466
+ for (; t.length > 0;) {
467
+ if (t[0].end >= e) {
468
+ t[0].start = r.Milli.max(t[0].start, e);
469
+ break;
470
+ }
471
+ t.shift();
472
+ }
473
+ });
474
+ }
475
+ reset() {
476
+ this.#c?.reset();
477
+ }
478
+ #x(e) {
479
+ e !== this.#l && (this.#l = e, this.#c?.reset(), this.source.sync.reset());
480
+ }
481
+ close() {
482
+ this.#u.close();
483
+ }
484
+ };
485
+ async function k(e) {
486
+ let t;
487
+ if (e.codec !== "opus") {
488
+ if (e.description) t = l.Hex.toBytes(e.description);
489
+ else if (e.container.kind === "cmaf") try {
490
+ t = c.Cmaf.decodeInitSegment(p(e.container.init)).description;
491
+ } catch (t) {
492
+ return console.warn(`audio: malformed CMAF init segment for codec ${e.codec}`, t), !1;
493
+ }
494
+ }
495
+ return (await AudioDecoder.isConfigSupported({
496
+ ...e,
497
+ description: t
498
+ })).supported ?? !1;
499
+ }
500
+ //#endregion
501
+ //#region src/audio/emitter.ts
502
+ var A = .001, j = .2, M = class {
503
+ source;
504
+ volume;
505
+ muted;
506
+ paused;
507
+ #e = new i();
508
+ #t = .5;
509
+ #n = new a(void 0);
510
+ constructor(e, t) {
511
+ this.source = e, this.volume = a.from(t?.volume ?? .5), this.muted = a.from(t?.muted ?? !1), this.paused = a.from(t?.paused ?? t?.muted ?? !1), this.#e.run((e) => {
512
+ e.get(this.muted) ? (this.#t = this.volume.peek() || .5, this.volume.set(0)) : this.volume.set(this.#t);
513
+ }), this.#e.run((e) => {
514
+ let t = !e.get(this.paused) && !e.get(this.muted);
515
+ this.source.enabled.set(t);
516
+ }), this.#e.run((e) => {
517
+ let t = e.get(this.volume);
518
+ this.muted.set(t === 0);
519
+ }), this.#e.run((e) => {
520
+ let t = e.get(this.source.root);
521
+ if (!t) return;
522
+ let n = new GainNode(t.context, { gain: e.get(this.volume) });
523
+ t.connect(n), e.set(this.#n, n), e.run((e) => {
524
+ e.get(this.source.enabled) && (n.connect(t.context.destination), e.cleanup(() => n.disconnect()));
525
+ });
526
+ }), this.#e.run((e) => {
527
+ let t = e.get(this.#n);
528
+ if (!t) return;
529
+ e.cleanup(() => t.gain.cancelScheduledValues(t.context.currentTime));
530
+ let n = e.get(this.volume);
531
+ n < A ? (t.gain.exponentialRampToValueAtTime(A, t.context.currentTime + j), t.gain.setValueAtTime(0, t.context.currentTime + j + .01)) : t.gain.exponentialRampToValueAtTime(n, t.context.currentTime + j);
532
+ });
533
+ }
534
+ close() {
535
+ this.#e.close();
536
+ }
537
+ };
538
+ //#endregion
539
+ //#region src/buffered.ts
540
+ function N(e) {
541
+ let n = [];
542
+ for (let r = 0; r < e.length; r++) {
543
+ let i = t.Time.Milli.fromSecond(e.start(r)), a = t.Time.Milli.fromSecond(e.end(r));
544
+ n.push({
545
+ start: i,
546
+ end: a
547
+ });
548
+ }
549
+ return n;
550
+ }
551
+ //#endregion
552
+ //#region src/audio/mse.ts
553
+ var P = class {
554
+ muxer;
555
+ source;
556
+ volume;
557
+ muted;
558
+ #e = new a(void 0);
559
+ stats = this.#e;
560
+ #t = new a([]);
561
+ buffered = this.#t;
562
+ context = new a(void 0);
563
+ #n = new i();
564
+ constructor(e, t, n) {
565
+ this.muxer = e, this.source = t, this.source.supported.set(ie), this.volume = a.from(n?.volume ?? .5), this.muted = a.from(n?.muted ?? !1), this.#n.run(this.#r.bind(this)), this.#n.run(this.#s.bind(this));
566
+ }
567
+ #r(e) {
568
+ let t = e.get(this.muxer.element);
569
+ if (!t) return;
570
+ let n = e.get(this.muxer.mediaSource);
571
+ if (!n) return;
572
+ let r = e.get(this.source.broadcast);
573
+ if (!r) return;
574
+ let i = e.get(r.active);
575
+ if (!i) return;
576
+ let a = e.get(this.source.track);
577
+ if (!a) return;
578
+ let s = e.get(this.source.config);
579
+ if (!s) return;
580
+ let c = `audio/mp4; codecs="${s.codec}"`, l = n.addSourceBuffer(c);
581
+ e.cleanup(() => {
582
+ n.removeSourceBuffer(l), l.abort();
583
+ }), e.event(l, "error", (e) => {
584
+ console.error("[MSE] SourceBuffer error:", e);
585
+ }), e.event(l, "updateend", () => {
586
+ this.#t.set(N(l.buffered));
587
+ });
588
+ let u = i.subscribe(a, o.PRIORITY.audio);
589
+ e.cleanup(() => u.close()), s.container.kind === "cmaf" ? this.#a(e, u, s, l, t) : this.#o(e, u, s, l, t);
590
+ }
591
+ async #i(e, t) {
592
+ for (; e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
593
+ for (e.appendBuffer(t); e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
594
+ }
595
+ #a(e, n, r, i, a) {
596
+ if (r.container.kind !== "cmaf") throw Error("unreachable");
597
+ let o = p(r.container.init), s = c.Cmaf.decodeInitSegment(o);
598
+ e.spawn(async () => {
599
+ for (await this.#i(i, o);;) {
600
+ let e = await n.readFrame();
601
+ if (!e) return;
602
+ let r = c.Cmaf.decodeTimestamp(e, s);
603
+ this.source.sync.received(t.Time.Milli.fromMicro(r), "audio"), await this.#i(i, e), a.buffered.length > 0 && a.currentTime < a.buffered.start(0) && (a.currentTime = a.buffered.start(0));
604
+ }
605
+ });
606
+ }
607
+ #o(e, n, r, i, a) {
608
+ let o = r.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), s = new c.Consumer(n, {
609
+ format: o,
610
+ latency: this.source.sync.buffer
611
+ });
612
+ e.cleanup(() => s.close()), e.spawn(async () => {
613
+ let e = c.Cmaf.createAudioInitSegment(r);
614
+ await this.#i(i, e);
615
+ let n = 1, o, l;
616
+ for (;;) {
617
+ let e = await s.next();
618
+ if (!e) return;
619
+ if (!e.frame) continue;
620
+ l = e.frame;
621
+ let n = t.Time.Milli.fromMicro(l.timestamp);
622
+ this.source.sync.received(n, "audio");
623
+ break;
624
+ }
625
+ for (;;) {
626
+ let e = await s.next();
627
+ if (e && !e.frame) continue;
628
+ let r = e?.frame;
629
+ if (r) {
630
+ o = t.Time.Micro.sub(r.timestamp, l.timestamp);
631
+ let e = t.Time.Milli.fromMicro(r.timestamp);
632
+ this.source.sync.received(e, "audio");
633
+ }
634
+ let u = c.Cmaf.encodeDataSegment({
635
+ data: l.data,
636
+ timestamp: l.timestamp,
637
+ duration: o ?? 0,
638
+ keyframe: l.keyframe,
639
+ sequence: n++
640
+ });
641
+ if (await this.#i(i, u), a.buffered.length > 0 && a.currentTime < a.buffered.start(0) && (a.currentTime = a.buffered.start(0)), !r) return;
642
+ l = r;
643
+ }
644
+ });
645
+ }
646
+ #s(e) {
647
+ let t = e.get(this.muxer.element);
648
+ if (!t) return;
649
+ let n = e.get(this.volume), r = e.get(this.muted);
650
+ r && !t.muted ? t.muted = !0 : !r && t.muted && (t.muted = !1), n !== t.volume && (t.volume = n), e.event(t, "volumechange", () => {
651
+ this.volume.set(t.volume);
652
+ });
653
+ }
654
+ close() {
655
+ this.#n.close();
656
+ }
657
+ };
658
+ async function ie(e) {
659
+ return MediaSource.isTypeSupported(`audio/mp4; codecs="${e.codec}"`);
660
+ }
661
+ //#endregion
662
+ //#region src/audio/source.ts
663
+ var ae = 128, F = class {
664
+ broadcast;
665
+ target;
666
+ catalog;
667
+ #e = new a({});
668
+ available = this.#e;
669
+ #t = new a(void 0);
670
+ track = this.#t;
671
+ #n = new a(void 0);
672
+ config = this.#n;
673
+ supported;
674
+ sync;
675
+ #r = new i();
676
+ constructor(e, t) {
677
+ this.sync = e, this.broadcast = a.from(t?.broadcast), this.target = a.from(t?.target), this.supported = a.from(t?.supported), this.catalog = this.#r.computed((e) => {
678
+ let t = e.get(this.broadcast);
679
+ return t ? e.get(t.catalog)?.audio : void 0;
680
+ }), this.#r.run(this.#i.bind(this)), this.#r.run(this.#a.bind(this));
681
+ }
682
+ #i(e) {
683
+ let t = e.get(this.catalog)?.renditions ?? {}, n = e.get(this.supported);
684
+ n && e.spawn(async () => {
685
+ let e = {};
686
+ for (let [r, i] of Object.entries(t)) await n(i) && (e[r] = i);
687
+ Object.keys(e).length === 0 && Object.keys(t).length > 0 && console.warn("no supported audio renditions found:", t), this.#e.set(e);
688
+ });
689
+ }
690
+ #a(e) {
691
+ let t = e.get(this.#e);
692
+ if (Object.keys(t).length === 0) return;
693
+ let n = e.get(this.target), r;
694
+ if (n?.name && n.name in t) r = {
695
+ track: n.name,
696
+ config: t[n.name]
697
+ };
698
+ else if (r = this.#o(t), !r) return;
699
+ e.set(this.#t, r.track), e.set(this.#n, r.config);
700
+ let i = (r.config.jitter ?? I(r.config) ?? 0) + Math.ceil(ae / r.config.sampleRate * 1e3);
701
+ e.set(this.sync.audio, i);
702
+ }
703
+ #o(e) {
704
+ let t = Object.entries(e);
705
+ if (t.length !== 0) {
706
+ for (let [e, n] of t) if (n.container.kind === "legacy") return {
707
+ track: e,
708
+ config: n
709
+ };
710
+ for (let [e, n] of t) if (n.container.kind === "loc") return {
711
+ track: e,
712
+ config: n
713
+ };
714
+ for (let [e, n] of t) if (n.container.kind === "cmaf") return {
715
+ track: e,
716
+ config: n
717
+ };
718
+ }
719
+ }
720
+ close() {
721
+ this.#r.close();
722
+ }
723
+ };
724
+ function I(e) {
725
+ if (e.codec.startsWith("opus")) return 20;
726
+ if (e.codec.startsWith("mp4a")) return Math.ceil(1024 / e.sampleRate * 1e3);
727
+ }
728
+ //#endregion
729
+ //#region src/audio/index.ts
730
+ var L = /* @__PURE__ */ f({
731
+ Decoder: () => O,
732
+ Emitter: () => M,
733
+ Mse: () => P,
734
+ Source: () => F
735
+ }), R = /* @__PURE__ */ f({ Muxer: () => z }), z = class {
736
+ element;
737
+ paused;
738
+ #e;
739
+ #t = new a(void 0);
740
+ mediaSource = this.#t;
741
+ #n = new i();
742
+ constructor(e, t) {
743
+ this.element = a.from(t?.element), this.paused = a.from(t?.paused ?? !1), this.#e = e, this.#n.run(this.#r.bind(this)), this.#n.run(this.#i.bind(this)), this.#n.run(this.#a.bind(this)), this.#n.run(this.#o.bind(this)), this.#n.run(this.#s.bind(this));
744
+ }
745
+ #r(e) {
746
+ let t = e.get(this.element);
747
+ if (!t) return;
748
+ let n = new MediaSource();
749
+ t.src = URL.createObjectURL(n), e.cleanup(() => URL.revokeObjectURL(t.src)), e.event(n, "sourceopen", () => {
750
+ e.set(this.#t, n);
751
+ }, { once: !0 }), e.event(n, "error", (e) => {
752
+ console.error("[MSE] MediaSource error event:", e);
753
+ });
754
+ }
755
+ #i(e) {
756
+ let t = e.get(this.element);
757
+ if (!t || e.get(this.paused)) return;
758
+ let n = r.Milli.toSecond(e.get(this.#e.buffer));
759
+ e.interval(() => {
760
+ let e = t.buffered;
761
+ if (e.length === 0) return;
762
+ let r = e.end(e.length - 1) - n, i = r - t.currentTime;
763
+ (i > .1 || i < -.1) && (console.warn("seeking", i > 0 ? "forward" : "backward", Math.abs(i).toFixed(3), "seconds"), t.currentTime = r);
764
+ }, 100);
765
+ }
766
+ #a(e) {
767
+ let t = e.get(this.element);
768
+ if (!t) return;
769
+ let n = e.get(this.mediaSource);
770
+ n && e.interval(() => {
771
+ for (let e of n.sourceBuffers) e.updating || t.currentTime > 10 && e.remove(0, t.currentTime - 10);
772
+ }, 1e3);
773
+ }
774
+ #o(e) {
775
+ let t = e.get(this.element);
776
+ if (!t) return;
777
+ let n = e.get(this.paused);
778
+ n && !t.paused ? t.pause() : !n && t.paused && t.play().catch((e) => {
779
+ console.error("[MSE] MediaElement play error:", e);
780
+ });
781
+ }
782
+ #s(e) {
783
+ let t = e.get(this.element);
784
+ if (!t || e.get(this.paused)) return;
785
+ let n = e.get(this.#e.reference);
786
+ if (n === void 0) return;
787
+ let i = e.get(this.#e.buffer), a = r.Milli.sub(r.Milli.sub(r.Milli.now(), n), i);
788
+ t.currentTime = r.Milli.toSecond(a);
789
+ }
790
+ close() {
791
+ this.#n.close();
792
+ }
793
+ }, B = 500, V = 100, H = class {
794
+ enabled;
795
+ source;
796
+ #e = new a(void 0);
797
+ #t = new a(void 0);
798
+ frame = this.#t;
799
+ #n = new a(void 0);
800
+ timestamp = this.#n;
801
+ #r = new a(void 0);
802
+ display = this.#r;
803
+ #i = new a(!1);
804
+ stalled = this.#i;
805
+ #a = new a(void 0);
806
+ stats = this.#a;
807
+ #o = new a([]);
808
+ buffered = this.#o;
809
+ #s = new i();
810
+ #c() {
811
+ this.#t.update((e) => {
812
+ e?.close();
813
+ }), this.#n.set(void 0);
814
+ }
815
+ constructor(e, t) {
816
+ this.enabled = a.from(t?.enabled ?? !1), this.source = e, this.source.supported.set(W), this.#s.run(this.#l.bind(this)), this.#s.run(this.#u.bind(this)), this.#s.run(this.#d.bind(this)), this.#s.run(this.#f.bind(this));
817
+ }
818
+ #l(e) {
819
+ let t = e.getAll([
820
+ this.enabled,
821
+ this.source.broadcast,
822
+ this.source.track,
823
+ this.source.config
824
+ ]);
825
+ if (!t) {
826
+ this.#e.set(void 0);
827
+ return;
828
+ }
829
+ let [n, r, i, a] = t, o = e.get(r.active);
830
+ if (!o) {
831
+ this.#e.set(void 0), this.#c(), this.#o.set([]);
832
+ return;
833
+ }
834
+ let s = new U({
835
+ source: this.source,
836
+ broadcast: o,
837
+ track: i,
838
+ config: a,
839
+ stats: this.#a
840
+ });
841
+ e.cleanup(() => s?.close()), e.run((e) => {
842
+ if (!s) return;
843
+ let t = e.get(this.#e);
844
+ if (t) {
845
+ let n = e.get(s.timestamp), r = e.get(t.timestamp);
846
+ if (!n || r && r > n + V) return;
847
+ }
848
+ this.#e.set(s), s = void 0, e.close();
849
+ });
850
+ }
851
+ #u(e) {
852
+ let t = e.get(this.#e);
853
+ if (!t) {
854
+ this.#o.set([]);
855
+ return;
856
+ }
857
+ e.cleanup(() => t.close()), e.run((e) => {
858
+ let n = e.get(t.frame);
859
+ this.#t.update((e) => (e?.close(), n?.clone()));
860
+ }), e.proxy(this.#n, t.timestamp), e.proxy(this.#o, t.buffered);
861
+ }
862
+ #d(e) {
863
+ let t = e.get(this.source.catalog);
864
+ if (!t) return;
865
+ let n = t.display;
866
+ if (n) {
867
+ e.set(this.#r, {
868
+ width: n.width,
869
+ height: n.height
870
+ });
871
+ return;
872
+ }
873
+ let r = e.get(this.frame);
874
+ r && e.set(this.#r, {
875
+ width: r.displayWidth,
876
+ height: r.displayHeight
877
+ });
878
+ }
879
+ #f(e) {
880
+ if (e.get(this.enabled)) {
881
+ if (!e.get(this.frame)) {
882
+ this.#i.set(!0);
883
+ return;
884
+ }
885
+ this.#i.set(!1), e.timer(() => {
886
+ this.#i.set(!0);
887
+ }, B);
888
+ }
889
+ }
890
+ close() {
891
+ this.#c(), this.#s.close();
892
+ }
893
+ }, U = class {
894
+ source;
895
+ broadcast;
896
+ track;
897
+ config;
898
+ stats;
899
+ timestamp = new a(void 0);
900
+ frame = new a(void 0);
901
+ buffered = new a([]);
902
+ #e = new a([]);
903
+ #t = 0;
904
+ signals = new i();
905
+ constructor(e) {
906
+ let { codedWidth: t, codedHeight: n, ...r } = e.config;
907
+ this.source = e.source, this.broadcast = e.broadcast, this.track = e.track, this.config = r, this.stats = e.stats, this.signals.run(this.#n.bind(this));
908
+ }
909
+ #n(e) {
910
+ let t = this.broadcast.subscribe(this.track, o.PRIORITY.video);
911
+ e.cleanup(() => t.close());
912
+ let n = new VideoDecoder({
913
+ output: async (t) => {
914
+ try {
915
+ let n = this.#t, i = r.Milli.fromMicro(t.timestamp);
916
+ if (i < (this.timestamp.peek() ?? 0)) return;
917
+ this.frame.peek() === void 0 && this.frame.set(t.clone());
918
+ let a = this.source.sync.wait(i).then(() => !0);
919
+ if (!await Promise.race([a, e.cancel]) || n !== this.#t || i < (this.timestamp.peek() ?? 0)) return;
920
+ this.timestamp.set(i), this.#s(i), this.frame.update((e) => (e?.close(), t.clone()));
921
+ } finally {
922
+ t.close();
923
+ }
924
+ },
925
+ error: (t) => {
926
+ console.error(t), e.close();
927
+ }
928
+ });
929
+ e.cleanup(() => {
930
+ n.state !== "closed" && n.close();
931
+ }), this.config.container.kind === "cmaf" ? this.#i(e, t, n) : this.#r(e, t, n);
932
+ }
933
+ #r(e, t, n) {
934
+ let i = this.config.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), a = new c.Consumer(t, {
935
+ format: i,
936
+ latency: this.source.sync.buffer
937
+ });
938
+ e.cleanup(() => a.close()), e.run((e) => {
939
+ let t = e.get(a.buffered), n = e.get(this.#e);
940
+ this.buffered.update(() => c.mergeBufferedRanges(t, n));
941
+ }), n.configure({
942
+ ...this.config,
943
+ description: this.config.description ? l.Hex.toBytes(this.config.description) : void 0,
944
+ optimizeForLatency: this.config.optimizeForLatency ?? !0,
945
+ flip: !1
946
+ });
947
+ let o;
948
+ e.spawn(async () => {
949
+ for (;;) {
950
+ let e = await a.next();
951
+ if (!e) break;
952
+ this.#a(e.discontinuity) && (o = void 0);
953
+ let { frame: t, group: i } = e;
954
+ if (!t) {
955
+ o && (o.final = !0);
956
+ continue;
957
+ }
958
+ let s = r.Milli.fromMicro(t.timestamp);
959
+ this.source.sync.received(s, "video");
960
+ let c = new EncodedVideoChunk({
961
+ type: t.keyframe ? "key" : "delta",
962
+ data: t.data,
963
+ timestamp: t.timestamp
964
+ });
965
+ this.stats.update((e) => ({
966
+ frameCount: (e?.frameCount ?? 0) + 1,
967
+ bytesReceived: (e?.bytesReceived ?? 0) + t.data.byteLength
968
+ }));
969
+ let l = o;
970
+ if (l && (l.group === i || l.final && l.group + 1 === i)) {
971
+ let e = r.Milli.fromMicro(l.timestamp), n = r.Milli.fromMicro(t.timestamp);
972
+ this.#o(e, n);
973
+ }
974
+ o = {
975
+ timestamp: t.timestamp,
976
+ group: i,
977
+ final: !1
978
+ }, n.decode(c);
979
+ }
980
+ });
981
+ }
982
+ #i(e, t, n) {
983
+ if (this.config.container.kind !== "cmaf") return;
984
+ let i = p(this.config.container.init), a = c.Cmaf.decodeInitSegment(i), o = this.config.description ? l.Hex.toBytes(this.config.description) : a.description, s = new c.Consumer(t, {
985
+ format: new c.Cmaf.Format(a),
986
+ latency: this.source.sync.buffer
987
+ });
988
+ e.cleanup(() => s.close()), e.run((e) => {
989
+ let t = e.get(s.buffered), n = e.get(this.#e);
990
+ this.buffered.update(() => c.mergeBufferedRanges(t, n));
991
+ }), n.configure({
992
+ codec: this.config.codec,
993
+ description: o,
994
+ optimizeForLatency: this.config.optimizeForLatency ?? !0,
995
+ flip: !1
996
+ });
997
+ let u;
998
+ e.spawn(async () => {
999
+ for (;;) {
1000
+ let e = await s.next();
1001
+ if (!e) break;
1002
+ this.#a(e.discontinuity) && (u = void 0);
1003
+ let { frame: t, group: i } = e;
1004
+ if (!t) {
1005
+ u && (u.final = !0);
1006
+ continue;
1007
+ }
1008
+ let a = r.Milli.fromMicro(t.timestamp);
1009
+ this.source.sync.received(a, "video"), this.stats.update((e) => ({
1010
+ frameCount: (e?.frameCount ?? 0) + 1,
1011
+ bytesReceived: (e?.bytesReceived ?? 0) + t.data.byteLength
1012
+ }));
1013
+ let o = u;
1014
+ if (o && (o.group === i || o.final && o.group + 1 === i)) {
1015
+ let e = r.Milli.fromMicro(o.timestamp), n = r.Milli.fromMicro(t.timestamp);
1016
+ this.#o(e, n);
1017
+ }
1018
+ if (u = {
1019
+ timestamp: t.timestamp,
1020
+ group: i,
1021
+ final: !1
1022
+ }, n.state === "closed") break;
1023
+ n.decode(new EncodedVideoChunk({
1024
+ type: t.keyframe ? "key" : "delta",
1025
+ data: t.data,
1026
+ timestamp: t.timestamp
1027
+ }));
1028
+ }
1029
+ });
1030
+ }
1031
+ #a(e) {
1032
+ return e === this.#t ? !1 : (this.#t = e, this.timestamp.set(void 0), this.#e.set([]), this.source.sync.reset(), !0);
1033
+ }
1034
+ #o(e, t) {
1035
+ e > t || this.#e.mutate((n) => {
1036
+ for (let i of n) if (i.start <= t && i.end >= e) {
1037
+ i.start = r.Milli.min(i.start, e), i.end = r.Milli.max(i.end, t);
1038
+ return;
1039
+ }
1040
+ n.push({
1041
+ start: e,
1042
+ end: t
1043
+ }), n.sort((e, t) => e.start - t.start);
1044
+ });
1045
+ }
1046
+ #s(e) {
1047
+ this.#e.mutate((t) => {
1048
+ for (; t.length > 0;) {
1049
+ if (t[0].end >= e) {
1050
+ t[0].start = r.Milli.max(t[0].start, e);
1051
+ break;
1052
+ }
1053
+ t.shift();
1054
+ }
1055
+ });
1056
+ }
1057
+ close() {
1058
+ this.signals.close(), this.frame.update((e) => {
1059
+ e?.close();
1060
+ });
1061
+ }
1062
+ };
1063
+ async function W(e) {
1064
+ let t;
1065
+ if (e.description) t = l.Hex.toBytes(e.description);
1066
+ else if (e.container.kind === "cmaf") try {
1067
+ t = c.Cmaf.decodeInitSegment(p(e.container.init)).description;
1068
+ } catch (t) {
1069
+ return console.warn(`video: malformed CMAF init segment for codec ${e.codec}`, t), !1;
1070
+ }
1071
+ let { supported: n } = await VideoDecoder.isConfigSupported({
1072
+ codec: e.codec,
1073
+ description: t,
1074
+ optimizeForLatency: e.optimizeForLatency ?? !0
1075
+ });
1076
+ if (n) return !0;
1077
+ if (e.codec.startsWith("avc3.")) {
1078
+ let n = `avc1.${e.codec.slice(5)}`;
1079
+ if ((await VideoDecoder.isConfigSupported({
1080
+ codec: n,
1081
+ description: t,
1082
+ optimizeForLatency: e.optimizeForLatency ?? !0
1083
+ })).supported) return e.codec = n, !0;
1084
+ }
1085
+ return !1;
1086
+ }
1087
+ //#endregion
1088
+ //#region src/video/mse.ts
1089
+ var G = class {
1090
+ muxer;
1091
+ source;
1092
+ #e = new a(void 0);
1093
+ stats = this.#e;
1094
+ #t = new a([]);
1095
+ buffered = this.#t;
1096
+ #n = new a(!1);
1097
+ stalled = this.#n;
1098
+ #r = new a(t.Time.Milli.zero);
1099
+ timestamp = this.#r;
1100
+ signals = new i();
1101
+ constructor(e, t) {
1102
+ this.muxer = e, this.source = t, this.source.supported.set(K), this.signals.run(this.#i.bind(this)), this.signals.run(this.#c.bind(this)), this.signals.run(this.#l.bind(this));
1103
+ }
1104
+ #i(e) {
1105
+ let t = e.get(this.muxer.element);
1106
+ if (!t) return;
1107
+ let n = e.get(this.muxer.mediaSource);
1108
+ if (!n) return;
1109
+ let r = e.get(this.source.broadcast);
1110
+ if (!r) return;
1111
+ let i = e.get(r.active);
1112
+ if (!i) return;
1113
+ let a = e.get(this.source.track);
1114
+ if (!a) return;
1115
+ let o = e.get(this.source.config);
1116
+ if (!o) return;
1117
+ let s = `video/mp4; codecs="${o.codec}"`, c = n.addSourceBuffer(s);
1118
+ e.cleanup(() => {
1119
+ n.removeSourceBuffer(c), c.abort();
1120
+ }), e.event(c, "error", (e) => {
1121
+ console.error("[MSE] SourceBuffer error:", e);
1122
+ }), e.event(c, "updateend", () => {
1123
+ this.#t.set(N(c.buffered));
1124
+ }), o.container.kind === "cmaf" ? this.#o(e, i, a, o, c, t) : this.#s(e, i, a, o, c, t);
1125
+ }
1126
+ async #a(e, t) {
1127
+ for (; e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
1128
+ for (e.appendBuffer(t); e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
1129
+ }
1130
+ #o(e, n, r, i, a, s) {
1131
+ if (i.container.kind !== "cmaf") throw Error("unreachable");
1132
+ let l = n.subscribe(r, o.PRIORITY.video);
1133
+ e.cleanup(() => l.close());
1134
+ let u = p(i.container.init), d = c.Cmaf.decodeInitSegment(u);
1135
+ e.spawn(async () => {
1136
+ for (await this.#a(a, u);;) {
1137
+ let e = await l.readFrame();
1138
+ if (!e) return;
1139
+ let n = c.Cmaf.decodeTimestamp(e, d);
1140
+ this.source.sync.received(t.Time.Milli.fromMicro(n), "video"), await this.#a(a, e), s.buffered.length > 0 && s.currentTime < s.buffered.start(0) && (s.currentTime = s.buffered.start(0));
1141
+ }
1142
+ });
1143
+ }
1144
+ #s(e, n, r, i, a, s) {
1145
+ let l = n.subscribe(r, o.PRIORITY.video);
1146
+ e.cleanup(() => l.close());
1147
+ let u = i.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), d = new c.Consumer(l, {
1148
+ format: u,
1149
+ latency: this.source.sync.buffer
1150
+ });
1151
+ e.cleanup(() => d.close()), e.spawn(async () => {
1152
+ let e = c.Cmaf.createVideoInitSegment(i);
1153
+ await this.#a(a, e);
1154
+ let n = 1, r, o;
1155
+ for (;;) {
1156
+ let e = await d.next();
1157
+ if (!e) return;
1158
+ if (!e.frame) continue;
1159
+ o = e.frame;
1160
+ let n = t.Time.Milli.fromMicro(o.timestamp);
1161
+ this.source.sync.received(n, "video");
1162
+ break;
1163
+ }
1164
+ for (;;) {
1165
+ let e = await d.next();
1166
+ if (e && !e.frame) continue;
1167
+ let i = e?.frame;
1168
+ if (i) {
1169
+ r = t.Time.Micro.sub(i.timestamp, o.timestamp);
1170
+ let e = t.Time.Milli.fromMicro(i.timestamp);
1171
+ this.source.sync.received(e, "video");
1172
+ }
1173
+ let l = c.Cmaf.encodeDataSegment({
1174
+ data: o.data,
1175
+ timestamp: o.timestamp,
1176
+ duration: r ?? 0,
1177
+ keyframe: o.keyframe,
1178
+ sequence: n++
1179
+ });
1180
+ if (await this.#a(a, l), s.buffered.length > 0 && s.currentTime < s.buffered.start(0) && (s.currentTime = s.buffered.start(0)), !i) return;
1181
+ o = i;
1182
+ }
1183
+ });
1184
+ }
1185
+ #c(e) {
1186
+ let t = e.get(this.muxer.element);
1187
+ if (!t) return;
1188
+ let n = () => {
1189
+ this.#n.set(t.readyState <= HTMLMediaElement.HAVE_CURRENT_DATA);
1190
+ };
1191
+ n(), e.event(t, "waiting", n), e.event(t, "playing", n), e.event(t, "seeking", n);
1192
+ }
1193
+ #l(e) {
1194
+ let n = e.get(this.muxer.element);
1195
+ if (n) if ("requestVideoFrameCallback" in n) {
1196
+ let r = n, i, a = () => {
1197
+ let e = t.Time.Milli.fromSecond(r.currentTime);
1198
+ this.#r.set(e), i = r.requestVideoFrameCallback(a);
1199
+ };
1200
+ i = r.requestVideoFrameCallback(a), e.cleanup(() => r.cancelVideoFrameCallback(i));
1201
+ } else e.event(n, "timeupdate", () => {
1202
+ let e = t.Time.Milli.fromSecond(n.currentTime);
1203
+ this.#r.set(e);
1204
+ });
1205
+ }
1206
+ close() {
1207
+ this.source.close(), this.signals.close();
1208
+ }
1209
+ };
1210
+ async function K(e) {
1211
+ return MediaSource.isTypeSupported(`video/mp4; codecs="${e.codec}"`);
1212
+ }
1213
+ //#endregion
1214
+ //#region src/video/renderer.ts
1215
+ var q = .01, J = class {
1216
+ decoder;
1217
+ canvas;
1218
+ paused;
1219
+ visible;
1220
+ frame = new a(void 0);
1221
+ timestamp = new a(void 0);
1222
+ #e = new a(void 0);
1223
+ #t = new a(!1);
1224
+ #n = new i();
1225
+ constructor(e, t) {
1226
+ this.decoder = e, this.canvas = a.from(t?.canvas), this.paused = a.from(t?.paused ?? !1), this.visible = a.from(t?.visible ?? "0px"), this.#n.run((e) => {
1227
+ let t = e.get(this.canvas);
1228
+ this.#e.set(t?.getContext("2d") ?? void 0);
1229
+ }), this.#n.run(this.#i.bind(this)), this.#n.run(this.#a.bind(this)), this.#n.run(this.#o.bind(this)), this.#n.run(this.#r.bind(this));
1230
+ }
1231
+ #r(e) {
1232
+ let t = e.getAll([this.canvas, this.decoder.display]);
1233
+ if (!t) return;
1234
+ let [n, r] = t;
1235
+ (n.width !== r.width || n.height !== r.height) && (n.width = r.width, n.height = r.height);
1236
+ }
1237
+ #i(e) {
1238
+ let t = e.get(this.visible);
1239
+ if (t === "never") {
1240
+ this.#t.set(!1);
1241
+ return;
1242
+ }
1243
+ if (t === "always") {
1244
+ this.#t.set(!0), e.cleanup(() => this.#t.set(!1));
1245
+ return;
1246
+ }
1247
+ let n = e.get(this.canvas);
1248
+ if (!n) {
1249
+ this.#t.set(!1);
1250
+ return;
1251
+ }
1252
+ let r = !1, i = () => {
1253
+ this.#t.set(r && !document.hidden);
1254
+ }, a = (e) => {
1255
+ for (let t of e) r = t.isIntersecting, i();
1256
+ }, o;
1257
+ try {
1258
+ o = new IntersectionObserver(a, {
1259
+ threshold: q,
1260
+ rootMargin: t
1261
+ });
1262
+ } catch {
1263
+ console.warn(`moq-watch: invalid visible margin "${t}", using "0px"`), o = new IntersectionObserver(a, { threshold: q });
1264
+ }
1265
+ i(), e.event(document, "visibilitychange", i), o.observe(n), e.cleanup(() => o.disconnect()), e.cleanup(() => this.#t.set(!1));
1266
+ }
1267
+ #a(e) {
1268
+ let t = e.get(this.paused), n = e.get(this.#t);
1269
+ if (e.cleanup(() => this.decoder.enabled.set(!1)), !t) {
1270
+ this.decoder.enabled.set(n);
1271
+ return;
1272
+ }
1273
+ let r = e.get(this.decoder.frame);
1274
+ this.decoder.enabled.set(!r);
1275
+ }
1276
+ #o(e) {
1277
+ let t = e.get(this.#e);
1278
+ if (!t) return;
1279
+ let n = e.get(this.decoder.frame), i = requestAnimationFrame(() => {
1280
+ this.#s(t, n), n ? (this.frame.update((e) => (e?.close(), n.clone())), this.timestamp.set(r.Milli.fromMicro(n.timestamp))) : (this.frame.update((e) => {
1281
+ e?.close();
1282
+ }), this.timestamp.set(void 0)), i = void 0;
1283
+ });
1284
+ e.cleanup(() => {
1285
+ i && cancelAnimationFrame(i);
1286
+ });
1287
+ }
1288
+ #s(e, t) {
1289
+ if (!t) {
1290
+ e.fillStyle = "#000", e.fillRect(0, 0, e.canvas.width, e.canvas.height);
1291
+ return;
1292
+ }
1293
+ e.save(), e.fillStyle = "#000", e.fillRect(0, 0, e.canvas.width, e.canvas.height), this.decoder.source.catalog.peek()?.flip && (e.scale(-1, 1), e.translate(-e.canvas.width, 0)), e.drawImage(t, 0, 0, e.canvas.width, e.canvas.height), e.restore();
1294
+ }
1295
+ close() {
1296
+ this.frame.update((e) => {
1297
+ e?.close();
1298
+ }), this.timestamp.set(void 0), this.#n.close();
1299
+ }
1300
+ };
1301
+ //#endregion
1302
+ //#region src/video/source.ts
1303
+ function oe(e) {
1304
+ return (t) => {
1305
+ let n = [], r = [];
1306
+ for (let [i, a] of t) if (a.codedWidth && a.codedHeight) {
1307
+ let t = a.codedWidth * a.codedHeight;
1308
+ t <= e ? n.push({
1309
+ name: i,
1310
+ size: t
1311
+ }) : r.push({
1312
+ name: i,
1313
+ size: t
1314
+ });
1315
+ }
1316
+ return n.sort((e, t) => t.size - e.size), n.length > 0 ? n.map((e) => e.name) : r.length > 0 ? (r.sort((e, t) => e.size - t.size), [r[0].name]) : t.map(([e]) => e);
1317
+ };
1318
+ }
1319
+ function se(e, t) {
1320
+ return (n) => {
1321
+ let r = [], i = [];
1322
+ for (let [a, o] of n) {
1323
+ if (!o.codedWidth || !o.codedHeight) continue;
1324
+ let n = o.codedWidth * o.codedHeight, s = e == null || o.codedWidth <= e, c = t == null || o.codedHeight <= t;
1325
+ s && c ? r.push({
1326
+ name: a,
1327
+ size: n
1328
+ }) : i.push({
1329
+ name: a,
1330
+ size: n
1331
+ });
1332
+ }
1333
+ return r.sort((e, t) => t.size - e.size), r.length > 0 ? r.map((e) => e.name) : i.length > 0 ? (i.sort((e, t) => e.size - t.size), [i[0].name]) : n.map(([e]) => e);
1334
+ };
1335
+ }
1336
+ function ce(e) {
1337
+ return (t) => {
1338
+ let n = [], r = [];
1339
+ for (let [i, a] of t) a.bitrate != null && a.bitrate <= e ? n.push({
1340
+ name: i,
1341
+ bitrate: a.bitrate
1342
+ }) : a.bitrate != null && r.push({
1343
+ name: i,
1344
+ bitrate: a.bitrate
1345
+ });
1346
+ return n.sort((e, t) => t.bitrate - e.bitrate), n.length > 0 ? n.map((e) => e.name) : r.length > 0 ? (r.sort((e, t) => e.bitrate - t.bitrate), [r[0].name]) : t.map(([e]) => e);
1347
+ };
1348
+ }
1349
+ function le(e) {
1350
+ let t = e[0];
1351
+ for (let n of e) {
1352
+ let [, e] = n, [, r] = t, i = (e.codedWidth ?? 0) * (e.codedHeight ?? 0), a = (r.codedWidth ?? 0) * (r.codedHeight ?? 0);
1353
+ if (i !== a) {
1354
+ i > a && (t = n);
1355
+ continue;
1356
+ }
1357
+ (e.bitrate ?? 0) > (r.bitrate ?? 0) && (t = n);
1358
+ }
1359
+ return t[0];
1360
+ }
1361
+ var Y = class {
1362
+ broadcast;
1363
+ target;
1364
+ catalog;
1365
+ #e = new a({});
1366
+ available = this.#e;
1367
+ #t = new a(void 0);
1368
+ track = this.#t;
1369
+ #n = new a(void 0);
1370
+ config = this.#n;
1371
+ sync;
1372
+ supported;
1373
+ #r = new i();
1374
+ constructor(e, t) {
1375
+ this.broadcast = a.from(t?.broadcast), this.target = a.from(t?.target), this.sync = e, this.supported = a.from(t?.supported), this.catalog = this.#r.computed((e) => {
1376
+ let t = e.get(this.broadcast);
1377
+ return t ? e.get(t.catalog)?.video : void 0;
1378
+ }), this.#r.run(this.#i.bind(this)), this.#r.run(this.#a.bind(this));
1379
+ }
1380
+ #i(e) {
1381
+ let t = e.get(this.supported);
1382
+ if (!t) return;
1383
+ let n = e.get(this.catalog)?.renditions ?? {};
1384
+ e.spawn(async () => {
1385
+ let e = {};
1386
+ for (let [r, i] of Object.entries(n)) await t(i) && (e[r] = i);
1387
+ Object.keys(e).length === 0 && Object.keys(n).length > 0 && console.warn("[Source] No supported video renditions found:", n), this.#e.set(e);
1388
+ });
1389
+ }
1390
+ #a(e) {
1391
+ let t = e.get(this.#e);
1392
+ if (Object.keys(t).length === 0) return;
1393
+ let n = e.get(this.target);
1394
+ if (n?.name && n.name in t) {
1395
+ let r = t[n.name];
1396
+ e.set(this.#t, n.name), e.set(this.#n, r), e.set(this.sync.video, r.jitter);
1397
+ return;
1398
+ }
1399
+ let r = n;
1400
+ if (!n?.bitrate) {
1401
+ let t = e.get(this.broadcast), i = (t ? e.get(t.connection) : void 0)?.recvBandwidth;
1402
+ if (i) {
1403
+ let t = e.get(i);
1404
+ if (t != null) {
1405
+ let e = Math.round(t * .8);
1406
+ r = {
1407
+ ...n,
1408
+ bitrate: e
1409
+ };
1410
+ }
1411
+ }
1412
+ }
1413
+ let i = this.#o(t, r);
1414
+ if (!i) return;
1415
+ let a = t[i];
1416
+ e.set(this.#t, i), e.set(this.#n, a);
1417
+ let o = a.jitter ?? (a.framerate ? Math.ceil(1e3 / a.framerate) : void 0);
1418
+ e.set(this.sync.video, o);
1419
+ }
1420
+ #o(e, t) {
1421
+ let n = Object.entries(e);
1422
+ if (n.length === 0) return;
1423
+ if (n.length === 1) return n[0][0];
1424
+ let r = [];
1425
+ if (t?.pixels != null && r.push(oe(t.pixels)), (t?.width != null || t?.height != null) && r.push(se(t.width, t.height)), t?.bitrate != null && r.push(ce(t.bitrate)), r.length === 0) return le(n);
1426
+ let i = r.map((e) => e(n)), a = i.map((e) => new Set(e));
1427
+ for (let e of i[0]) if (a.every((t) => t.has(e))) return e;
1428
+ console.warn("conflicting rendition filters, no rendition satisfies all criteria");
1429
+ }
1430
+ close() {
1431
+ this.#r.close();
1432
+ }
1433
+ }, ue = /* @__PURE__ */ f({
1434
+ Decoder: () => H,
1435
+ Mse: () => G,
1436
+ Renderer: () => J,
1437
+ Source: () => Y
1438
+ }), de = class {
1439
+ source;
1440
+ stats = new a(void 0);
1441
+ stalled = new a(!1);
1442
+ buffered = new a([]);
1443
+ timestamp = new a(t.Time.Milli.zero);
1444
+ constructor(e) {
1445
+ this.source = e;
1446
+ }
1447
+ }, fe = class {
1448
+ source;
1449
+ volume = new a(.5);
1450
+ muted = new a(!1);
1451
+ stats = new a(void 0);
1452
+ buffered = new a([]);
1453
+ context = new a(void 0);
1454
+ constructor(e) {
1455
+ this.source = e;
1456
+ }
1457
+ }, pe = class {
1458
+ element = new a(void 0);
1459
+ broadcast;
1460
+ latency;
1461
+ jitter;
1462
+ buffered;
1463
+ paused;
1464
+ visible;
1465
+ video;
1466
+ #e;
1467
+ audio;
1468
+ #t;
1469
+ #n;
1470
+ sync;
1471
+ signals = new i();
1472
+ constructor(t) {
1473
+ this.element = a.from(t?.element), this.broadcast = a.from(t?.broadcast), this.sync = new e({
1474
+ latency: t?.latency,
1475
+ connection: t?.connection
1476
+ }), this.latency = this.sync.latency, this.jitter = this.sync.jitter, this.buffered = this.sync.buffered, this.#e = new Y(this.sync, { broadcast: this.broadcast }), this.#t = new F(this.sync, { broadcast: this.broadcast }), this.video = new de(this.#e), this.audio = new fe(this.#t), this.paused = a.from(t?.paused ?? !1), this.visible = a.from(t?.visible ?? "0px"), this.signals.run(this.#r.bind(this));
1477
+ }
1478
+ #r(e) {
1479
+ let t = e.get(this.element);
1480
+ t && (t instanceof HTMLCanvasElement ? this.#i(e, t) : t instanceof HTMLVideoElement && this.#a(e, t));
1481
+ }
1482
+ #i(e, t) {
1483
+ let n = new H(this.#e), r = new O(this.#t);
1484
+ this.#n = r;
1485
+ let i = new M(r, {
1486
+ volume: this.audio.volume,
1487
+ muted: this.audio.muted,
1488
+ paused: this.paused
1489
+ }), a = new J(n, {
1490
+ canvas: t,
1491
+ paused: this.paused,
1492
+ visible: this.visible
1493
+ });
1494
+ e.cleanup(() => {
1495
+ n.close(), r.close(), i.close(), a.close(), this.#n = void 0;
1496
+ }), e.proxy(this.video.stats, n.stats), e.proxy(this.video.buffered, n.buffered), e.proxy(this.video.stalled, n.stalled), e.proxy(this.video.timestamp, n.timestamp), e.proxy(this.audio.stats, r.stats), e.proxy(this.audio.buffered, r.buffered), e.proxy(this.audio.context, r.context);
1497
+ }
1498
+ #a(e, t) {
1499
+ let n = new z(this.sync, {
1500
+ paused: this.paused,
1501
+ element: t
1502
+ }), r = new G(n, this.#e), i = new P(n, this.#t, {
1503
+ volume: this.audio.volume,
1504
+ muted: this.audio.muted
1505
+ });
1506
+ e.cleanup(() => {
1507
+ r.close(), i.close(), n.close();
1508
+ }), e.proxy(this.video.stats, r.stats), e.proxy(this.video.buffered, r.buffered), e.proxy(this.video.stalled, r.stalled), e.proxy(this.video.timestamp, r.timestamp), e.proxy(this.audio.stats, i.stats), e.proxy(this.audio.buffered, i.buffered), e.proxy(this.audio.context, i.context);
1509
+ }
1510
+ reset() {
1511
+ this.sync.reset(), this.#n?.reset();
1512
+ }
1513
+ close() {
1514
+ this.signals.close(), this.#e.close(), this.#t.close(), this.sync.close();
1515
+ }
1516
+ }, me = 48e3, X = 2;
1517
+ function he(e) {
1518
+ let t = "";
1519
+ for (let n = 0; n < e.length; n++) t += e[n].toString(16).padStart(2, "0");
1520
+ return t;
1521
+ }
1522
+ function Z(e) {
1523
+ let t;
1524
+ try {
1525
+ t = e.initData ? p(e.initData) : void 0;
1526
+ } catch {
1527
+ t = void 0;
1528
+ }
1529
+ return e.packaging === "cmaf" && e.initData && t ? {
1530
+ container: {
1531
+ kind: "cmaf",
1532
+ init: e.initData
1533
+ },
1534
+ description: void 0
1535
+ } : {
1536
+ container: { kind: "legacy" },
1537
+ description: t ? he(t) : void 0
1538
+ };
1539
+ }
1540
+ function ge(e) {
1541
+ if (!e.codec) return;
1542
+ let { container: t, description: n } = Z(e);
1543
+ return {
1544
+ codec: e.codec,
1545
+ container: t,
1546
+ description: n,
1547
+ codedWidth: e.width == null ? void 0 : s(e.width),
1548
+ codedHeight: e.height == null ? void 0 : s(e.height),
1549
+ framerate: e.framerate,
1550
+ bitrate: e.bitrate == null ? void 0 : s(e.bitrate),
1551
+ jitter: e.jitter == null ? void 0 : s(e.jitter)
1552
+ };
1553
+ }
1554
+ function _e(e) {
1555
+ if (!e.codec) return;
1556
+ let t = (() => {
1557
+ if (!e.channelConfig) return X;
1558
+ let t = Number.parseInt(e.channelConfig, 10);
1559
+ return Number.isFinite(t) ? t : X;
1560
+ })(), { container: n, description: r } = Z(e);
1561
+ return {
1562
+ codec: e.codec,
1563
+ container: n,
1564
+ description: r,
1565
+ sampleRate: s(e.samplerate ?? me),
1566
+ numberOfChannels: s(t),
1567
+ bitrate: e.bitrate == null ? void 0 : s(e.bitrate),
1568
+ jitter: e.jitter == null ? void 0 : s(e.jitter)
1569
+ };
1570
+ }
1571
+ function Q(e) {
1572
+ let t = {}, n = {};
1573
+ for (let r of e.tracks) if (r.role === "video") {
1574
+ let e = ge(r);
1575
+ e && (t[r.name] = e);
1576
+ } else if (r.role === "audio") {
1577
+ let e = _e(r);
1578
+ e && (n[r.name] = e);
1579
+ }
1580
+ let r = {};
1581
+ return Object.keys(t).length > 0 && (r.video = { renditions: t }), Object.keys(n).length > 0 && (r.audio = { renditions: n }), r;
1582
+ }
1583
+ //#endregion
1584
+ //#region src/broadcast.ts
1585
+ var $ = [
1586
+ ...o.FORMATS,
1587
+ "hangz",
1588
+ "manual"
1589
+ ];
1590
+ function ve(e) {
1591
+ if (e !== null) return $.find((t) => t === e);
1592
+ }
1593
+ var ye = class {
1594
+ connection;
1595
+ enabled;
1596
+ name;
1597
+ status = new a("offline");
1598
+ reload;
1599
+ catalogFormat;
1600
+ #e = new a(void 0);
1601
+ active = this.#e;
1602
+ catalog;
1603
+ #t;
1604
+ #n = new a(!1);
1605
+ signals = new i();
1606
+ constructor(e) {
1607
+ this.connection = a.from(e?.connection), this.name = a.from(e?.name ?? n.empty()), this.enabled = a.from(e?.enabled ?? !1), this.reload = a.from(e?.reload ?? !1), this.catalogFormat = a.from(e?.catalogFormat), this.catalog = a.from(e?.catalog), this.#t = e?.announced ?? new a(/* @__PURE__ */ new Set()), this.signals.run(this.#r.bind(this)), this.signals.run(this.#i.bind(this)), this.signals.run(this.#a.bind(this));
1608
+ }
1609
+ #r(e) {
1610
+ if (!e.get(this.reload)) {
1611
+ this.#n.set(!0);
1612
+ return;
1613
+ }
1614
+ if (e.get(this.connection)?.url.hostname.endsWith("mediaoverquic.com")) {
1615
+ console.warn("Cloudflare relay does not support broadcast discovery yet; ignoring reload signal."), this.#n.set(!0);
1616
+ return;
1617
+ }
1618
+ let t = e.get(this.name), n = e.get(this.#t);
1619
+ this.#n.set(n.has(t));
1620
+ }
1621
+ #i(e) {
1622
+ if (!e.get(this.enabled) || !e.get(this.#n)) return;
1623
+ let t = e.get(this.connection);
1624
+ if (!t) return;
1625
+ let n = e.get(this.name), r = t.consume(n);
1626
+ e.cleanup(() => r.close()), e.set(this.#e, r, void 0);
1627
+ }
1628
+ #a(e) {
1629
+ if (!e.get(this.enabled)) return;
1630
+ let t = e.get(this.catalogFormat), n = e.get(this.name), r = t ?? o.detectFormat(n) ?? o.DEFAULT_FORMAT;
1631
+ if (r === "manual") {
1632
+ let t = e.get(this.catalog);
1633
+ this.status.set(t ? "live" : "loading");
1634
+ return;
1635
+ }
1636
+ let i = e.get(this.active);
1637
+ if (!i) return;
1638
+ this.status.set("loading");
1639
+ let a = r === "hang" ? o.TRACK : r === "hangz" ? o.TRACK_COMPRESSED : "catalog", s = i.subscribe(a, o.PRIORITY.catalog);
1640
+ e.cleanup(() => s.close());
1641
+ let c;
1642
+ if (r === "hang" || r === "hangz") {
1643
+ let e = new o.Consumer(s, { compression: r === "hangz" });
1644
+ c = () => e.next();
1645
+ } else c = async () => {
1646
+ let e = await u.fetch(s);
1647
+ return e ? Q(e) : void 0;
1648
+ };
1649
+ e.spawn(async () => {
1650
+ try {
1651
+ for (;;) {
1652
+ let t = await Promise.race([e.cancel, c()]);
1653
+ if (!t) break;
1654
+ console.debug("received catalog", r, this.name.peek(), t), this.catalog.set(t), this.status.set("live");
1655
+ }
1656
+ } catch (e) {
1657
+ console.warn("error fetching catalog", this.name.peek(), e);
1658
+ } finally {
1659
+ this.catalog.set(void 0), this.status.set("offline");
1660
+ }
1661
+ });
1662
+ }
1663
+ subscribeTrack(e, t, n) {
1664
+ let r = new i();
1665
+ return r.run((r) => {
1666
+ let i = r.get(this.active);
1667
+ if (!i) return;
1668
+ let a = i.subscribe(e, t);
1669
+ r.cleanup(() => a.close()), n(a, r);
1670
+ }), this.signals.cleanup(() => r.close()), () => r.close();
1671
+ }
1672
+ close() {
1673
+ this.signals.close();
1674
+ }
1675
+ };
1676
+ //#endregion
1677
+ export { ue as a, N as c, pe as i, $ as n, R as o, ve as r, L as s, ye as t };
1678
+
1679
+ //# sourceMappingURL=broadcast-oQKyLEQ1.js.map