@avoid.quest/audio 0.1.1-beta.2 → 0.1.1-beta.3

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