@avoid.quest/audio 0.1.1-beta.1 → 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 (46) hide show
  1. package/README.md +6 -6
  2. package/dist/effects/index.d.ts +3 -23
  3. package/dist/effects/index.js +11 -34
  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/midi/index.d.ts +1 -1
  8. package/dist/midi/index.js +5 -7
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js.map +1 -1
  11. package/dist/{pcm-buffer-DSzGHbon.js → pcm-buffer-CYMaauzk.js} +33 -37
  12. package/dist/pcm-buffer-CYMaauzk.js.map +1 -0
  13. package/dist/playback/index.d.ts +118 -47
  14. package/dist/playback/index.js +232 -138
  15. package/dist/playback/index.js.map +1 -1
  16. package/dist/queue/index.d.ts +0 -7
  17. package/dist/queue/index.js +6 -32
  18. package/dist/queue/index.js.map +1 -1
  19. package/dist/recognize/index.d.ts +8 -98
  20. package/dist/recognize/index.js +1 -273
  21. package/dist/routing/index.d.ts +5 -4
  22. package/dist/routing/index.js +56 -58
  23. package/dist/routing/index.js.map +1 -1
  24. package/dist/{shazam-gBrX1NEY.d.ts → shazam-D9clxt6q.d.ts} +3 -3
  25. package/dist/sync/index.d.ts +23 -178
  26. package/dist/sync/index.js +167 -732
  27. package/dist/sync/index.js.map +1 -1
  28. package/dist/{worklet-loader-f741D1tk.js → worklet-loader-BJy5r9pD.js} +53 -63
  29. package/dist/worklet-loader-BJy5r9pD.js.map +1 -0
  30. package/dist/worklet-loader-DEEeZBiD.d.ts +27 -0
  31. package/dist/worklets/live-pcm.d.ts +1 -0
  32. package/dist/worklets/live-pcm.js +285 -0
  33. package/dist/worklets/live-pcm.js.map +1 -0
  34. package/dist/worklets/meter.js.map +1 -1
  35. package/dist/worklets/pcm-capture.d.ts +0 -2
  36. package/dist/worklets/pcm-capture.js +0 -2
  37. package/dist/worklets/pcm-capture.js.map +1 -1
  38. package/package.json +12 -13
  39. package/types/hls-unavailable.d.ts +10 -0
  40. package/dist/pcm-buffer-DSzGHbon.js.map +0 -1
  41. package/dist/recognize/index.js.map +0 -1
  42. package/dist/worklet-loader-BabwPALw.d.ts +0 -41
  43. package/dist/worklet-loader-f741D1tk.js.map +0 -1
  44. package/dist/worklets/couch-live.d.ts +0 -1
  45. package/dist/worklets/couch-live.js +0 -283
  46. package/dist/worklets/couch-live.js.map +0 -1
@@ -1,457 +1,10 @@
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
- }
1
+ import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-BJy5r9pD.js";
2
+ // src/sync/live-timeline.ts
98
3
  /**
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`.
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.
102
6
  */
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;
7
+ const DEFAULT_LIVE_TIMELINE_CAPACITY = 1280;
455
8
  const DEADBAND_SEC = .001;
456
9
  const SLEW_RATE = .003;
457
10
  const REPLACE_SEC = .2;
@@ -501,185 +54,181 @@ function interpolateSample(samples, nextChunk, ch, idx, frac) {
501
54
  if (frac === 0) return s;
502
55
  return s + ((idx + 1 < samples.length ? samples[idx + 1] ?? s : (nextChunk?.channels[ch] ?? nextChunk?.channels[0])?.[0] ?? s) - s) * frac;
503
56
  }
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;
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)) {
613
91
  const offset = Math.round(frame - chunk.frame);
614
92
  const len = chunk.channels[0]?.length ?? 0;
615
93
  if (offset < 0) return false;
616
94
  if (offset < len) {
617
- this.stats.skipped += offset;
618
- this.position = offset;
619
- this.playing = true;
95
+ stats.skipped += offset;
96
+ position = offset;
97
+ playing = true;
620
98
  return true;
621
99
  }
622
- this.stats.skipped += len;
623
- this.dropHead();
100
+ stats.skipped += len;
101
+ dropHead();
624
102
  }
625
103
  return false;
626
- }
627
- steer(frame) {
628
- const chunk = this.at(0);
104
+ };
105
+ const steer = (frame) => {
106
+ const chunk = at(0);
629
107
  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();
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();
635
113
  return;
636
114
  }
637
115
  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);
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);
647
125
  if (!chunk) return;
648
- const next = this.at(1);
649
- const idx = Math.floor(this.position);
650
- const frac = this.position - idx;
126
+ const next = at(1);
127
+ const idx = Math.floor(position);
128
+ const frac = position - idx;
651
129
  const chCount = output.length;
652
130
  for (let c = 0; c < chCount; c += 1) {
653
131
  const outCh = output[c];
654
132
  const samples = chunk.channels[c] ?? chunk.channels[0];
655
133
  if (outCh && samples) outCh[i] = interpolateSample(samples, next, c, idx, frac);
656
134
  }
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;
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;
664
142
  }
665
143
  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);
144
+ if (position < len) return;
145
+ position -= len;
146
+ endStampUs = chunk.stampUs + len / sampleRate * 1e6;
147
+ dropHead();
148
+ const nextChunk = at(0);
671
149
  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";
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";
224
+ const isRecord = (value) => typeof value === "object" && value !== null;
225
+ const isFloat32Array = (value) => value instanceof Float32Array;
226
+ const isFeedPort = (value) => isRecord(value) && typeof value.addEventListener === "function" && typeof value.postMessage === "function" && typeof value.removeEventListener === "function";
227
+ const isLiveChunk = (value) => isRecord(value) && typeof value.frame === "number" && typeof value.stampUs === "number" && Array.isArray(value.channels) && value.channels.every(isFloat32Array);
679
228
  if (typeof registerProcessor === "function") {
680
229
  const reportFrames = sampleRate / 10;
681
- registerProcessor(COUCH_LIVE_PROCESSOR_NAME, class CouchLiveProcessor extends AudioWorkletProcessor {
682
- timeline = new LiveTimeline(sampleRate);
230
+ registerProcessor(LIVE_PCM_PROCESSOR_NAME, class LivePcmProcessor extends AudioWorkletProcessor {
231
+ timeline = createLiveTimeline(sampleRate);
683
232
  reportStats = noStats();
684
233
  reportPayload;
685
234
  epoch = 0;
@@ -687,11 +236,11 @@ if (typeof registerProcessor === "function") {
687
236
  reported = currentFrame;
688
237
  feed;
689
238
  disposed = false;
690
- onFeedMessage = (msgEvent) => {
691
- const msg = msgEvent.data;
692
- if (this.disposed || !msg || typeof msg !== "object") return;
239
+ onFeedMessage = (event) => {
240
+ const msg = event.data;
241
+ if (this.disposed || !isRecord(msg)) return;
693
242
  if (msg.type === "dispose") this.dispose();
694
- else if (msg.type === "chunk" && msg.chunk) this.timeline.push(msg.chunk, this.next);
243
+ else if (msg.type === "chunk" && isLiveChunk(msg.chunk)) this.timeline.push(msg.chunk, this.next);
695
244
  else if (msg.type === "reset") {
696
245
  this.timeline.reset();
697
246
  this.epoch = typeof msg.epoch === "number" ? msg.epoch : 0;
@@ -699,10 +248,10 @@ if (typeof registerProcessor === "function") {
699
248
  };
700
249
  onPortMessage = (event) => {
701
250
  const { data } = event;
702
- if (this.disposed || !data || typeof data !== "object") return;
251
+ if (this.disposed || !isRecord(data)) return;
703
252
  if (data.type === "dispose") this.dispose();
704
253
  else if (data.type === "poll") this.flushReport();
705
- else if (data.port) {
254
+ else if (isFeedPort(data.port)) {
706
255
  this.detachFeed();
707
256
  this.feed = data.port;
708
257
  this.feed.addEventListener("message", this.onFeedMessage);
@@ -752,130 +301,16 @@ if (typeof registerProcessor === "function") {
752
301
  }
753
302
  });
754
303
  }
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 = {}) {
304
+ // src/sync/live-pcm.ts
305
+ function loadLivePcmWorklet(context, options = {}) {
777
306
  return loadAudioWorklet(context, {
778
307
  fallbackToBlob: options.fallbackToBlob ?? true,
779
308
  fetchImpl: options.fetchImpl,
780
309
  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;
310
+ moduleUrl: options.inlineSource === void 0 ? options.moduleUrl ?? createWorkletModuleUrl("live-pcm") : void 0,
311
+ processorName: LIVE_PCM_PROCESSOR_NAME
874
312
  });
875
313
  }
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 };
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 };
880
315
 
881
316
  //# sourceMappingURL=index.js.map