@avoid.quest/audio 0.0.0-stage → 0.1.1-beta.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.
- package/LICENSE +21 -0
- package/README.md +98 -2
- package/dist/effects/index.d.ts +215 -0
- package/dist/effects/index.js +451 -0
- package/dist/effects/index.js.map +1 -0
- package/dist/errors-BT9HxDLn.js +74 -0
- package/dist/errors-BT9HxDLn.js.map +1 -0
- package/dist/errors-ChTQFwuZ.d.ts +53 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/midi/index.d.ts +138 -0
- package/dist/midi/index.js +302 -0
- package/dist/midi/index.js.map +1 -0
- package/dist/native-Bern4_PB.js +172 -0
- package/dist/native-Bern4_PB.js.map +1 -0
- package/dist/pcm-buffer-DSzGHbon.js +436 -0
- package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
- package/dist/playback/index.d.ts +295 -0
- package/dist/playback/index.js +1209 -0
- package/dist/playback/index.js.map +1 -0
- package/dist/queue/index.d.ts +133 -0
- package/dist/queue/index.js +563 -0
- package/dist/queue/index.js.map +1 -0
- package/dist/recognize/index.d.ts +124 -0
- package/dist/recognize/index.js +273 -0
- package/dist/recognize/index.js.map +1 -0
- package/dist/routing/index.d.ts +109 -0
- package/dist/routing/index.js +555 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/shazam-gBrX1NEY.d.ts +27 -0
- package/dist/sync/index.d.ts +214 -0
- package/dist/sync/index.js +881 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/worklet-loader-BabwPALw.d.ts +41 -0
- package/dist/worklet-loader-f741D1tk.js +160 -0
- package/dist/worklet-loader-f741D1tk.js.map +1 -0
- package/dist/worklets/couch-live.d.ts +1 -0
- package/dist/worklets/couch-live.js +283 -0
- package/dist/worklets/couch-live.js.map +1 -0
- package/dist/worklets/meter.d.ts +7 -0
- package/dist/worklets/meter.js +74 -0
- package/dist/worklets/meter.js.map +1 -0
- package/dist/worklets/pcm-capture.d.ts +6 -0
- package/dist/worklets/pcm-capture.js +52 -0
- package/dist/worklets/pcm-capture.js.map +1 -0
- package/package.json +114 -4
|
@@ -0,0 +1,881 @@
|
|
|
1
|
+
import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-f741D1tk.js";
|
|
2
|
+
import { Effect, Scope } from "effect";
|
|
3
|
+
import { c as AudioSyncError, l as AudioUnsupportedError } from "../errors-BT9HxDLn.js";
|
|
4
|
+
import { a as clampFinite, f as disconnectEdge, m as setParamTarget } from "../native-Bern4_PB.js";
|
|
5
|
+
// src/sync/cca1.ts
|
|
6
|
+
const CCA1_MAGIC = 826360643;
|
|
7
|
+
const CCA1_HEADER_BYTES = 40;
|
|
8
|
+
const CCA1_FORMAT_F32_INTERLEAVED = 1;
|
|
9
|
+
const CCA1_MAX_FRAMES = 4096;
|
|
10
|
+
const CCA1_MAX_PACKET_BYTES = 32808;
|
|
11
|
+
const CCA1_ALLOWED_SAMPLE_RATES = [
|
|
12
|
+
44100,
|
|
13
|
+
48e3,
|
|
14
|
+
96e3
|
|
15
|
+
];
|
|
16
|
+
const CCA1_MAX_CLOCK_RTT_US = 1e5;
|
|
17
|
+
const GENERATION_REGEX = /^[\w-]{1,64}$/u;
|
|
18
|
+
const syncFail = (code, message) => Effect.fail(new AudioSyncError({
|
|
19
|
+
code,
|
|
20
|
+
message
|
|
21
|
+
}));
|
|
22
|
+
function validateCca1Packet(packet) {
|
|
23
|
+
if (!CCA1_ALLOWED_SAMPLE_RATES.includes(packet.sampleRate)) return syncFail("INVALID_HEADER", `Unsupported CCA1 sampleRate: ${String(packet.sampleRate)}.`);
|
|
24
|
+
if (packet.channels !== 1 && packet.channels !== 2) return syncFail("INVALID_HEADER", `Invalid CCA1 channel count: ${String(packet.channels)}.`);
|
|
25
|
+
if (packet.generation !== void 0 && !GENERATION_REGEX.test(packet.generation) || !Number.isSafeInteger(packet.sequence) || packet.sequence < 0 || packet.sequence > 0xffffffff || !Number.isSafeInteger(packet.samplePosition) || packet.samplePosition < 0 || !Number.isSafeInteger(packet.capturedAtUs)) return syncFail("INVALID_HEADER", "Invalid CCA1 generation, sequence, samplePosition, or capturedAtUs.");
|
|
26
|
+
const frames = packet.pcm.length / packet.channels;
|
|
27
|
+
if (packet.pcm.length === 0 || packet.pcm.length % packet.channels !== 0 || frames > 4096) return syncFail("INVALID_FRAME", "Invalid CCA1 PCM frame length.");
|
|
28
|
+
for (let i = 0; i < packet.pcm.length; i += 1) {
|
|
29
|
+
const sample = packet.pcm[i] ?? NaN;
|
|
30
|
+
if (!Number.isFinite(sample) || Math.abs(sample) > 8) return syncFail("INVALID_SAMPLE", `Invalid CCA1 PCM sample at index ${i}.`);
|
|
31
|
+
}
|
|
32
|
+
return Effect.succeed(packet);
|
|
33
|
+
}
|
|
34
|
+
function encodeCca1Frame(packet) {
|
|
35
|
+
return validateCca1Packet(packet).pipe(Effect.map((valid) => {
|
|
36
|
+
const out = new Uint8Array(40 + valid.pcm.length * 4);
|
|
37
|
+
const view = new DataView(out.buffer);
|
|
38
|
+
view.setUint32(0, CCA1_MAGIC, true);
|
|
39
|
+
view.setUint8(4, valid.channels);
|
|
40
|
+
view.setUint8(5, 1);
|
|
41
|
+
view.setUint16(6, 40, true);
|
|
42
|
+
view.setUint32(8, valid.sampleRate, true);
|
|
43
|
+
view.setUint32(12, valid.sequence, true);
|
|
44
|
+
view.setBigUint64(16, BigInt(valid.samplePosition), true);
|
|
45
|
+
view.setBigInt64(24, BigInt(valid.capturedAtUs), true);
|
|
46
|
+
view.setUint32(32, valid.pcm.length / valid.channels, true);
|
|
47
|
+
view.setUint32(36, 0, true);
|
|
48
|
+
for (let i = 0; i < valid.pcm.length; i += 1) view.setFloat32(40 + i * 4, valid.pcm[i] ?? 0, true);
|
|
49
|
+
return out;
|
|
50
|
+
}));
|
|
51
|
+
}
|
|
52
|
+
function decodeCca1Frame(data, options = {}) {
|
|
53
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
54
|
+
if (bytes.byteLength < 44 || bytes.byteLength > 32808) return syncFail("INVALID_FRAME", `CCA1 frame length ${bytes.byteLength} is out of bounds.`);
|
|
55
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
56
|
+
const payloadBytes = bytes.byteLength - 40;
|
|
57
|
+
if (payloadBytes % 4 !== 0) return syncFail("INVALID_FRAME", "CCA1 PCM payload is not 4-byte aligned.");
|
|
58
|
+
const channels = view.getUint8(4);
|
|
59
|
+
const sampleCount = payloadBytes / 4;
|
|
60
|
+
if (view.getUint32(0, true) !== 826360643 || view.getUint8(5) !== 1 || view.getUint16(6, true) !== 40 || view.getUint32(36, true) !== 0 || channels !== 1 && channels !== 2) return syncFail("INVALID_HEADER", "Invalid CCA1 binary header.");
|
|
61
|
+
if (view.getUint32(32, true) !== sampleCount / channels) return syncFail("INVALID_HEADER", "CCA1 header frame count does not match PCM payload length.");
|
|
62
|
+
const pcm = new Float32Array(sampleCount);
|
|
63
|
+
for (let i = 0; i < sampleCount; i += 1) pcm[i] = view.getFloat32(40 + i * 4, true);
|
|
64
|
+
return validateCca1Packet({
|
|
65
|
+
capturedAtUs: Math.round(Number(view.getBigInt64(24, true)) + (options.clockOffsetUs ?? 0)),
|
|
66
|
+
channels,
|
|
67
|
+
generation: options.generation,
|
|
68
|
+
pcm,
|
|
69
|
+
samplePosition: Number(view.getBigUint64(16, true)),
|
|
70
|
+
sampleRate: view.getUint32(8, true),
|
|
71
|
+
sequence: view.getUint32(12, true)
|
|
72
|
+
});
|
|
73
|
+
}
|
|
74
|
+
function computeClockHandshake(samples, maxRttUs = CCA1_MAX_CLOCK_RTT_US) {
|
|
75
|
+
let best;
|
|
76
|
+
let bestRtt = Number.POSITIVE_INFINITY;
|
|
77
|
+
for (const sample of samples) {
|
|
78
|
+
const rtt = sample.clientReceivedUs - sample.clientSentUs;
|
|
79
|
+
if (rtt >= 0 && rtt < bestRtt) {
|
|
80
|
+
bestRtt = rtt;
|
|
81
|
+
best = sample;
|
|
82
|
+
}
|
|
83
|
+
}
|
|
84
|
+
if (!best) return syncFail("CLOCK_RTT_EXCEEDED", "Clock handshake requires at least one valid ping sample.");
|
|
85
|
+
if (bestRtt > maxRttUs) return syncFail("CLOCK_RTT_EXCEEDED", `Clock handshake RTT ${bestRtt} µs exceeded max ${maxRttUs} µs.`);
|
|
86
|
+
return Effect.succeed({
|
|
87
|
+
offsetUs: Math.round(best.serverUs - (best.clientReceivedUs + best.clientSentUs) / 2),
|
|
88
|
+
rttUs: bestRtt
|
|
89
|
+
});
|
|
90
|
+
}
|
|
91
|
+
// src/sync/live-need.ts
|
|
92
|
+
const LIVE_STEP_MS = 5;
|
|
93
|
+
const LIVE_LATE_STEP_MS = 10;
|
|
94
|
+
const LIVE_READINGS = 5;
|
|
95
|
+
function liveStep(needMs) {
|
|
96
|
+
return Math.ceil(needMs / 5) * 5;
|
|
97
|
+
}
|
|
98
|
+
/**
|
|
99
|
+
* Computes a monotonically rising buffered need from recent once-a-second readings.
|
|
100
|
+
* Sets immediately on the first reading; subsequently raises only when the median
|
|
101
|
+
* of the last `window` readings exceeds `currentMs + LIVE_STEP_MS`.
|
|
102
|
+
*/
|
|
103
|
+
function risenNeed(currentMs, readingsMs, allowanceMs = 0, window = 5) {
|
|
104
|
+
const recent = readingsMs.slice(-window).toSorted((a, b) => a - b);
|
|
105
|
+
if (recent.length === 0 || currentMs !== void 0 && recent.length < window) return currentMs;
|
|
106
|
+
const mid = recent[Math.floor(recent.length / 2)] ?? 0;
|
|
107
|
+
const need = Math.ceil(mid + allowanceMs);
|
|
108
|
+
return currentMs === void 0 || need > currentMs + 5 ? need : currentMs;
|
|
109
|
+
}
|
|
110
|
+
// src/sync/live-buffer.ts
|
|
111
|
+
const SDK_BATCH_MS = 15;
|
|
112
|
+
const LIMIT_MS = 5e3;
|
|
113
|
+
const SLEW_SECONDS = 10;
|
|
114
|
+
const WINDOW_SECONDS = 10;
|
|
115
|
+
const RUN_SECONDS = 3;
|
|
116
|
+
const APART_SECONDS = 2;
|
|
117
|
+
const HORIZON_SPELLS = 3;
|
|
118
|
+
const MOVING_SECONDS = 3;
|
|
119
|
+
const PAUSE_SECONDS = 24;
|
|
120
|
+
const LONGEST_PAUSE_SECONDS = 384;
|
|
121
|
+
const FORGET_SECONDS = 960;
|
|
122
|
+
const HOUR_SECONDS = 3600;
|
|
123
|
+
const WATCHING = { kind: "watching" };
|
|
124
|
+
const NO_LATE_STEPS = {
|
|
125
|
+
clean: 0,
|
|
126
|
+
counted: 0,
|
|
127
|
+
lateMs: 0,
|
|
128
|
+
phase: WATCHING,
|
|
129
|
+
seconds: [],
|
|
130
|
+
taken: [],
|
|
131
|
+
unhelpful: 0
|
|
132
|
+
};
|
|
133
|
+
const SDK_LATE_STEPS = {
|
|
134
|
+
...NO_LATE_STEPS,
|
|
135
|
+
partMs: 10
|
|
136
|
+
};
|
|
137
|
+
const partPause = (part) => Math.min(LONGEST_PAUSE_SECONDS, PAUSE_SECONDS * 2 ** part);
|
|
138
|
+
const pauseAfter = (unhelpful, stepMs) => {
|
|
139
|
+
let left = 0;
|
|
140
|
+
for (let p = 0; p < stepMs / 10; p += 1) left += partPause(unhelpful + p);
|
|
141
|
+
return Math.min(LONGEST_PAUSE_SECONDS, left);
|
|
142
|
+
};
|
|
143
|
+
const mostMs = (unhelpful) => {
|
|
144
|
+
let parts = 1;
|
|
145
|
+
for (let a = HOUR_SECONDS - partPause(unhelpful); a >= 0; parts += 1) a -= partPause(unhelpful + parts);
|
|
146
|
+
for (let b = HOUR_SECONDS, p = unhelpful - 1; p >= 0; p -= 1) {
|
|
147
|
+
b -= partPause(p);
|
|
148
|
+
if (b <= 0) break;
|
|
149
|
+
parts -= 1;
|
|
150
|
+
}
|
|
151
|
+
return Math.max(1, parts) * 10;
|
|
152
|
+
};
|
|
153
|
+
const FIRST_HOUR_MAX_LATE_MS = mostMs(0);
|
|
154
|
+
const SUBSEQUENT_HOUR_MAX_LATE_MS = Math.floor(HOUR_SECONDS / LONGEST_PAUSE_SECONDS) * 10;
|
|
155
|
+
const arrivalLateMs = (sendAheadMs, stampUs, nowUs) => sendAheadMs - (stampUs - nowUs) / 1e3;
|
|
156
|
+
function measuredLateMs(seconds) {
|
|
157
|
+
const last = seconds.slice(-5);
|
|
158
|
+
if (last.length < 5) return;
|
|
159
|
+
let lateMs = 0;
|
|
160
|
+
for (let i = 0; i < last.length; i += 1) for (let j = i + 2; j < last.length; j += 1) lateMs = Math.max(lateMs, Math.min(last[i] ?? 0, last[j] ?? 0));
|
|
161
|
+
return Math.min(FIRST_HOUR_MAX_LATE_MS, Math.round(lateMs));
|
|
162
|
+
}
|
|
163
|
+
const declareLiveBuffer = (declaredMs, latencyMs = [], allowanceMs = 0) => {
|
|
164
|
+
const need = risenNeed(declaredMs, latencyMs, allowanceMs);
|
|
165
|
+
return need === void 0 ? void 0 : Math.min(LIMIT_MS, need);
|
|
166
|
+
};
|
|
167
|
+
const withLateSteps = (needMs, lateMs) => Math.min(LIMIT_MS, needMs + lateMs);
|
|
168
|
+
const lostIn = (seconds) => seconds.reduce((sum, s) => sum + s.lost, 0);
|
|
169
|
+
const stepOf = (ms) => Math.max(1, Math.ceil(ms / 10)) * 10;
|
|
170
|
+
const stepFor = (vals) => stepOf(vals.toSorted((a, b) => b - a)[1] ?? 0);
|
|
171
|
+
function spellsIn(seconds) {
|
|
172
|
+
const apart = [];
|
|
173
|
+
let [spells, run, longest, clean] = [
|
|
174
|
+
0,
|
|
175
|
+
0,
|
|
176
|
+
0,
|
|
177
|
+
APART_SECONDS
|
|
178
|
+
];
|
|
179
|
+
for (const s of seconds) {
|
|
180
|
+
if (s.lost === 0) {
|
|
181
|
+
run = 0;
|
|
182
|
+
clean += 1;
|
|
183
|
+
continue;
|
|
184
|
+
}
|
|
185
|
+
const lateMs = s.lateMs ?? 0;
|
|
186
|
+
spells += run === 0 ? 1 : 0;
|
|
187
|
+
if (clean >= APART_SECONDS) apart.push(lateMs);
|
|
188
|
+
else if (apart.length > 0) apart[apart.length - 1] = Math.max(apart.at(-1) ?? 0, lateMs);
|
|
189
|
+
clean = 0;
|
|
190
|
+
run += 1;
|
|
191
|
+
longest = Math.max(longest, run);
|
|
192
|
+
}
|
|
193
|
+
return {
|
|
194
|
+
apart,
|
|
195
|
+
longest,
|
|
196
|
+
spells
|
|
197
|
+
};
|
|
198
|
+
}
|
|
199
|
+
function recurs(seconds) {
|
|
200
|
+
const win = seconds.slice(-10);
|
|
201
|
+
const run = win.slice(-3);
|
|
202
|
+
if (run.length === RUN_SECONDS && run.every((s) => s.lost > 0)) {
|
|
203
|
+
const vals = run.map((s) => s.lateMs ?? 0);
|
|
204
|
+
const [least, latest] = [Math.min(...vals), Math.max(...vals)];
|
|
205
|
+
const held = run.every((s) => s.lateMs !== void 0) && latest - least <= 10;
|
|
206
|
+
return {
|
|
207
|
+
count: lostIn(run),
|
|
208
|
+
measure: "running",
|
|
209
|
+
stepMs: stepOf(held ? latest : least)
|
|
210
|
+
};
|
|
211
|
+
}
|
|
212
|
+
if (seconds.length < WINDOW_SECONDS) return;
|
|
213
|
+
const recent = spellsIn(win);
|
|
214
|
+
if (recent.spells >= 2 || recent.longest >= RUN_SECONDS) return {
|
|
215
|
+
count: lostIn(win),
|
|
216
|
+
measure: "chunks",
|
|
217
|
+
stepMs: stepFor(recent.apart)
|
|
218
|
+
};
|
|
219
|
+
const { spells, apart } = spellsIn(seconds);
|
|
220
|
+
return spells >= HORIZON_SPELLS ? {
|
|
221
|
+
count: spells,
|
|
222
|
+
measure: "spells",
|
|
223
|
+
stepMs: stepFor(apart)
|
|
224
|
+
} : void 0;
|
|
225
|
+
}
|
|
226
|
+
const ask = (late, phase) => {
|
|
227
|
+
const partMs = Math.min(phase.caused.stepMs - phase.askedMs, late.partMs ?? Number.POSITIVE_INFINITY);
|
|
228
|
+
return {
|
|
229
|
+
...late,
|
|
230
|
+
lateMs: late.lateMs + partMs,
|
|
231
|
+
phase: {
|
|
232
|
+
...phase,
|
|
233
|
+
askedMs: phase.askedMs + partMs,
|
|
234
|
+
waited: 0
|
|
235
|
+
},
|
|
236
|
+
taken: [...late.taken, {
|
|
237
|
+
at: late.counted,
|
|
238
|
+
ms: partMs
|
|
239
|
+
}]
|
|
240
|
+
};
|
|
241
|
+
};
|
|
242
|
+
function step(late, seconds, recurring) {
|
|
243
|
+
const taken = late.taken.filter(({ at }) => late.counted - at < HOUR_SECONDS);
|
|
244
|
+
const cap = late.counted <= HOUR_SECONDS ? FIRST_HOUR_MAX_LATE_MS : SUBSEQUENT_HOUR_MAX_LATE_MS;
|
|
245
|
+
const stepMs = Math.min(recurring.stepMs, mostMs(late.unhelpful), cap - taken.reduce((sum, { ms }) => sum + ms, 0));
|
|
246
|
+
if (stepMs <= 0) return {
|
|
247
|
+
...late,
|
|
248
|
+
caused: void 0,
|
|
249
|
+
seconds,
|
|
250
|
+
taken
|
|
251
|
+
};
|
|
252
|
+
const aheads = seconds.flatMap((s) => s.sendAheadMs ?? []).toSorted((a, b) => a - b);
|
|
253
|
+
return ask({
|
|
254
|
+
...late,
|
|
255
|
+
caused: void 0,
|
|
256
|
+
clean: 0,
|
|
257
|
+
seconds,
|
|
258
|
+
taken
|
|
259
|
+
}, {
|
|
260
|
+
askedMs: 0,
|
|
261
|
+
caused: {
|
|
262
|
+
...recurring,
|
|
263
|
+
stepMs
|
|
264
|
+
},
|
|
265
|
+
kind: "moving",
|
|
266
|
+
landedMs: 0,
|
|
267
|
+
sendAheadMs: aheads[Math.floor(aheads.length / 2)],
|
|
268
|
+
waited: 0
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
function move(late, phase, second, seconds) {
|
|
272
|
+
const wait = () => ({
|
|
273
|
+
...late,
|
|
274
|
+
phase: {
|
|
275
|
+
...phase,
|
|
276
|
+
waited: phase.waited + 1
|
|
277
|
+
},
|
|
278
|
+
seconds
|
|
279
|
+
});
|
|
280
|
+
const done = (stepMs) => ({
|
|
281
|
+
...late,
|
|
282
|
+
caused: {
|
|
283
|
+
...phase.caused,
|
|
284
|
+
stepMs
|
|
285
|
+
},
|
|
286
|
+
phase: WATCHING,
|
|
287
|
+
seconds: []
|
|
288
|
+
});
|
|
289
|
+
if (phase.askedMs > phase.landedMs) {
|
|
290
|
+
if (!(phase.sendAheadMs !== void 0 && second.sendAheadMs !== void 0 && second.sendAheadMs >= phase.sendAheadMs + (phase.askedMs + phase.landedMs) / 2)) return phase.waited + 1 < MOVING_SECONDS ? wait() : {
|
|
291
|
+
...late,
|
|
292
|
+
phase: WATCHING,
|
|
293
|
+
seconds
|
|
294
|
+
};
|
|
295
|
+
return second.syncErrorMs === void 0 && phase.askedMs === phase.caused.stepMs ? done(phase.askedMs) : {
|
|
296
|
+
...late,
|
|
297
|
+
phase: {
|
|
298
|
+
...phase,
|
|
299
|
+
landedMs: phase.askedMs,
|
|
300
|
+
waited: 0
|
|
301
|
+
},
|
|
302
|
+
seconds
|
|
303
|
+
};
|
|
304
|
+
}
|
|
305
|
+
const { syncErrorMs } = second;
|
|
306
|
+
const settled = syncErrorMs !== void 0 && syncErrorMs > -8;
|
|
307
|
+
if (!settled && phase.waited + 1 < SLEW_SECONDS) return wait();
|
|
308
|
+
return (settled || syncErrorMs === void 0) && phase.landedMs < phase.caused.stepMs ? ask({
|
|
309
|
+
...late,
|
|
310
|
+
seconds
|
|
311
|
+
}, phase) : done(phase.landedMs);
|
|
312
|
+
}
|
|
313
|
+
function nextLateSteps(before, second) {
|
|
314
|
+
const late = {
|
|
315
|
+
...before,
|
|
316
|
+
counted: before.counted + 1
|
|
317
|
+
};
|
|
318
|
+
const seconds = [...late.seconds, second].slice(-60);
|
|
319
|
+
const { phase } = late;
|
|
320
|
+
if (phase.kind === "moving") return move(late, phase, second, seconds);
|
|
321
|
+
const recurring = recurs(seconds);
|
|
322
|
+
const clean = recurring ? 0 : late.clean + 1;
|
|
323
|
+
const next = clean >= FORGET_SECONDS || late.caused?.measure === "running" && second.lost === 0 ? {
|
|
324
|
+
...late,
|
|
325
|
+
caused: void 0,
|
|
326
|
+
clean,
|
|
327
|
+
seconds,
|
|
328
|
+
unhelpful: 0
|
|
329
|
+
} : {
|
|
330
|
+
...late,
|
|
331
|
+
clean,
|
|
332
|
+
seconds
|
|
333
|
+
};
|
|
334
|
+
const running = recurring?.measure === "running";
|
|
335
|
+
if (phase.kind === "pausing" && !running) return {
|
|
336
|
+
...next,
|
|
337
|
+
phase: phase.left > 1 ? {
|
|
338
|
+
kind: "pausing",
|
|
339
|
+
left: phase.left - 1
|
|
340
|
+
} : WATCHING
|
|
341
|
+
};
|
|
342
|
+
if (!recurring) return next;
|
|
343
|
+
const { caused } = next;
|
|
344
|
+
if (!caused || running && caused.measure !== "running") return step(next, seconds, recurring);
|
|
345
|
+
if (caused.measure !== "spells" && caused.measure === recurring.measure && recurring.count * 2 <= caused.count) return step({
|
|
346
|
+
...next,
|
|
347
|
+
unhelpful: 0
|
|
348
|
+
}, seconds, recurring);
|
|
349
|
+
const unhelpful = next.unhelpful + caused.stepMs / 10;
|
|
350
|
+
return running ? step({
|
|
351
|
+
...next,
|
|
352
|
+
unhelpful
|
|
353
|
+
}, seconds, recurring) : {
|
|
354
|
+
...next,
|
|
355
|
+
caused: void 0,
|
|
356
|
+
phase: {
|
|
357
|
+
kind: "pausing",
|
|
358
|
+
left: pauseAfter(next.unhelpful, caused.stepMs)
|
|
359
|
+
},
|
|
360
|
+
unhelpful
|
|
361
|
+
};
|
|
362
|
+
}
|
|
363
|
+
// src/sync/live-lead.ts
|
|
364
|
+
const LOG_EVERY_MS = 1e4;
|
|
365
|
+
const INPUT_READINGS = 30;
|
|
366
|
+
const INPUT_PART_SECONDS = 2;
|
|
367
|
+
const MEASURE_MS = 1e3;
|
|
368
|
+
const noopLog = () => {};
|
|
369
|
+
function advanceWireSecond(wire, input, second, log) {
|
|
370
|
+
input.readings = [...input.readings, input.highest].slice(-30);
|
|
371
|
+
const beforeMs = input.ms;
|
|
372
|
+
const beforeRisen = input.risen;
|
|
373
|
+
if (input.ms === void 0 || input.held) {
|
|
374
|
+
const initial = risenNeed(void 0, input.readings);
|
|
375
|
+
input.ms = initial;
|
|
376
|
+
input.risen = initial;
|
|
377
|
+
input.held = false;
|
|
378
|
+
} else {
|
|
379
|
+
input.risen = risenNeed(input.risen, input.readings, 0, INPUT_READINGS);
|
|
380
|
+
if (input.risen !== void 0 && input.ms < input.risen && second - (input.partSecond ?? Number.NEGATIVE_INFINITY) >= INPUT_PART_SECONDS) {
|
|
381
|
+
input.ms = Math.min(input.risen, input.ms + 5);
|
|
382
|
+
input.partSecond = second;
|
|
383
|
+
}
|
|
384
|
+
}
|
|
385
|
+
if (input.ms !== beforeMs || input.risen !== beforeRisen) {
|
|
386
|
+
const note = input.ms !== void 0 && input.risen !== void 0 && input.ms < input.risen ? `, rising to ${input.risen} ms` : "";
|
|
387
|
+
log(`live input side ${wire}: ${String(input.ms)} ms${note}`);
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
function createLiveLead(log = noopLog, nowMs = () => Date.now()) {
|
|
391
|
+
const inputs = /* @__PURE__ */ new Map();
|
|
392
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
393
|
+
const logged = /* @__PURE__ */ new Map();
|
|
394
|
+
return {
|
|
395
|
+
arrived(wire, capturedAtUs, nowUs) {
|
|
396
|
+
let input = inputs.get(wire);
|
|
397
|
+
if (!input) {
|
|
398
|
+
input = {
|
|
399
|
+
highest: Number.NEGATIVE_INFINITY,
|
|
400
|
+
readings: [],
|
|
401
|
+
second: 0
|
|
402
|
+
};
|
|
403
|
+
inputs.set(wire, input);
|
|
404
|
+
}
|
|
405
|
+
input.firstUs ??= nowUs;
|
|
406
|
+
const second = Math.floor((nowUs - input.firstUs) / 1e6);
|
|
407
|
+
if (second !== input.second) {
|
|
408
|
+
if (input.second > 0) advanceWireSecond(wire, input, second, log);
|
|
409
|
+
input.second = second;
|
|
410
|
+
input.highest = Number.NEGATIVE_INFINITY;
|
|
411
|
+
}
|
|
412
|
+
input.highest = Math.max(input.highest, (nowUs - capturedAtUs) / 1e3);
|
|
413
|
+
},
|
|
414
|
+
leadMs(clientId, wire, declaredMs, name = clientId) {
|
|
415
|
+
const known = listeners.get(clientId);
|
|
416
|
+
const inputMs = inputs.get(wire)?.ms;
|
|
417
|
+
if (inputMs === void 0 || declaredMs === void 0) return known?.step ?? 0;
|
|
418
|
+
const step = Math.max(known?.step ?? 0, liveStep(declaredMs + inputMs));
|
|
419
|
+
const last = logged.get(clientId);
|
|
420
|
+
if ((step !== known?.step || declaredMs !== known?.declared) && (!last || step > last.step || nowMs() - last.atMs >= LOG_EVERY_MS)) {
|
|
421
|
+
log(`live listener ${JSON.stringify(name)} ${wire}: declares ${declaredMs} ms, input side ${inputMs} ms, plays ${step} ms after capture`);
|
|
422
|
+
logged.set(clientId, {
|
|
423
|
+
atMs: nowMs(),
|
|
424
|
+
step
|
|
425
|
+
});
|
|
426
|
+
}
|
|
427
|
+
listeners.set(clientId, {
|
|
428
|
+
declared: declaredMs,
|
|
429
|
+
step
|
|
430
|
+
});
|
|
431
|
+
return step;
|
|
432
|
+
},
|
|
433
|
+
left: (clientId) => {
|
|
434
|
+
listeners.delete(clientId);
|
|
435
|
+
},
|
|
436
|
+
measureMs: (wire) => {
|
|
437
|
+
const inputMs = inputs.get(wire)?.ms;
|
|
438
|
+
return inputMs === void 0 ? void 0 : liveStep(inputMs + MEASURE_MS);
|
|
439
|
+
},
|
|
440
|
+
restart() {
|
|
441
|
+
for (const input of inputs.values()) {
|
|
442
|
+
input.held = input.ms !== void 0;
|
|
443
|
+
input.firstUs = void 0;
|
|
444
|
+
input.second = 0;
|
|
445
|
+
input.highest = Number.NEGATIVE_INFINITY;
|
|
446
|
+
input.readings = [];
|
|
447
|
+
input.partSecond = void 0;
|
|
448
|
+
}
|
|
449
|
+
listeners.clear();
|
|
450
|
+
}
|
|
451
|
+
};
|
|
452
|
+
}
|
|
453
|
+
// src/sync/live-timeline.ts
|
|
454
|
+
const DEFAULT_LIVE_TIMELINE_CAPACITY = 256;
|
|
455
|
+
const DEADBAND_SEC = .001;
|
|
456
|
+
const SLEW_RATE = .003;
|
|
457
|
+
const REPLACE_SEC = .2;
|
|
458
|
+
const JOIN_US = 1e3;
|
|
459
|
+
const contextFrame = (clock, pageMs) => (clock.offset + pageMs / 1e3) * clock.sampleRate;
|
|
460
|
+
function pageClock() {
|
|
461
|
+
let aheadMs = Number.POSITIVE_INFINITY;
|
|
462
|
+
return {
|
|
463
|
+
pageMs: (ownMs = performance.now()) => ownMs - aheadMs,
|
|
464
|
+
saw: (pageMs, ownMs = performance.now()) => {
|
|
465
|
+
aheadMs = Math.min(aheadMs, ownMs - pageMs);
|
|
466
|
+
}
|
|
467
|
+
};
|
|
468
|
+
}
|
|
469
|
+
const noStats = () => ({
|
|
470
|
+
chunks: 0,
|
|
471
|
+
corrections: 0,
|
|
472
|
+
errorMax: Number.NEGATIVE_INFINITY,
|
|
473
|
+
errorMin: Number.POSITIVE_INFINITY,
|
|
474
|
+
filled: 0,
|
|
475
|
+
lost: 0,
|
|
476
|
+
skipped: 0,
|
|
477
|
+
slack: Number.POSITIVE_INFINITY
|
|
478
|
+
});
|
|
479
|
+
function addStats(totals, stats) {
|
|
480
|
+
totals.chunks += stats.chunks;
|
|
481
|
+
totals.lost += stats.lost;
|
|
482
|
+
totals.slack = Math.min(totals.slack, stats.slack);
|
|
483
|
+
totals.filled += stats.filled;
|
|
484
|
+
totals.skipped += stats.skipped;
|
|
485
|
+
totals.errorMin = Math.min(totals.errorMin, stats.errorMin);
|
|
486
|
+
totals.errorMax = Math.max(totals.errorMax, stats.errorMax);
|
|
487
|
+
totals.corrections += stats.corrections;
|
|
488
|
+
}
|
|
489
|
+
function resetStats(s) {
|
|
490
|
+
s.chunks = 0;
|
|
491
|
+
s.corrections = 0;
|
|
492
|
+
s.errorMax = Number.NEGATIVE_INFINITY;
|
|
493
|
+
s.errorMin = Number.POSITIVE_INFINITY;
|
|
494
|
+
s.filled = 0;
|
|
495
|
+
s.lost = 0;
|
|
496
|
+
s.skipped = 0;
|
|
497
|
+
s.slack = Number.POSITIVE_INFINITY;
|
|
498
|
+
}
|
|
499
|
+
function interpolateSample(samples, nextChunk, ch, idx, frac) {
|
|
500
|
+
const s = samples[idx] ?? 0;
|
|
501
|
+
if (frac === 0) return s;
|
|
502
|
+
return s + ((idx + 1 < samples.length ? samples[idx + 1] ?? s : (nextChunk?.channels[ch] ?? nextChunk?.channels[0])?.[0] ?? s) - s) * frac;
|
|
503
|
+
}
|
|
504
|
+
var LiveTimeline = class {
|
|
505
|
+
capacity;
|
|
506
|
+
ring;
|
|
507
|
+
head = 0;
|
|
508
|
+
tail = 0;
|
|
509
|
+
count = 0;
|
|
510
|
+
position = 0;
|
|
511
|
+
playing = false;
|
|
512
|
+
dry = false;
|
|
513
|
+
endStampUs;
|
|
514
|
+
correcting = 0;
|
|
515
|
+
settling = false;
|
|
516
|
+
rate = 1;
|
|
517
|
+
sampleRate;
|
|
518
|
+
stats = noStats();
|
|
519
|
+
constructor(sampleRate, capacity = 256) {
|
|
520
|
+
this.sampleRate = sampleRate;
|
|
521
|
+
this.capacity = Number.isFinite(capacity) ? Math.max(2, Math.floor(capacity)) : 256;
|
|
522
|
+
this.ring = Array.from({ length: this.capacity });
|
|
523
|
+
}
|
|
524
|
+
get length() {
|
|
525
|
+
return this.count;
|
|
526
|
+
}
|
|
527
|
+
get maxCapacity() {
|
|
528
|
+
return this.capacity;
|
|
529
|
+
}
|
|
530
|
+
reset() {
|
|
531
|
+
this.ring.fill(void 0);
|
|
532
|
+
this.head = 0;
|
|
533
|
+
this.tail = 0;
|
|
534
|
+
this.count = 0;
|
|
535
|
+
this.dry = false;
|
|
536
|
+
this.endStampUs = void 0;
|
|
537
|
+
this.stopSlew(true);
|
|
538
|
+
resetStats(this.stats);
|
|
539
|
+
}
|
|
540
|
+
takeStats() {
|
|
541
|
+
const snap = noStats();
|
|
542
|
+
this.takeStatsInto(snap);
|
|
543
|
+
return snap;
|
|
544
|
+
}
|
|
545
|
+
takeStatsInto(target) {
|
|
546
|
+
target.chunks = this.stats.chunks;
|
|
547
|
+
target.corrections = this.stats.corrections;
|
|
548
|
+
target.errorMax = this.stats.errorMax;
|
|
549
|
+
target.errorMin = this.stats.errorMin;
|
|
550
|
+
target.filled = this.stats.filled;
|
|
551
|
+
target.lost = this.stats.lost;
|
|
552
|
+
target.skipped = this.stats.skipped;
|
|
553
|
+
target.slack = this.stats.slack;
|
|
554
|
+
resetStats(this.stats);
|
|
555
|
+
}
|
|
556
|
+
stopSlew(resetPos = false) {
|
|
557
|
+
this.playing = false;
|
|
558
|
+
this.settling = false;
|
|
559
|
+
this.correcting = 0;
|
|
560
|
+
this.rate = 1;
|
|
561
|
+
if (resetPos) this.position = 0;
|
|
562
|
+
}
|
|
563
|
+
at(offset) {
|
|
564
|
+
return offset < this.count ? this.ring[(this.head + offset) % this.capacity] : void 0;
|
|
565
|
+
}
|
|
566
|
+
dropHead() {
|
|
567
|
+
this.ring[this.head] = void 0;
|
|
568
|
+
this.head = (this.head + 1) % this.capacity;
|
|
569
|
+
this.count -= 1;
|
|
570
|
+
}
|
|
571
|
+
push(chunk, next) {
|
|
572
|
+
if ((chunk.channels[0]?.length ?? 0) === 0) return;
|
|
573
|
+
const slack = this.playing ? this.queued() : chunk.frame - next;
|
|
574
|
+
const follows = this.endStampUs !== void 0 && Math.abs(chunk.stampUs - this.endStampUs) <= JOIN_US;
|
|
575
|
+
this.stats.chunks += 1;
|
|
576
|
+
this.stats.slack = Math.min(this.stats.slack, slack);
|
|
577
|
+
if (slack < 0 || this.dry && follows) this.stats.lost += 1;
|
|
578
|
+
this.dry = false;
|
|
579
|
+
if (this.count === this.capacity) {
|
|
580
|
+
this.dropHead();
|
|
581
|
+
this.stats.lost += 1;
|
|
582
|
+
if (this.playing) this.stopSlew(true);
|
|
583
|
+
}
|
|
584
|
+
this.ring[this.tail] = chunk;
|
|
585
|
+
this.tail = (this.tail + 1) % this.capacity;
|
|
586
|
+
this.count += 1;
|
|
587
|
+
}
|
|
588
|
+
render(frame, output) {
|
|
589
|
+
const frames = output[0]?.length ?? 0;
|
|
590
|
+
if (this.playing) this.steer(frame);
|
|
591
|
+
const chCount = output.length;
|
|
592
|
+
for (let i = 0; i < frames; i += 1) {
|
|
593
|
+
if (!this.playing && !this.place(frame + i)) {
|
|
594
|
+
for (let c = 0; c < chCount; c += 1) {
|
|
595
|
+
const outCh = output[c];
|
|
596
|
+
if (outCh) outCh[i] = 0;
|
|
597
|
+
}
|
|
598
|
+
if (this.dry) this.stats.filled += 1;
|
|
599
|
+
continue;
|
|
600
|
+
}
|
|
601
|
+
this.read(output, i, frame + i);
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
queued() {
|
|
605
|
+
let frames = -this.position;
|
|
606
|
+
for (let i = 0; i < this.count; i += 1) frames += this.ring[(this.head + i) % this.capacity]?.channels[0]?.length ?? 0;
|
|
607
|
+
return frames / this.rate;
|
|
608
|
+
}
|
|
609
|
+
place(frame) {
|
|
610
|
+
while (this.count > 0) {
|
|
611
|
+
const chunk = this.at(0);
|
|
612
|
+
if (!chunk) return false;
|
|
613
|
+
const offset = Math.round(frame - chunk.frame);
|
|
614
|
+
const len = chunk.channels[0]?.length ?? 0;
|
|
615
|
+
if (offset < 0) return false;
|
|
616
|
+
if (offset < len) {
|
|
617
|
+
this.stats.skipped += offset;
|
|
618
|
+
this.position = offset;
|
|
619
|
+
this.playing = true;
|
|
620
|
+
return true;
|
|
621
|
+
}
|
|
622
|
+
this.stats.skipped += len;
|
|
623
|
+
this.dropHead();
|
|
624
|
+
}
|
|
625
|
+
return false;
|
|
626
|
+
}
|
|
627
|
+
steer(frame) {
|
|
628
|
+
const chunk = this.at(0);
|
|
629
|
+
if (!chunk) return;
|
|
630
|
+
const err = chunk.frame + this.position - frame;
|
|
631
|
+
this.stats.errorMin = Math.min(this.stats.errorMin, err);
|
|
632
|
+
this.stats.errorMax = Math.max(this.stats.errorMax, err);
|
|
633
|
+
if (Math.abs(err) > REPLACE_SEC * this.sampleRate) {
|
|
634
|
+
this.stopSlew();
|
|
635
|
+
return;
|
|
636
|
+
}
|
|
637
|
+
const sign = Math.sign(err);
|
|
638
|
+
if (this.correcting === 0 && Math.abs(err) > DEADBAND_SEC * this.sampleRate) {
|
|
639
|
+
this.correcting = sign;
|
|
640
|
+
this.settling = false;
|
|
641
|
+
this.rate = 1 - sign * SLEW_RATE;
|
|
642
|
+
this.stats.corrections += 1;
|
|
643
|
+
} else if (this.correcting !== 0 && sign !== this.correcting) this.settling = true;
|
|
644
|
+
}
|
|
645
|
+
read(output, i, frameIdx) {
|
|
646
|
+
const chunk = this.at(0);
|
|
647
|
+
if (!chunk) return;
|
|
648
|
+
const next = this.at(1);
|
|
649
|
+
const idx = Math.floor(this.position);
|
|
650
|
+
const frac = this.position - idx;
|
|
651
|
+
const chCount = output.length;
|
|
652
|
+
for (let c = 0; c < chCount; c += 1) {
|
|
653
|
+
const outCh = output[c];
|
|
654
|
+
const samples = chunk.channels[c] ?? chunk.channels[0];
|
|
655
|
+
if (outCh && samples) outCh[i] = interpolateSample(samples, next, c, idx, frac);
|
|
656
|
+
}
|
|
657
|
+
this.position += this.rate;
|
|
658
|
+
const whole = Math.round(this.position);
|
|
659
|
+
if (this.settling && Math.abs(this.position - whole) < SLEW_RATE) {
|
|
660
|
+
this.position = whole;
|
|
661
|
+
this.rate = 1;
|
|
662
|
+
this.correcting = 0;
|
|
663
|
+
this.settling = false;
|
|
664
|
+
}
|
|
665
|
+
const len = chunk.channels[0]?.length ?? 0;
|
|
666
|
+
if (this.position < len) return;
|
|
667
|
+
this.position -= len;
|
|
668
|
+
this.endStampUs = chunk.stampUs + len / this.sampleRate * 1e6;
|
|
669
|
+
this.dropHead();
|
|
670
|
+
const nextChunk = this.at(0);
|
|
671
|
+
if (!nextChunk) {
|
|
672
|
+
this.dry = true;
|
|
673
|
+
this.stopSlew();
|
|
674
|
+
} else if (Math.abs(nextChunk.frame + this.position - (frameIdx + 1)) > REPLACE_SEC * this.sampleRate) this.stopSlew(true);
|
|
675
|
+
}
|
|
676
|
+
};
|
|
677
|
+
// src/worklets/couch-live.ts
|
|
678
|
+
const COUCH_LIVE_PROCESSOR_NAME = "couch-live";
|
|
679
|
+
if (typeof registerProcessor === "function") {
|
|
680
|
+
const reportFrames = sampleRate / 10;
|
|
681
|
+
registerProcessor(COUCH_LIVE_PROCESSOR_NAME, class CouchLiveProcessor extends AudioWorkletProcessor {
|
|
682
|
+
timeline = new LiveTimeline(sampleRate);
|
|
683
|
+
reportStats = noStats();
|
|
684
|
+
reportPayload;
|
|
685
|
+
epoch = 0;
|
|
686
|
+
next = currentFrame;
|
|
687
|
+
reported = currentFrame;
|
|
688
|
+
feed;
|
|
689
|
+
disposed = false;
|
|
690
|
+
onFeedMessage = (msgEvent) => {
|
|
691
|
+
const msg = msgEvent.data;
|
|
692
|
+
if (this.disposed || !msg || typeof msg !== "object") return;
|
|
693
|
+
if (msg.type === "dispose") this.dispose();
|
|
694
|
+
else if (msg.type === "chunk" && msg.chunk) this.timeline.push(msg.chunk, this.next);
|
|
695
|
+
else if (msg.type === "reset") {
|
|
696
|
+
this.timeline.reset();
|
|
697
|
+
this.epoch = typeof msg.epoch === "number" ? msg.epoch : 0;
|
|
698
|
+
}
|
|
699
|
+
};
|
|
700
|
+
onPortMessage = (event) => {
|
|
701
|
+
const { data } = event;
|
|
702
|
+
if (this.disposed || !data || typeof data !== "object") return;
|
|
703
|
+
if (data.type === "dispose") this.dispose();
|
|
704
|
+
else if (data.type === "poll") this.flushReport();
|
|
705
|
+
else if (data.port) {
|
|
706
|
+
this.detachFeed();
|
|
707
|
+
this.feed = data.port;
|
|
708
|
+
this.feed.addEventListener("message", this.onFeedMessage);
|
|
709
|
+
this.feed.start?.();
|
|
710
|
+
}
|
|
711
|
+
};
|
|
712
|
+
constructor() {
|
|
713
|
+
super();
|
|
714
|
+
this.reportPayload = {
|
|
715
|
+
epoch: 0,
|
|
716
|
+
stats: this.reportStats
|
|
717
|
+
};
|
|
718
|
+
this.port.addEventListener("message", this.onPortMessage);
|
|
719
|
+
this.port.start?.();
|
|
720
|
+
}
|
|
721
|
+
detachFeed() {
|
|
722
|
+
if (!this.feed) return;
|
|
723
|
+
this.feed.removeEventListener("message", this.onFeedMessage);
|
|
724
|
+
this.feed.close?.();
|
|
725
|
+
this.feed = void 0;
|
|
726
|
+
}
|
|
727
|
+
dispose() {
|
|
728
|
+
if (this.disposed) return;
|
|
729
|
+
this.disposed = true;
|
|
730
|
+
this.detachFeed();
|
|
731
|
+
this.timeline.reset();
|
|
732
|
+
this.port.removeEventListener("message", this.onPortMessage);
|
|
733
|
+
this.port.close?.();
|
|
734
|
+
}
|
|
735
|
+
flushReport() {
|
|
736
|
+
if (this.disposed || !this.feed) return;
|
|
737
|
+
this.timeline.takeStatsInto(this.reportStats);
|
|
738
|
+
this.reportPayload.epoch = this.epoch;
|
|
739
|
+
this.feed.postMessage(this.reportPayload);
|
|
740
|
+
}
|
|
741
|
+
process(_inputs, outputs) {
|
|
742
|
+
if (this.disposed) return false;
|
|
743
|
+
const [output] = outputs;
|
|
744
|
+
if (!output) return true;
|
|
745
|
+
this.timeline.render(currentFrame, output);
|
|
746
|
+
this.next = currentFrame + (output[0]?.length ?? 0);
|
|
747
|
+
if (this.next - this.reported >= reportFrames) {
|
|
748
|
+
this.reported = this.next;
|
|
749
|
+
this.flushReport();
|
|
750
|
+
}
|
|
751
|
+
return true;
|
|
752
|
+
}
|
|
753
|
+
});
|
|
754
|
+
}
|
|
755
|
+
// src/sync/sendspin.ts
|
|
756
|
+
const SENDSPIN_BINARY_AUDIO_TYPE = 4;
|
|
757
|
+
const SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S = .015;
|
|
758
|
+
function computeLiveVolumeGain(volumePercent, muted) {
|
|
759
|
+
return muted ? 0 : (clampFinite(volumePercent, 0, 100, 100) / 100) ** 1.5;
|
|
760
|
+
}
|
|
761
|
+
function sniffSendspinAudioHeader(data) {
|
|
762
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
763
|
+
if (bytes.byteLength < 13 || bytes[0] !== 4) return;
|
|
764
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
765
|
+
return {
|
|
766
|
+
messageType: 4,
|
|
767
|
+
sendAheadUs: view.getUint32(9, false),
|
|
768
|
+
stampUs: Number(view.getBigInt64(1, false))
|
|
769
|
+
};
|
|
770
|
+
}
|
|
771
|
+
function collectTransferables(chunk) {
|
|
772
|
+
const seen = /* @__PURE__ */ new Set();
|
|
773
|
+
for (const ch of chunk.channels) if (ch.buffer instanceof ArrayBuffer && ch.buffer.byteLength > 0) seen.add(ch.buffer);
|
|
774
|
+
return [...seen];
|
|
775
|
+
}
|
|
776
|
+
function loadCouchLiveWorklet(context, options = {}) {
|
|
777
|
+
return loadAudioWorklet(context, {
|
|
778
|
+
fallbackToBlob: options.fallbackToBlob ?? true,
|
|
779
|
+
fetchImpl: options.fetchImpl,
|
|
780
|
+
inlineSource: options.inlineSource,
|
|
781
|
+
moduleUrl: options.inlineSource === void 0 ? options.moduleUrl ?? createWorkletModuleUrl("couch-live") : void 0,
|
|
782
|
+
processorName: COUCH_LIVE_PROCESSOR_NAME
|
|
783
|
+
});
|
|
784
|
+
}
|
|
785
|
+
function buildSendspinReceiver(context, options) {
|
|
786
|
+
const workletNode = new globalThis.AudioWorkletNode(context, COUCH_LIVE_PROCESSOR_NAME, {
|
|
787
|
+
numberOfInputs: 0,
|
|
788
|
+
numberOfOutputs: 1,
|
|
789
|
+
outputChannelCount: [2]
|
|
790
|
+
});
|
|
791
|
+
const outputGain = context.createGain();
|
|
792
|
+
let volumePercent = options.initialVolume ?? 100;
|
|
793
|
+
let muted = options.initialMuted ?? false;
|
|
794
|
+
outputGain.gain.value = computeLiveVolumeGain(volumePercent, muted);
|
|
795
|
+
let currentTarget = options.outputNode ?? context.destination;
|
|
796
|
+
workletNode.connect(outputGain);
|
|
797
|
+
outputGain.connect(currentTarget);
|
|
798
|
+
const channel = new MessageChannel();
|
|
799
|
+
const feedPort = channel.port2;
|
|
800
|
+
workletNode.port.postMessage({ port: channel.port1 }, [channel.port1]);
|
|
801
|
+
const onFeedMessage = (event) => {
|
|
802
|
+
if (event.data?.stats) options.onStats?.(event.data.epoch, event.data.stats);
|
|
803
|
+
};
|
|
804
|
+
if (options.onStats) {
|
|
805
|
+
feedPort.addEventListener("message", onFeedMessage);
|
|
806
|
+
feedPort.start?.();
|
|
807
|
+
}
|
|
808
|
+
let epoch = 0;
|
|
809
|
+
let disposed = false;
|
|
810
|
+
const applyGain = () => {
|
|
811
|
+
setParamTarget(outputGain.gain, context, computeLiveVolumeGain(volumePercent, muted), SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S);
|
|
812
|
+
};
|
|
813
|
+
const dispose = () => {
|
|
814
|
+
if (disposed) return;
|
|
815
|
+
disposed = true;
|
|
816
|
+
try {
|
|
817
|
+
workletNode.port.postMessage({ type: "dispose" });
|
|
818
|
+
} catch {}
|
|
819
|
+
workletNode.port.close?.();
|
|
820
|
+
feedPort.removeEventListener("message", onFeedMessage);
|
|
821
|
+
feedPort.close?.();
|
|
822
|
+
workletNode.disconnect();
|
|
823
|
+
outputGain.disconnect();
|
|
824
|
+
};
|
|
825
|
+
return {
|
|
826
|
+
dispose,
|
|
827
|
+
feedPort,
|
|
828
|
+
outputGain,
|
|
829
|
+
pushChunk: (chunk) => {
|
|
830
|
+
if (!disposed) feedPort.postMessage({
|
|
831
|
+
chunk,
|
|
832
|
+
type: "chunk"
|
|
833
|
+
}, collectTransferables(chunk));
|
|
834
|
+
},
|
|
835
|
+
reconnectOutput: (next) => {
|
|
836
|
+
disconnectEdge(outputGain, currentTarget);
|
|
837
|
+
currentTarget = next;
|
|
838
|
+
outputGain.connect(currentTarget);
|
|
839
|
+
},
|
|
840
|
+
resetTimeline: (nextEpoch) => {
|
|
841
|
+
epoch = nextEpoch ?? epoch + 1;
|
|
842
|
+
feedPort.postMessage({
|
|
843
|
+
epoch,
|
|
844
|
+
type: "reset"
|
|
845
|
+
});
|
|
846
|
+
return epoch;
|
|
847
|
+
},
|
|
848
|
+
setMuted: (next) => {
|
|
849
|
+
muted = next;
|
|
850
|
+
applyGain();
|
|
851
|
+
return muted;
|
|
852
|
+
},
|
|
853
|
+
setVolume: (next) => {
|
|
854
|
+
volumePercent = Math.max(0, Math.min(100, next));
|
|
855
|
+
applyGain();
|
|
856
|
+
return volumePercent;
|
|
857
|
+
},
|
|
858
|
+
get targetNode() {
|
|
859
|
+
return currentTarget;
|
|
860
|
+
},
|
|
861
|
+
workletNode
|
|
862
|
+
};
|
|
863
|
+
}
|
|
864
|
+
function createSendspinReceiver(context, options = {}) {
|
|
865
|
+
return Effect.gen(function* () {
|
|
866
|
+
yield* loadCouchLiveWorklet(context, options.workletOptions);
|
|
867
|
+
if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
|
|
868
|
+
feature: "AudioWorkletNode",
|
|
869
|
+
message: "AudioWorkletNode is not available."
|
|
870
|
+
}));
|
|
871
|
+
const receiver = buildSendspinReceiver(context, options);
|
|
872
|
+
yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(receiver.dispose));
|
|
873
|
+
return receiver;
|
|
874
|
+
});
|
|
875
|
+
}
|
|
876
|
+
function createLivePlayer(context, options = {}) {
|
|
877
|
+
return createSendspinReceiver(context, options);
|
|
878
|
+
}
|
|
879
|
+
export { CCA1_ALLOWED_SAMPLE_RATES, CCA1_FORMAT_F32_INTERLEAVED, CCA1_HEADER_BYTES, CCA1_MAGIC, CCA1_MAX_CLOCK_RTT_US, CCA1_MAX_FRAMES, CCA1_MAX_PACKET_BYTES, COUCH_LIVE_PROCESSOR_NAME, DEFAULT_LIVE_TIMELINE_CAPACITY, FIRST_HOUR_MAX_LATE_MS, LIVE_LATE_STEP_MS, LIVE_READINGS, LIVE_STEP_MS, LiveTimeline, NO_LATE_STEPS, SDK_BATCH_MS, SDK_LATE_STEPS, SENDSPIN_BINARY_AUDIO_TYPE, SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S, SUBSEQUENT_HOUR_MAX_LATE_MS, VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE, addStats, arrivalLateMs, computeClockHandshake, computeLiveVolumeGain, contextFrame, createLiveLead, createLivePlayer, createSendspinReceiver, createWorkletBlobUrl, createWorkletModuleUrl, declareLiveBuffer, decodeCca1Frame, encodeCca1Frame, liveStep, loadAudioWorklet, loadCouchLiveWorklet, measuredLateMs, nextLateSteps, noStats, pageClock, risenNeed, sniffSendspinAudioHeader, validateCca1Packet, withLateSteps };
|
|
880
|
+
|
|
881
|
+
//# sourceMappingURL=index.js.map
|