@moq/watch 0.3.1 → 0.4.0

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 (73) hide show
  1. package/README.md +1 -2
  2. package/audio/decoder.d.ts +25 -15
  3. package/audio/decoder.d.ts.map +1 -1
  4. package/audio/emitter.d.ts +13 -10
  5. package/audio/emitter.d.ts.map +1 -1
  6. package/audio/index.d.ts +0 -2
  7. package/audio/index.d.ts.map +1 -1
  8. package/audio/source.d.ts +21 -17
  9. package/audio/source.d.ts.map +1 -1
  10. package/audio/unlock.d.ts +20 -0
  11. package/audio/unlock.d.ts.map +1 -0
  12. package/audio/unlock.test.d.ts +2 -0
  13. package/audio/unlock.test.d.ts.map +1 -0
  14. package/broadcast.d.ts +27 -57
  15. package/broadcast.d.ts.map +1 -1
  16. package/element.d.ts +42 -12
  17. package/element.d.ts.map +1 -1
  18. package/element.js +146 -90
  19. package/element.js.map +1 -1
  20. package/index.d.ts +9 -6
  21. package/index.d.ts.map +1 -1
  22. package/index.js +24 -5
  23. package/index.js.map +1 -0
  24. package/package.json +5 -6
  25. package/source-CWtgjSC_.js +1359 -0
  26. package/source-CWtgjSC_.js.map +1 -0
  27. package/support/element.d.ts.map +1 -1
  28. package/support/element.js.map +1 -1
  29. package/support/index.d.ts +3 -3
  30. package/support/index.d.ts.map +1 -1
  31. package/support/index.js +18 -17
  32. package/support/index.js.map +1 -1
  33. package/sync-zdwVEj9u.js +129 -0
  34. package/sync-zdwVEj9u.js.map +1 -0
  35. package/sync.d.ts +19 -18
  36. package/sync.d.ts.map +1 -1
  37. package/ui/components/buffer-control.d.ts +1 -1
  38. package/ui/components/buffer-control.d.ts.map +1 -1
  39. package/ui/components/fullscreen-button.d.ts +1 -2
  40. package/ui/components/fullscreen-button.d.ts.map +1 -1
  41. package/ui/components/play-pause.d.ts +1 -1
  42. package/ui/components/play-pause.d.ts.map +1 -1
  43. package/ui/element.d.ts.map +1 -1
  44. package/ui/element.js +269 -265
  45. package/ui/element.js.map +1 -1
  46. package/ui/fullscreen.d.ts +1 -2
  47. package/ui/fullscreen.d.ts.map +1 -1
  48. package/video/decoder.d.ts +32 -16
  49. package/video/decoder.d.ts.map +1 -1
  50. package/video/index.d.ts +0 -2
  51. package/video/index.d.ts.map +1 -1
  52. package/video/renderer.d.ts +14 -17
  53. package/video/renderer.d.ts.map +1 -1
  54. package/video/source.d.ts +23 -20
  55. package/video/source.d.ts.map +1 -1
  56. package/audio/backend.d.ts +0 -26
  57. package/audio/backend.d.ts.map +0 -1
  58. package/audio/mse.d.ts +0 -22
  59. package/audio/mse.d.ts.map +0 -1
  60. package/backend.d.ts +0 -65
  61. package/backend.d.ts.map +0 -1
  62. package/broadcast-C2qofUBv.js +0 -1701
  63. package/broadcast-C2qofUBv.js.map +0 -1
  64. package/buffered.d.ts +0 -19
  65. package/buffered.d.ts.map +0 -1
  66. package/mse.d.ts +0 -19
  67. package/mse.d.ts.map +0 -1
  68. package/sync-D67IxmxJ.js +0 -128
  69. package/sync-D67IxmxJ.js.map +0 -1
  70. package/video/backend.d.ts +0 -25
  71. package/video/backend.d.ts.map +0 -1
  72. package/video/mse.d.ts +0 -23
  73. package/video/mse.d.ts.map +0 -1
@@ -1,1701 +0,0 @@
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 __export = (target, all) => {\n for (var name in all)\n __defProp(target, name, { get: all[name], enumerable: true });\n};\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// 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 Promise.race([a.audioWorklet.addModule(D), e.cancel]), 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
- if (e.codec === "mp3") {
728
- let t = e.sampleRate >= 32e3 ? 1152 : 576;
729
- return Math.ceil(t / e.sampleRate * 1e3);
730
- }
731
- }
732
- //#endregion
733
- //#region src/audio/index.ts
734
- var L = /* @__PURE__ */ f({
735
- Decoder: () => O,
736
- Emitter: () => M,
737
- Mse: () => P,
738
- Source: () => F
739
- }), R = /* @__PURE__ */ f({ Muxer: () => z }), z = class {
740
- element;
741
- paused;
742
- #e;
743
- #t = new a(void 0);
744
- mediaSource = this.#t;
745
- #n = new i();
746
- constructor(e, t) {
747
- 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));
748
- }
749
- #r(e) {
750
- let t = e.get(this.element);
751
- if (!t) return;
752
- let n = new MediaSource();
753
- t.src = URL.createObjectURL(n), e.cleanup(() => URL.revokeObjectURL(t.src)), e.event(n, "sourceopen", () => {
754
- e.set(this.#t, n);
755
- }, { once: !0 }), e.event(n, "error", (e) => {
756
- console.error("[MSE] MediaSource error event:", e);
757
- });
758
- }
759
- #i(e) {
760
- let t = e.get(this.element);
761
- if (!t || e.get(this.paused)) return;
762
- let n = r.Milli.toSecond(e.get(this.#e.buffer));
763
- e.interval(() => {
764
- let e = t.buffered;
765
- if (e.length === 0) return;
766
- let r = e.end(e.length - 1) - n, i = r - t.currentTime;
767
- (i > .1 || i < -.1) && (console.warn("seeking", i > 0 ? "forward" : "backward", Math.abs(i).toFixed(3), "seconds"), t.currentTime = r);
768
- }, 100);
769
- }
770
- #a(e) {
771
- let t = e.get(this.element);
772
- if (!t) return;
773
- let n = e.get(this.mediaSource);
774
- n && e.interval(() => {
775
- for (let e of n.sourceBuffers) e.updating || t.currentTime > 10 && e.remove(0, t.currentTime - 10);
776
- }, 1e3);
777
- }
778
- #o(e) {
779
- let t = e.get(this.element);
780
- if (!t) return;
781
- let n = e.get(this.paused);
782
- n && !t.paused ? t.pause() : !n && t.paused && t.play().catch((e) => {
783
- console.error("[MSE] MediaElement play error:", e);
784
- });
785
- }
786
- #s(e) {
787
- let t = e.get(this.element);
788
- if (!t || e.get(this.paused)) return;
789
- let n = e.get(this.#e.reference);
790
- if (n === void 0) return;
791
- let i = e.get(this.#e.buffer), a = r.Milli.sub(r.Milli.sub(r.Milli.now(), n), i);
792
- t.currentTime = r.Milli.toSecond(a);
793
- }
794
- close() {
795
- this.#n.close();
796
- }
797
- }, B = 500, V = 100, H = class {
798
- enabled;
799
- source;
800
- #e = new a(void 0);
801
- #t = new a(void 0);
802
- frame = this.#t;
803
- #n = new a(void 0);
804
- timestamp = this.#n;
805
- #r = new a(void 0);
806
- display = this.#r;
807
- #i = new a(!1);
808
- stalled = this.#i;
809
- #a = new a(void 0);
810
- stats = this.#a;
811
- #o = new a([]);
812
- buffered = this.#o;
813
- #s = new i();
814
- #c() {
815
- this.#t.update((e) => {
816
- e?.close();
817
- }), this.#n.set(void 0);
818
- }
819
- constructor(e, t) {
820
- 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));
821
- }
822
- #l(e) {
823
- let t = e.getAll([
824
- this.enabled,
825
- this.source.broadcast,
826
- this.source.track,
827
- this.source.config
828
- ]);
829
- if (!t) {
830
- this.#e.set(void 0);
831
- return;
832
- }
833
- let [n, r, i, a] = t, o = e.get(r.active);
834
- if (!o) {
835
- this.#e.set(void 0), this.#c(), this.#o.set([]);
836
- return;
837
- }
838
- let s = new U({
839
- source: this.source,
840
- broadcast: o,
841
- track: i,
842
- config: a,
843
- stats: this.#a
844
- });
845
- e.cleanup(() => s?.close()), e.run((e) => {
846
- if (!s) return;
847
- let t = e.get(this.#e);
848
- if (t) {
849
- let n = e.get(s.timestamp), r = e.get(t.timestamp);
850
- if (!n || r && r > n + V) return;
851
- }
852
- this.#e.set(s), s = void 0, e.close();
853
- });
854
- }
855
- #u(e) {
856
- let t = e.get(this.#e);
857
- if (!t) {
858
- this.#o.set([]);
859
- return;
860
- }
861
- e.cleanup(() => t.close()), e.run((e) => {
862
- let n = e.get(t.frame);
863
- this.#t.update((e) => (e?.close(), n?.clone()));
864
- }), e.proxy(this.#n, t.timestamp), e.proxy(this.#o, t.buffered);
865
- }
866
- #d(e) {
867
- let t = e.get(this.source.catalog);
868
- if (!t) return;
869
- let n = t.display;
870
- if (n) {
871
- e.set(this.#r, {
872
- width: n.width,
873
- height: n.height
874
- });
875
- return;
876
- }
877
- let r = e.get(this.frame);
878
- r && e.set(this.#r, {
879
- width: r.displayWidth,
880
- height: r.displayHeight
881
- });
882
- }
883
- #f(e) {
884
- if (e.get(this.enabled)) {
885
- if (!e.get(this.frame)) {
886
- this.#i.set(!0);
887
- return;
888
- }
889
- this.#i.set(!1), e.timer(() => {
890
- this.#i.set(!0);
891
- }, B);
892
- }
893
- }
894
- close() {
895
- this.#c(), this.#s.close();
896
- }
897
- }, U = class {
898
- source;
899
- broadcast;
900
- track;
901
- config;
902
- stats;
903
- timestamp = new a(void 0);
904
- frame = new a(void 0);
905
- buffered = new a([]);
906
- #e = new a([]);
907
- #t = 0;
908
- signals = new i();
909
- constructor(e) {
910
- let { codedWidth: t, codedHeight: n, ...r } = e.config;
911
- 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));
912
- }
913
- #n(e) {
914
- let t = this.broadcast.subscribe(this.track, o.PRIORITY.video);
915
- e.cleanup(() => t.close());
916
- let n = new VideoDecoder({
917
- output: async (t) => {
918
- try {
919
- let n = this.#t, i = r.Milli.fromMicro(t.timestamp);
920
- if (i < (this.timestamp.peek() ?? 0)) return;
921
- this.frame.peek() === void 0 && this.frame.set(t.clone());
922
- let a = this.source.sync.wait(i).then(() => !0);
923
- if (!await Promise.race([a, e.cancel]) || n !== this.#t || i < (this.timestamp.peek() ?? 0)) return;
924
- this.timestamp.set(i), this.#s(i), this.frame.update((e) => (e?.close(), t.clone()));
925
- } finally {
926
- t.close();
927
- }
928
- },
929
- error: (t) => {
930
- console.error(t), e.close();
931
- }
932
- });
933
- e.cleanup(() => {
934
- n.state !== "closed" && n.close();
935
- }), this.config.container.kind === "cmaf" ? this.#i(e, t, n) : this.#r(e, t, n);
936
- }
937
- #r(e, t, n) {
938
- let i = this.config.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), a = new c.Consumer(t, {
939
- format: i,
940
- latency: this.source.sync.buffer
941
- });
942
- e.cleanup(() => a.close()), e.run((e) => {
943
- let t = e.get(a.buffered), n = e.get(this.#e);
944
- this.buffered.update(() => c.mergeBufferedRanges(t, n));
945
- }), n.configure({
946
- ...this.config,
947
- description: this.config.description ? l.Hex.toBytes(this.config.description) : void 0,
948
- optimizeForLatency: this.config.optimizeForLatency ?? !0,
949
- flip: !1
950
- });
951
- let o;
952
- e.spawn(async () => {
953
- for (;;) {
954
- let e = await a.next();
955
- if (!e) break;
956
- this.#a(e.discontinuity) && (o = void 0);
957
- let { frame: t, group: i } = e;
958
- if (!t) {
959
- o && (o.final = !0);
960
- continue;
961
- }
962
- let s = r.Milli.fromMicro(t.timestamp);
963
- this.source.sync.received(s, "video");
964
- let c = new EncodedVideoChunk({
965
- type: t.keyframe ? "key" : "delta",
966
- data: t.data,
967
- timestamp: t.timestamp
968
- });
969
- this.stats.update((e) => ({
970
- frameCount: (e?.frameCount ?? 0) + 1,
971
- bytesReceived: (e?.bytesReceived ?? 0) + t.data.byteLength
972
- }));
973
- let l = o;
974
- if (l && (l.group === i || l.final && l.group + 1 === i)) {
975
- let e = r.Milli.fromMicro(l.timestamp), n = r.Milli.fromMicro(t.timestamp);
976
- this.#o(e, n);
977
- }
978
- o = {
979
- timestamp: t.timestamp,
980
- group: i,
981
- final: !1
982
- }, n.decode(c);
983
- }
984
- });
985
- }
986
- #i(e, t, n) {
987
- if (this.config.container.kind !== "cmaf") return;
988
- 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, {
989
- format: new c.Cmaf.Format(a),
990
- latency: this.source.sync.buffer
991
- });
992
- e.cleanup(() => s.close()), e.run((e) => {
993
- let t = e.get(s.buffered), n = e.get(this.#e);
994
- this.buffered.update(() => c.mergeBufferedRanges(t, n));
995
- }), n.configure({
996
- codec: this.config.codec,
997
- description: o,
998
- optimizeForLatency: this.config.optimizeForLatency ?? !0,
999
- flip: !1
1000
- });
1001
- let u;
1002
- e.spawn(async () => {
1003
- for (;;) {
1004
- let e = await s.next();
1005
- if (!e) break;
1006
- this.#a(e.discontinuity) && (u = void 0);
1007
- let { frame: t, group: i } = e;
1008
- if (!t) {
1009
- u && (u.final = !0);
1010
- continue;
1011
- }
1012
- let a = r.Milli.fromMicro(t.timestamp);
1013
- this.source.sync.received(a, "video"), this.stats.update((e) => ({
1014
- frameCount: (e?.frameCount ?? 0) + 1,
1015
- bytesReceived: (e?.bytesReceived ?? 0) + t.data.byteLength
1016
- }));
1017
- let o = u;
1018
- if (o && (o.group === i || o.final && o.group + 1 === i)) {
1019
- let e = r.Milli.fromMicro(o.timestamp), n = r.Milli.fromMicro(t.timestamp);
1020
- this.#o(e, n);
1021
- }
1022
- if (u = {
1023
- timestamp: t.timestamp,
1024
- group: i,
1025
- final: !1
1026
- }, n.state === "closed") break;
1027
- n.decode(new EncodedVideoChunk({
1028
- type: t.keyframe ? "key" : "delta",
1029
- data: t.data,
1030
- timestamp: t.timestamp
1031
- }));
1032
- }
1033
- });
1034
- }
1035
- #a(e) {
1036
- return e === this.#t ? !1 : (this.#t = e, this.timestamp.set(void 0), this.#e.set([]), this.source.sync.reset(), !0);
1037
- }
1038
- #o(e, t) {
1039
- e > t || this.#e.mutate((n) => {
1040
- for (let i of n) if (i.start <= t && i.end >= e) {
1041
- i.start = r.Milli.min(i.start, e), i.end = r.Milli.max(i.end, t);
1042
- return;
1043
- }
1044
- n.push({
1045
- start: e,
1046
- end: t
1047
- }), n.sort((e, t) => e.start - t.start);
1048
- });
1049
- }
1050
- #s(e) {
1051
- this.#e.mutate((t) => {
1052
- for (; t.length > 0;) {
1053
- if (t[0].end >= e) {
1054
- t[0].start = r.Milli.max(t[0].start, e);
1055
- break;
1056
- }
1057
- t.shift();
1058
- }
1059
- });
1060
- }
1061
- close() {
1062
- this.signals.close(), this.frame.update((e) => {
1063
- e?.close();
1064
- });
1065
- }
1066
- };
1067
- async function W(e) {
1068
- let t;
1069
- if (e.description) t = l.Hex.toBytes(e.description);
1070
- else if (e.container.kind === "cmaf") try {
1071
- t = c.Cmaf.decodeInitSegment(p(e.container.init)).description;
1072
- } catch (t) {
1073
- return console.warn(`video: malformed CMAF init segment for codec ${e.codec}`, t), !1;
1074
- }
1075
- let { supported: n } = await VideoDecoder.isConfigSupported({
1076
- codec: e.codec,
1077
- description: t,
1078
- optimizeForLatency: e.optimizeForLatency ?? !0
1079
- });
1080
- if (n) return !0;
1081
- if (e.codec.startsWith("avc3.")) {
1082
- let n = `avc1.${e.codec.slice(5)}`;
1083
- if ((await VideoDecoder.isConfigSupported({
1084
- codec: n,
1085
- description: t,
1086
- optimizeForLatency: e.optimizeForLatency ?? !0
1087
- })).supported) return e.codec = n, !0;
1088
- }
1089
- return !1;
1090
- }
1091
- //#endregion
1092
- //#region src/video/mse.ts
1093
- var G = class {
1094
- muxer;
1095
- source;
1096
- #e = new a(void 0);
1097
- stats = this.#e;
1098
- #t = new a([]);
1099
- buffered = this.#t;
1100
- #n = new a(!1);
1101
- stalled = this.#n;
1102
- #r = new a(t.Time.Milli.zero);
1103
- timestamp = this.#r;
1104
- signals = new i();
1105
- constructor(e, t) {
1106
- 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));
1107
- }
1108
- #i(e) {
1109
- let t = e.get(this.muxer.element);
1110
- if (!t) return;
1111
- let n = e.get(this.muxer.mediaSource);
1112
- if (!n) return;
1113
- let r = e.get(this.source.broadcast);
1114
- if (!r) return;
1115
- let i = e.get(r.active);
1116
- if (!i) return;
1117
- let a = e.get(this.source.track);
1118
- if (!a) return;
1119
- let o = e.get(this.source.config);
1120
- if (!o) return;
1121
- let s = `video/mp4; codecs="${o.codec}"`, c = n.addSourceBuffer(s);
1122
- e.cleanup(() => {
1123
- n.removeSourceBuffer(c), c.abort();
1124
- }), e.event(c, "error", (e) => {
1125
- console.error("[MSE] SourceBuffer error:", e);
1126
- }), e.event(c, "updateend", () => {
1127
- this.#t.set(N(c.buffered));
1128
- }), o.container.kind === "cmaf" ? this.#o(e, i, a, o, c, t) : this.#s(e, i, a, o, c, t);
1129
- }
1130
- async #a(e, t) {
1131
- for (; e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
1132
- for (e.appendBuffer(t); e.updating;) await new Promise((t) => e.addEventListener("updateend", t, { once: !0 }));
1133
- }
1134
- #o(e, n, r, i, a, s) {
1135
- if (i.container.kind !== "cmaf") throw Error("unreachable");
1136
- let l = n.subscribe(r, o.PRIORITY.video);
1137
- e.cleanup(() => l.close());
1138
- let u = p(i.container.init), d = c.Cmaf.decodeInitSegment(u);
1139
- e.spawn(async () => {
1140
- for (await this.#a(a, u);;) {
1141
- let e = await l.readFrame();
1142
- if (!e) return;
1143
- let n = c.Cmaf.decodeTimestamp(e, d);
1144
- 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));
1145
- }
1146
- });
1147
- }
1148
- #s(e, n, r, i, a, s) {
1149
- let l = n.subscribe(r, o.PRIORITY.video);
1150
- e.cleanup(() => l.close());
1151
- let u = i.container.kind === "loc" ? new c.Loc.Format() : new c.Legacy.Format(), d = new c.Consumer(l, {
1152
- format: u,
1153
- latency: this.source.sync.buffer
1154
- });
1155
- e.cleanup(() => d.close()), e.spawn(async () => {
1156
- let e = c.Cmaf.createVideoInitSegment(i);
1157
- await this.#a(a, e);
1158
- let n = 1, r, o;
1159
- for (;;) {
1160
- let e = await d.next();
1161
- if (!e) return;
1162
- if (!e.frame) continue;
1163
- o = e.frame;
1164
- let n = t.Time.Milli.fromMicro(o.timestamp);
1165
- this.source.sync.received(n, "video");
1166
- break;
1167
- }
1168
- for (;;) {
1169
- let e = await d.next();
1170
- if (e && !e.frame) continue;
1171
- let i = e?.frame;
1172
- if (i) {
1173
- r = t.Time.Micro.sub(i.timestamp, o.timestamp);
1174
- let e = t.Time.Milli.fromMicro(i.timestamp);
1175
- this.source.sync.received(e, "video");
1176
- }
1177
- let l = c.Cmaf.encodeDataSegment({
1178
- data: o.data,
1179
- timestamp: o.timestamp,
1180
- duration: r ?? 0,
1181
- keyframe: o.keyframe,
1182
- sequence: n++
1183
- });
1184
- if (await this.#a(a, l), s.buffered.length > 0 && s.currentTime < s.buffered.start(0) && (s.currentTime = s.buffered.start(0)), !i) return;
1185
- o = i;
1186
- }
1187
- });
1188
- }
1189
- #c(e) {
1190
- let t = e.get(this.muxer.element);
1191
- if (!t) return;
1192
- let n = () => {
1193
- this.#n.set(t.readyState <= HTMLMediaElement.HAVE_CURRENT_DATA);
1194
- };
1195
- n(), e.event(t, "waiting", n), e.event(t, "playing", n), e.event(t, "seeking", n);
1196
- }
1197
- #l(e) {
1198
- let n = e.get(this.muxer.element);
1199
- if (n) if ("requestVideoFrameCallback" in n) {
1200
- let r = n, i, a = () => {
1201
- let e = t.Time.Milli.fromSecond(r.currentTime);
1202
- this.#r.set(e), i = r.requestVideoFrameCallback(a);
1203
- };
1204
- i = r.requestVideoFrameCallback(a), e.cleanup(() => r.cancelVideoFrameCallback(i));
1205
- } else e.event(n, "timeupdate", () => {
1206
- let e = t.Time.Milli.fromSecond(n.currentTime);
1207
- this.#r.set(e);
1208
- });
1209
- }
1210
- close() {
1211
- this.source.close(), this.signals.close();
1212
- }
1213
- };
1214
- async function K(e) {
1215
- return MediaSource.isTypeSupported(`video/mp4; codecs="${e.codec}"`);
1216
- }
1217
- //#endregion
1218
- //#region src/video/renderer.ts
1219
- var q = .01, J = class {
1220
- decoder;
1221
- canvas;
1222
- paused;
1223
- visible;
1224
- frame = new a(void 0);
1225
- timestamp = new a(void 0);
1226
- #e = new a(void 0);
1227
- #t = new a(!1);
1228
- #n = new i();
1229
- constructor(e, t) {
1230
- this.decoder = e, this.canvas = a.from(t?.canvas), this.paused = a.from(t?.paused ?? !1), this.visible = a.from(t?.visible ?? "20%"), this.#n.run((e) => {
1231
- let t = e.get(this.canvas);
1232
- this.#e.set(t?.getContext("2d") ?? void 0);
1233
- }), 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));
1234
- }
1235
- #r(e) {
1236
- let t = e.getAll([this.canvas, this.decoder.display]);
1237
- if (!t) return;
1238
- let [n, r] = t;
1239
- (n.width !== r.width || n.height !== r.height) && (n.width = r.width, n.height = r.height);
1240
- }
1241
- #i(e) {
1242
- let t = e.get(this.visible);
1243
- if (t === "never") {
1244
- this.#t.set(!1);
1245
- return;
1246
- }
1247
- if (t === "always") {
1248
- this.#t.set(!0), e.cleanup(() => this.#t.set(!1));
1249
- return;
1250
- }
1251
- let n = e.get(this.canvas);
1252
- if (!n) {
1253
- this.#t.set(!1);
1254
- return;
1255
- }
1256
- let r = !1, i = () => {
1257
- this.#t.set(r && !document.hidden);
1258
- }, a = (e) => {
1259
- for (let t of e) r = t.isIntersecting, i();
1260
- }, o;
1261
- try {
1262
- o = new IntersectionObserver(a, {
1263
- threshold: q,
1264
- rootMargin: t
1265
- });
1266
- } catch {
1267
- console.warn(`moq-watch: invalid visible margin "${t}", using "0px"`), o = new IntersectionObserver(a, { threshold: q });
1268
- }
1269
- i(), e.event(document, "visibilitychange", i), o.observe(n), e.cleanup(() => o.disconnect()), e.cleanup(() => this.#t.set(!1));
1270
- }
1271
- #a(e) {
1272
- let t = e.get(this.paused), n = e.get(this.#t);
1273
- if (e.cleanup(() => this.decoder.enabled.set(!1)), !t) {
1274
- this.decoder.enabled.set(n);
1275
- return;
1276
- }
1277
- let r = e.get(this.decoder.frame);
1278
- this.decoder.enabled.set(!r);
1279
- }
1280
- #o(e) {
1281
- let t = e.get(this.#e);
1282
- if (!t) return;
1283
- let n = e.get(this.decoder.frame), i = requestAnimationFrame(() => {
1284
- 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) => {
1285
- e?.close();
1286
- }), this.timestamp.set(void 0)), i = void 0;
1287
- });
1288
- e.cleanup(() => {
1289
- i && cancelAnimationFrame(i);
1290
- });
1291
- }
1292
- #s(e, t) {
1293
- if (!t) {
1294
- e.fillStyle = "#000", e.fillRect(0, 0, e.canvas.width, e.canvas.height);
1295
- return;
1296
- }
1297
- 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();
1298
- }
1299
- close() {
1300
- this.frame.update((e) => {
1301
- e?.close();
1302
- }), this.timestamp.set(void 0), this.#n.close();
1303
- }
1304
- };
1305
- //#endregion
1306
- //#region src/video/source.ts
1307
- function oe(e) {
1308
- return (t) => {
1309
- let n = [], r = [];
1310
- for (let [i, a] of t) if (a.codedWidth && a.codedHeight) {
1311
- let t = a.codedWidth * a.codedHeight;
1312
- t <= e ? n.push({
1313
- name: i,
1314
- size: t
1315
- }) : r.push({
1316
- name: i,
1317
- size: t
1318
- });
1319
- }
1320
- 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);
1321
- };
1322
- }
1323
- function se(e, t) {
1324
- return (n) => {
1325
- let r = [], i = [];
1326
- for (let [a, o] of n) {
1327
- if (!o.codedWidth || !o.codedHeight) continue;
1328
- let n = o.codedWidth * o.codedHeight, s = e == null || o.codedWidth <= e, c = t == null || o.codedHeight <= t;
1329
- s && c ? r.push({
1330
- name: a,
1331
- size: n
1332
- }) : i.push({
1333
- name: a,
1334
- size: n
1335
- });
1336
- }
1337
- 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);
1338
- };
1339
- }
1340
- function ce(e) {
1341
- return (t) => {
1342
- let n = [], r = [];
1343
- for (let [i, a] of t) a.bitrate != null && a.bitrate <= e ? n.push({
1344
- name: i,
1345
- bitrate: a.bitrate
1346
- }) : a.bitrate != null && r.push({
1347
- name: i,
1348
- bitrate: a.bitrate
1349
- });
1350
- 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);
1351
- };
1352
- }
1353
- function le(e) {
1354
- let t = e[0];
1355
- for (let n of e) {
1356
- let [, e] = n, [, r] = t, i = (e.codedWidth ?? 0) * (e.codedHeight ?? 0), a = (r.codedWidth ?? 0) * (r.codedHeight ?? 0);
1357
- if (i !== a) {
1358
- i > a && (t = n);
1359
- continue;
1360
- }
1361
- (e.bitrate ?? 0) > (r.bitrate ?? 0) && (t = n);
1362
- }
1363
- return t[0];
1364
- }
1365
- var Y = class {
1366
- broadcast;
1367
- target;
1368
- catalog;
1369
- #e = new a({});
1370
- available = this.#e;
1371
- #t = new a(void 0);
1372
- error = this.#t;
1373
- #n = new a(void 0);
1374
- track = this.#n;
1375
- #r = new a(void 0);
1376
- config = this.#r;
1377
- sync;
1378
- supported;
1379
- #i = new i();
1380
- constructor(e, t) {
1381
- this.broadcast = a.from(t?.broadcast), this.target = a.from(t?.target), this.sync = e, this.supported = a.from(t?.supported), this.catalog = this.#i.computed((e) => {
1382
- let t = e.get(this.broadcast);
1383
- return t ? e.get(t.catalog)?.video : void 0;
1384
- }), this.#i.run(this.#a.bind(this)), this.#i.run(this.#o.bind(this));
1385
- }
1386
- #a(e) {
1387
- let t = e.get(this.supported);
1388
- if (!t) {
1389
- this.#t.set(void 0);
1390
- return;
1391
- }
1392
- let n = e.get(this.catalog)?.renditions ?? {};
1393
- this.#t.set(void 0), e.spawn(async () => {
1394
- let e = {};
1395
- for (let [r, i] of Object.entries(n)) {
1396
- let n = !1;
1397
- try {
1398
- n = await t(i);
1399
- } catch (e) {
1400
- console.warn(`[Source] video rendition ${r} (${i.codec}) support probe failed; treating as unsupported`, e);
1401
- }
1402
- n && (e[r] = i);
1403
- }
1404
- let r = Object.keys(e).length === 0 && Object.keys(n).length > 0 ? "unsupported" : void 0;
1405
- r === "unsupported" && console.warn("[Source] No supported video renditions found:", n), this.#t.set(r), this.#e.set(e);
1406
- });
1407
- }
1408
- #o(e) {
1409
- let t = e.get(this.#e);
1410
- if (Object.keys(t).length === 0) return;
1411
- let n = e.get(this.target);
1412
- if (n?.name && n.name in t) {
1413
- let r = t[n.name];
1414
- e.set(this.#n, n.name), e.set(this.#r, r), e.set(this.sync.video, r.jitter);
1415
- return;
1416
- }
1417
- let r = n;
1418
- if (!n?.bitrate) {
1419
- let t = e.get(this.broadcast), i = (t ? e.get(t.connection) : void 0)?.recvBandwidth;
1420
- if (i) {
1421
- let t = e.get(i);
1422
- if (t != null) {
1423
- let e = Math.round(t * .8);
1424
- r = {
1425
- ...n,
1426
- bitrate: e
1427
- };
1428
- }
1429
- }
1430
- }
1431
- let i = this.#s(t, r);
1432
- if (!i) return;
1433
- let a = t[i];
1434
- e.set(this.#n, i), e.set(this.#r, a);
1435
- let o = a.jitter ?? (a.framerate ? Math.ceil(1e3 / a.framerate) : void 0);
1436
- e.set(this.sync.video, o);
1437
- }
1438
- #s(e, t) {
1439
- let n = Object.entries(e);
1440
- if (n.length === 0) return;
1441
- if (n.length === 1) return n[0][0];
1442
- let r = [];
1443
- 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);
1444
- let i = r.map((e) => e(n)), a = i.map((e) => new Set(e));
1445
- for (let e of i[0]) if (a.every((t) => t.has(e))) return e;
1446
- console.warn("conflicting rendition filters, no rendition satisfies all criteria");
1447
- }
1448
- close() {
1449
- this.#i.close();
1450
- }
1451
- }, ue = /* @__PURE__ */ f({
1452
- Decoder: () => H,
1453
- Mse: () => G,
1454
- Renderer: () => J,
1455
- Source: () => Y
1456
- }), de = class {
1457
- source;
1458
- stats = new a(void 0);
1459
- stalled = new a(!1);
1460
- buffered = new a([]);
1461
- timestamp = new a(t.Time.Milli.zero);
1462
- constructor(e) {
1463
- this.source = e;
1464
- }
1465
- }, fe = class {
1466
- source;
1467
- volume = new a(.5);
1468
- muted = new a(!1);
1469
- stats = new a(void 0);
1470
- buffered = new a([]);
1471
- context = new a(void 0);
1472
- constructor(e) {
1473
- this.source = e;
1474
- }
1475
- }, pe = class {
1476
- element = new a(void 0);
1477
- broadcast;
1478
- latency;
1479
- jitter;
1480
- buffered;
1481
- paused;
1482
- visible;
1483
- video;
1484
- #e;
1485
- audio;
1486
- #t;
1487
- #n;
1488
- sync;
1489
- signals = new i();
1490
- constructor(t) {
1491
- this.element = a.from(t?.element), this.broadcast = a.from(t?.broadcast), this.sync = new e({
1492
- latency: t?.latency,
1493
- connection: t?.connection
1494
- }), 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 ?? "20%"), this.signals.run(this.#r.bind(this));
1495
- }
1496
- #r(e) {
1497
- let t = e.get(this.element);
1498
- t && (t instanceof HTMLCanvasElement ? this.#i(e, t) : t instanceof HTMLVideoElement && this.#a(e, t));
1499
- }
1500
- #i(e, t) {
1501
- let n = new H(this.#e), r = new O(this.#t);
1502
- this.#n = r;
1503
- let i = new M(r, {
1504
- volume: this.audio.volume,
1505
- muted: this.audio.muted,
1506
- paused: this.paused
1507
- }), a = new J(n, {
1508
- canvas: t,
1509
- paused: this.paused,
1510
- visible: this.visible
1511
- });
1512
- e.cleanup(() => {
1513
- n.close(), r.close(), i.close(), a.close(), this.#n = void 0;
1514
- }), 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);
1515
- }
1516
- #a(e, t) {
1517
- let n = new z(this.sync, {
1518
- paused: this.paused,
1519
- element: t
1520
- }), r = new G(n, this.#e), i = new P(n, this.#t, {
1521
- volume: this.audio.volume,
1522
- muted: this.audio.muted
1523
- });
1524
- e.cleanup(() => {
1525
- r.close(), i.close(), n.close();
1526
- }), 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);
1527
- }
1528
- reset() {
1529
- this.sync.reset(), this.#n?.reset();
1530
- }
1531
- close() {
1532
- this.signals.close(), this.#e.close(), this.#t.close(), this.sync.close();
1533
- }
1534
- }, me = 48e3, X = 2;
1535
- function he(e) {
1536
- let t = "";
1537
- for (let n = 0; n < e.length; n++) t += e[n].toString(16).padStart(2, "0");
1538
- return t;
1539
- }
1540
- function Z(e) {
1541
- let t;
1542
- try {
1543
- t = e.initData ? p(e.initData) : void 0;
1544
- } catch {
1545
- t = void 0;
1546
- }
1547
- return e.packaging === "cmaf" && e.initData && t ? {
1548
- container: {
1549
- kind: "cmaf",
1550
- init: e.initData
1551
- },
1552
- description: void 0
1553
- } : {
1554
- container: { kind: "legacy" },
1555
- description: t ? he(t) : void 0
1556
- };
1557
- }
1558
- function ge(e) {
1559
- if (!e.codec) return;
1560
- let { container: t, description: n } = Z(e);
1561
- return {
1562
- codec: e.codec,
1563
- container: t,
1564
- description: n,
1565
- codedWidth: e.width == null ? void 0 : s(e.width),
1566
- codedHeight: e.height == null ? void 0 : s(e.height),
1567
- framerate: e.framerate,
1568
- bitrate: e.bitrate == null ? void 0 : s(e.bitrate),
1569
- jitter: e.jitter == null ? void 0 : s(e.jitter)
1570
- };
1571
- }
1572
- function _e(e) {
1573
- if (!e.codec) return;
1574
- let t = (() => {
1575
- if (!e.channelConfig) return X;
1576
- let t = Number.parseInt(e.channelConfig, 10);
1577
- return Number.isFinite(t) ? t : X;
1578
- })(), { container: n, description: r } = Z(e);
1579
- return {
1580
- codec: e.codec,
1581
- container: n,
1582
- description: r,
1583
- sampleRate: s(e.samplerate ?? me),
1584
- numberOfChannels: s(t),
1585
- bitrate: e.bitrate == null ? void 0 : s(e.bitrate),
1586
- jitter: e.jitter == null ? void 0 : s(e.jitter)
1587
- };
1588
- }
1589
- function Q(e) {
1590
- let t = {}, n = {};
1591
- for (let r of e.tracks) if (r.role === "video") {
1592
- let e = ge(r);
1593
- e && (t[r.name] = e);
1594
- } else if (r.role === "audio") {
1595
- let e = _e(r);
1596
- e && (n[r.name] = e);
1597
- }
1598
- let r = {};
1599
- return Object.keys(t).length > 0 && (r.video = { renditions: t }), Object.keys(n).length > 0 && (r.audio = { renditions: n }), r;
1600
- }
1601
- //#endregion
1602
- //#region src/broadcast.ts
1603
- var $ = [
1604
- ...o.FORMATS,
1605
- "hangz",
1606
- "manual"
1607
- ];
1608
- function ve(e) {
1609
- if (e !== null) return $.find((t) => t === e);
1610
- }
1611
- var ye = class {
1612
- connection;
1613
- enabled;
1614
- name;
1615
- status = new a("offline");
1616
- reload;
1617
- catalogFormat;
1618
- #e = new a(void 0);
1619
- active = this.#e;
1620
- catalog;
1621
- #t;
1622
- #n = new a(!1);
1623
- signals = new i();
1624
- constructor(e) {
1625
- 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 ?? !0), this.catalogFormat = a.from(e?.catalogFormat), this.catalog = a.from(e?.catalog), this.#t = e?.announced, this.signals.run(this.#r.bind(this)), this.signals.run(this.#i.bind(this)), this.signals.run(this.#a.bind(this));
1626
- }
1627
- #r(e) {
1628
- if (!e.get(this.reload)) {
1629
- this.#n.set(!0);
1630
- return;
1631
- }
1632
- if (!this.#t) {
1633
- this.#n.set(!0);
1634
- return;
1635
- }
1636
- if (e.get(this.connection)?.url.hostname.endsWith("mediaoverquic.com")) {
1637
- this.#n.set(!0);
1638
- return;
1639
- }
1640
- let t = e.get(this.name), n = e.get(this.#t);
1641
- this.#n.set(n.has(t));
1642
- }
1643
- #i(e) {
1644
- if (!e.get(this.enabled) || !e.get(this.#n)) return;
1645
- let t = e.get(this.connection);
1646
- if (!t) return;
1647
- let n = e.get(this.name), r = t.consume(n);
1648
- e.cleanup(() => r.close()), e.set(this.#e, r, void 0);
1649
- }
1650
- #a(e) {
1651
- if (!e.get(this.enabled)) return;
1652
- let t = e.get(this.catalogFormat), n = e.get(this.name), r = t ?? o.detectFormat(n) ?? o.DEFAULT_FORMAT;
1653
- if (r === "manual") {
1654
- let t = e.get(this.catalog);
1655
- this.status.set(t ? "live" : "loading");
1656
- return;
1657
- }
1658
- let i = e.get(this.active);
1659
- if (!i) return;
1660
- this.status.set("loading");
1661
- let a = r === "hang" ? o.TRACK : r === "hangz" ? o.TRACK_COMPRESSED : "catalog", s = i.subscribe(a, o.PRIORITY.catalog);
1662
- e.cleanup(() => s.close());
1663
- let c;
1664
- if (r === "hang" || r === "hangz") {
1665
- let e = new o.Consumer(s, { compression: r === "hangz" });
1666
- c = () => e.next();
1667
- } else c = async () => {
1668
- let e = await u.fetch(s);
1669
- return e ? Q(e) : void 0;
1670
- };
1671
- e.spawn(async () => {
1672
- try {
1673
- for (;;) {
1674
- let t = await Promise.race([e.cancel, c()]);
1675
- if (!t) break;
1676
- console.debug("received catalog", r, this.name.peek(), t), this.catalog.set(t), this.status.set("live");
1677
- }
1678
- } catch (e) {
1679
- console.warn("error fetching catalog", this.name.peek(), e);
1680
- } finally {
1681
- this.catalog.set(void 0), this.status.set("offline");
1682
- }
1683
- });
1684
- }
1685
- subscribeTrack(e, t, n) {
1686
- let r = new i();
1687
- return r.run((r) => {
1688
- let i = r.get(this.active);
1689
- if (!i) return;
1690
- let a = i.subscribe(e, t);
1691
- r.cleanup(() => a.close()), n(a, r);
1692
- }), this.signals.cleanup(() => r.close()), () => r.close();
1693
- }
1694
- close() {
1695
- this.signals.close();
1696
- }
1697
- };
1698
- //#endregion
1699
- export { ue as a, N as c, pe as i, $ as n, R as o, ve as r, L as s, ye as t };
1700
-
1701
- //# sourceMappingURL=broadcast-C2qofUBv.js.map