@avoid.quest/audio 0.1.0 → 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.
Files changed (41) hide show
  1. package/README.md +30 -2
  2. package/dist/effects/index.d.ts +21 -72
  3. package/dist/effects/index.js +212 -505
  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 +0 -24
  8. package/dist/midi/index.js +222 -258
  9. package/dist/midi/index.js.map +1 -1
  10. package/dist/native-Bern4_PB.js +172 -0
  11. package/dist/native-Bern4_PB.js.map +1 -0
  12. package/dist/pcm-buffer-DSzGHbon.js +436 -0
  13. package/dist/pcm-buffer-DSzGHbon.js.map +1 -0
  14. package/dist/playback/index.d.ts +60 -114
  15. package/dist/playback/index.js +899 -1062
  16. package/dist/playback/index.js.map +1 -1
  17. package/dist/queue/index.d.ts +8 -19
  18. package/dist/queue/index.js +461 -960
  19. package/dist/queue/index.js.map +1 -1
  20. package/dist/recognize/index.d.ts +37 -74
  21. package/dist/recognize/index.js +172 -2715
  22. package/dist/recognize/index.js.map +1 -1
  23. package/dist/routing/index.d.ts +3 -34
  24. package/dist/routing/index.js +413 -536
  25. package/dist/routing/index.js.map +1 -1
  26. package/dist/shazam-gBrX1NEY.d.ts +27 -0
  27. package/dist/sync/index.d.ts +9 -77
  28. package/dist/sync/index.js +320 -542
  29. package/dist/sync/index.js.map +1 -1
  30. package/dist/{worklet-loader-BvEW0oVO.d.ts → worklet-loader-BabwPALw.d.ts} +4 -7
  31. package/dist/{worklet-loader-S7R8ZAmP.js → worklet-loader-f741D1tk.js} +37 -52
  32. package/dist/worklet-loader-f741D1tk.js.map +1 -0
  33. package/dist/worklets/couch-live.js +110 -192
  34. package/dist/worklets/couch-live.js.map +1 -1
  35. package/dist/worklets/meter.js +14 -20
  36. package/dist/worklets/meter.js.map +1 -1
  37. package/dist/worklets/pcm-capture.d.ts +6 -0
  38. package/dist/worklets/pcm-capture.js +52 -0
  39. package/dist/worklets/pcm-capture.js.map +1 -0
  40. package/package.json +8 -3
  41. package/dist/worklet-loader-S7R8ZAmP.js.map +0 -1
@@ -1,8 +1,8 @@
1
- import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-S7R8ZAmP.js";
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
2
  import { Effect, Scope } from "effect";
3
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";
4
5
  // src/sync/cca1.ts
5
- /** ASCII `"CCA1"` little-endian uint32 magic (`0x31414343`). */
6
6
  const CCA1_MAGIC = 826360643;
7
7
  const CCA1_HEADER_BYTES = 40;
8
8
  const CCA1_FORMAT_F32_INTERLEAVED = 1;
@@ -15,49 +15,25 @@ const CCA1_ALLOWED_SAMPLE_RATES = [
15
15
  ];
16
16
  const CCA1_MAX_CLOCK_RTT_US = 1e5;
17
17
  const GENERATION_REGEX = /^[\w-]{1,64}$/u;
18
- /**
19
- * Validates a `"CCA1"` timestamped audio packet's header fields and PCM samples.
20
- */
18
+ const syncFail = (code, message) => Effect.fail(new AudioSyncError({
19
+ code,
20
+ message
21
+ }));
21
22
  function validateCca1Packet(packet) {
22
- if (packet.generation !== void 0 && !GENERATION_REGEX.test(packet.generation)) return Effect.fail(new AudioSyncError({
23
- code: "INVALID_HEADER",
24
- message: "Invalid CCA1 generation identifier."
25
- }));
26
- if (!Number.isSafeInteger(packet.sequence) || packet.sequence < 0 || packet.sequence > 0xffffffff || !Number.isSafeInteger(packet.samplePosition) || packet.samplePosition < 0 || !Number.isSafeInteger(packet.capturedAtUs)) return Effect.fail(new AudioSyncError({
27
- code: "INVALID_HEADER",
28
- message: "Invalid CCA1 sequence, samplePosition, or capturedAtUs."
29
- }));
30
- if (!CCA1_ALLOWED_SAMPLE_RATES.includes(packet.sampleRate)) return Effect.fail(new AudioSyncError({
31
- code: "INVALID_HEADER",
32
- message: `Unsupported CCA1 sampleRate: ${packet.sampleRate}.`
33
- }));
34
- if (packet.channels !== 1 && packet.channels !== 2) return Effect.fail(new AudioSyncError({
35
- code: "INVALID_HEADER",
36
- message: `Invalid CCA1 channel count: ${String(packet.channels)}.`
37
- }));
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.");
38
26
  const frames = packet.pcm.length / packet.channels;
39
- if (packet.pcm.length === 0 || packet.pcm.length % packet.channels !== 0 || frames > 4096) return Effect.fail(new AudioSyncError({
40
- code: "INVALID_FRAME",
41
- message: "Invalid CCA1 PCM frame length."
42
- }));
27
+ if (packet.pcm.length === 0 || packet.pcm.length % packet.channels !== 0 || frames > 4096) return syncFail("INVALID_FRAME", "Invalid CCA1 PCM frame length.");
43
28
  for (let i = 0; i < packet.pcm.length; i += 1) {
44
29
  const sample = packet.pcm[i] ?? NaN;
45
- if (!Number.isFinite(sample) || Math.abs(sample) > 8) return Effect.fail(new AudioSyncError({
46
- code: "INVALID_SAMPLE",
47
- message: `Invalid CCA1 PCM sample at index ${i}.`
48
- }));
30
+ if (!Number.isFinite(sample) || Math.abs(sample) > 8) return syncFail("INVALID_SAMPLE", `Invalid CCA1 PCM sample at index ${i}.`);
49
31
  }
50
32
  return Effect.succeed(packet);
51
33
  }
52
- /**
53
- * Encodes a timestamped interleaved Float32 PCM packet into Couch's 40-byte
54
- * little-endian `"CCA1"` binary frame (`Uint8Array`, 100% isomorphic).
55
- */
56
34
  function encodeCca1Frame(packet) {
57
- return Effect.map(validateCca1Packet(packet), (valid) => {
58
- const frames = valid.pcm.length / valid.channels;
59
- const pcmBytes = valid.pcm.length * 4;
60
- const out = new Uint8Array(40 + pcmBytes);
35
+ return validateCca1Packet(packet).pipe(Effect.map((valid) => {
36
+ const out = new Uint8Array(40 + valid.pcm.length * 4);
61
37
  const view = new DataView(out.buffer);
62
38
  view.setUint32(0, CCA1_MAGIC, true);
63
39
  view.setUint8(4, valid.channels);
@@ -67,72 +43,35 @@ function encodeCca1Frame(packet) {
67
43
  view.setUint32(12, valid.sequence, true);
68
44
  view.setBigUint64(16, BigInt(valid.samplePosition), true);
69
45
  view.setBigInt64(24, BigInt(valid.capturedAtUs), true);
70
- view.setUint32(32, frames, true);
46
+ view.setUint32(32, valid.pcm.length / valid.channels, true);
71
47
  view.setUint32(36, 0, true);
72
48
  for (let i = 0; i < valid.pcm.length; i += 1) view.setFloat32(40 + i * 4, valid.pcm[i] ?? 0, true);
73
49
  return out;
74
- });
50
+ }));
75
51
  }
76
- /**
77
- * Decodes a 40-byte little-endian `"CCA1"` binary frame into a validated `Cca1Packet`.
78
- * Optionally adds `clockOffsetUs` and attaches `generation`.
79
- */
80
52
  function decodeCca1Frame(data, options = {}) {
81
53
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
82
- if (bytes.byteLength < 44 || bytes.byteLength > 32808) return Effect.fail(new AudioSyncError({
83
- code: "INVALID_FRAME",
84
- message: `CCA1 frame length ${bytes.byteLength} is out of bounds.`
85
- }));
54
+ if (bytes.byteLength < 44 || bytes.byteLength > 32808) return syncFail("INVALID_FRAME", `CCA1 frame length ${bytes.byteLength} is out of bounds.`);
86
55
  const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
87
- const magic = view.getUint32(0, true);
88
- const channels = view.getUint8(4);
89
- const format = view.getUint8(5);
90
- const headerBytes = view.getUint16(6, true);
91
- const sampleRate = view.getUint32(8, true);
92
- const sequence = view.getUint32(12, true);
93
- const samplePosition = Number(view.getBigUint64(16, true));
94
- const rawCapturedAtUs = Number(view.getBigInt64(24, true));
95
- const frames = view.getUint32(32, true);
96
- const reserved = view.getUint32(36, true);
97
- if (magic !== 826360643 || headerBytes !== 40 || format !== 1 || reserved !== 0) return Effect.fail(new AudioSyncError({
98
- code: "INVALID_HEADER",
99
- message: "Invalid CCA1 binary header."
100
- }));
101
56
  const payloadBytes = bytes.byteLength - 40;
102
- if (payloadBytes % 4 !== 0) return Effect.fail(new AudioSyncError({
103
- code: "INVALID_FRAME",
104
- message: "CCA1 PCM payload is not 4-byte aligned."
105
- }));
57
+ if (payloadBytes % 4 !== 0) return syncFail("INVALID_FRAME", "CCA1 PCM payload is not 4-byte aligned.");
58
+ const channels = view.getUint8(4);
106
59
  const sampleCount = payloadBytes / 4;
107
- if (channels !== 1 && channels !== 2) return Effect.fail(new AudioSyncError({
108
- code: "INVALID_HEADER",
109
- message: `Invalid CCA1 channels: ${channels}.`
110
- }));
111
- if (frames !== sampleCount / channels) return Effect.fail(new AudioSyncError({
112
- code: "INVALID_HEADER",
113
- message: "CCA1 header frame count does not match PCM payload length."
114
- }));
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.");
115
62
  const pcm = new Float32Array(sampleCount);
116
63
  for (let i = 0; i < sampleCount; i += 1) pcm[i] = view.getFloat32(40 + i * 4, true);
117
64
  return validateCca1Packet({
118
- capturedAtUs: Math.round(rawCapturedAtUs + (options.clockOffsetUs ?? 0)),
65
+ capturedAtUs: Math.round(Number(view.getBigInt64(24, true)) + (options.clockOffsetUs ?? 0)),
119
66
  channels,
120
67
  generation: options.generation,
121
68
  pcm,
122
- samplePosition,
123
- sampleRate,
124
- sequence
69
+ samplePosition: Number(view.getBigUint64(16, true)),
70
+ sampleRate: view.getUint32(8, true),
71
+ sequence: view.getUint32(12, true)
125
72
  });
126
73
  }
127
- /**
128
- * Computes Couch's `"CCA1"` clock handshake offset from ping samples, picking
129
- * the lowest-RTT sample and rejecting RTTs above `maxRttUs` (default 100 ms).
130
- */
131
74
  function computeClockHandshake(samples, maxRttUs = CCA1_MAX_CLOCK_RTT_US) {
132
- if (samples.length === 0) return Effect.fail(new AudioSyncError({
133
- code: "CLOCK_RTT_EXCEEDED",
134
- message: "No clock handshake ping samples provided."
135
- }));
136
75
  let best;
137
76
  let bestRtt = Number.POSITIVE_INFINITY;
138
77
  for (const sample of samples) {
@@ -142,14 +81,10 @@ function computeClockHandshake(samples, maxRttUs = CCA1_MAX_CLOCK_RTT_US) {
142
81
  best = sample;
143
82
  }
144
83
  }
145
- if (!best || bestRtt > maxRttUs) return Effect.fail(new AudioSyncError({
146
- code: "CLOCK_RTT_EXCEEDED",
147
- message: `Clock handshake RTT ${bestRtt} µs exceeded max ${maxRttUs} µs.`
148
- }));
149
- const midpointUs = (best.clientReceivedUs + best.clientSentUs) / 2;
150
- const offsetUs = Math.round(best.serverUs - midpointUs);
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.`);
151
86
  return Effect.succeed({
152
- offsetUs,
87
+ offsetUs: Math.round(best.serverUs - (best.clientReceivedUs + best.clientSentUs) / 2),
153
88
  rttUs: bestRtt
154
89
  });
155
90
  }
@@ -175,7 +110,6 @@ function risenNeed(currentMs, readingsMs, allowanceMs = 0, window = 5) {
175
110
  // src/sync/live-buffer.ts
176
111
  const SDK_BATCH_MS = 15;
177
112
  const LIMIT_MS = 5e3;
178
- const MEASURE_SECONDS = 5;
179
113
  const SLEW_SECONDS = 10;
180
114
  const WINDOW_SECONDS = 10;
181
115
  const RUN_SECONDS = 3;
@@ -200,71 +134,58 @@ const SDK_LATE_STEPS = {
200
134
  ...NO_LATE_STEPS,
201
135
  partMs: 10
202
136
  };
203
- function partPause(part) {
204
- return Math.min(LONGEST_PAUSE_SECONDS, PAUSE_SECONDS * 2 ** part);
205
- }
206
- function pauseAfter(unhelpful, stepMs) {
137
+ const partPause = (part) => Math.min(LONGEST_PAUSE_SECONDS, PAUSE_SECONDS * 2 ** part);
138
+ const pauseAfter = (unhelpful, stepMs) => {
207
139
  let left = 0;
208
- for (let part = 0; part < stepMs / 10; part += 1) left += partPause(unhelpful + part);
140
+ for (let p = 0; p < stepMs / 10; p += 1) left += partPause(unhelpful + p);
209
141
  return Math.min(LONGEST_PAUSE_SECONDS, left);
210
- }
211
- function mostMs(unhelpful) {
142
+ };
143
+ const mostMs = (unhelpful) => {
212
144
  let parts = 1;
213
- for (let ahead = HOUR_SECONDS - partPause(unhelpful); ahead >= 0; parts += 1) ahead -= partPause(unhelpful + parts);
214
- for (let behind = HOUR_SECONDS, part = unhelpful - 1; part >= 0; part -= 1) {
215
- behind -= partPause(part);
216
- if (behind <= 0) break;
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;
217
149
  parts -= 1;
218
150
  }
219
151
  return Math.max(1, parts) * 10;
220
- }
152
+ };
221
153
  const FIRST_HOUR_MAX_LATE_MS = mostMs(0);
222
154
  const SUBSEQUENT_HOUR_MAX_LATE_MS = Math.floor(HOUR_SECONDS / LONGEST_PAUSE_SECONDS) * 10;
223
- function arrivalLateMs(sendAheadMs, stampUs, nowUs) {
224
- return sendAheadMs - (stampUs - nowUs) / 1e3;
225
- }
155
+ const arrivalLateMs = (sendAheadMs, stampUs, nowUs) => sendAheadMs - (stampUs - nowUs) / 1e3;
226
156
  function measuredLateMs(seconds) {
227
157
  const last = seconds.slice(-5);
228
- if (last.length < MEASURE_SECONDS) return;
158
+ if (last.length < 5) return;
229
159
  let lateMs = 0;
230
- for (let i = 0; i < last.length; i += 1) for (let j = i + 2; j < last.length; j += 1) {
231
- const a = last[i] ?? 0;
232
- const b = last[j] ?? 0;
233
- lateMs = Math.max(lateMs, Math.min(a, b));
234
- }
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));
235
161
  return Math.min(FIRST_HOUR_MAX_LATE_MS, Math.round(lateMs));
236
162
  }
237
- function declareLiveBuffer(declaredMs, latencyMs = [], allowanceMs = 0) {
163
+ const declareLiveBuffer = (declaredMs, latencyMs = [], allowanceMs = 0) => {
238
164
  const need = risenNeed(declaredMs, latencyMs, allowanceMs);
239
165
  return need === void 0 ? void 0 : Math.min(LIMIT_MS, need);
240
- }
241
- function lostIn(seconds) {
242
- return seconds.reduce((sum, second) => sum + second.lost, 0);
243
- }
244
- function median(values) {
245
- if (values.length === 0) return;
246
- const sorted = values.toSorted((a, b) => a - b);
247
- return sorted[Math.floor(sorted.length / 2)];
248
- }
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);
249
171
  function spellsIn(seconds) {
250
172
  const apart = [];
251
- let spells = 0;
252
- let run = 0;
253
- let longest = 0;
254
- let clean = APART_SECONDS;
255
- for (const second of seconds) {
256
- if (second.lost === 0) {
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) {
257
181
  run = 0;
258
182
  clean += 1;
259
183
  continue;
260
184
  }
261
- const lateMs = second.lateMs ?? 0;
262
- if (run === 0) spells += 1;
185
+ const lateMs = s.lateMs ?? 0;
186
+ spells += run === 0 ? 1 : 0;
263
187
  if (clean >= APART_SECONDS) apart.push(lateMs);
264
- else if (apart.length > 0) {
265
- const prev = apart.at(-1) ?? 0;
266
- apart[apart.length - 1] = Math.max(prev, lateMs);
267
- }
188
+ else if (apart.length > 0) apart[apart.length - 1] = Math.max(apart.at(-1) ?? 0, lateMs);
268
189
  clean = 0;
269
190
  run += 1;
270
191
  longest = Math.max(longest, run);
@@ -275,30 +196,23 @@ function spellsIn(seconds) {
275
196
  spells
276
197
  };
277
198
  }
278
- function stepOf(lateMs) {
279
- return Math.max(1, Math.ceil(lateMs / 10)) * 10;
280
- }
281
- function stepFor(lateMs) {
282
- return stepOf(lateMs.toSorted((a, b) => b - a)[1] ?? 0);
283
- }
284
- function runStep(run) {
285
- const lateValues = run.map((second) => second.lateMs ?? 0);
286
- const least = Math.min(...lateValues);
287
- const latest = Math.max(...lateValues);
288
- return stepOf(run.every((second) => second.lateMs !== void 0) && latest - least <= 10 ? latest : least);
289
- }
290
199
  function recurs(seconds) {
291
- const window = seconds.slice(-10);
292
- const run = window.slice(-3);
293
- if (run.length === RUN_SECONDS && run.every((second) => second.lost > 0)) return {
294
- count: lostIn(run),
295
- measure: "running",
296
- stepMs: runStep(run)
297
- };
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
+ }
298
212
  if (seconds.length < WINDOW_SECONDS) return;
299
- const recent = spellsIn(window);
213
+ const recent = spellsIn(win);
300
214
  if (recent.spells >= 2 || recent.longest >= RUN_SECONDS) return {
301
- count: lostIn(window),
215
+ count: lostIn(win),
302
216
  measure: "chunks",
303
217
  stepMs: stepFor(recent.apart)
304
218
  };
@@ -309,7 +223,7 @@ function recurs(seconds) {
309
223
  stepMs: stepFor(apart)
310
224
  } : void 0;
311
225
  }
312
- function ask(late, phase) {
226
+ const ask = (late, phase) => {
313
227
  const partMs = Math.min(phase.caused.stepMs - phase.askedMs, late.partMs ?? Number.POSITIVE_INFINITY);
314
228
  return {
315
229
  ...late,
@@ -324,17 +238,18 @@ function ask(late, phase) {
324
238
  ms: partMs
325
239
  }]
326
240
  };
327
- }
241
+ };
328
242
  function step(late, seconds, recurring) {
329
243
  const taken = late.taken.filter(({ at }) => late.counted - at < HOUR_SECONDS);
330
- const leftMs = (late.counted <= HOUR_SECONDS ? FIRST_HOUR_MAX_LATE_MS : SUBSEQUENT_HOUR_MAX_LATE_MS) - taken.reduce((sum, { ms }) => sum + ms, 0);
331
- const stepMs = Math.min(recurring.stepMs, mostMs(late.unhelpful), leftMs);
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));
332
246
  if (stepMs <= 0) return {
333
247
  ...late,
334
248
  caused: void 0,
335
249
  seconds,
336
250
  taken
337
251
  };
252
+ const aheads = seconds.flatMap((s) => s.sendAheadMs ?? []).toSorted((a, b) => a - b);
338
253
  return ask({
339
254
  ...late,
340
255
  caused: void 0,
@@ -349,37 +264,35 @@ function step(late, seconds, recurring) {
349
264
  },
350
265
  kind: "moving",
351
266
  landedMs: 0,
352
- sendAheadMs: median(seconds.flatMap((second) => second.sendAheadMs ?? [])),
267
+ sendAheadMs: aheads[Math.floor(aheads.length / 2)],
353
268
  waited: 0
354
269
  });
355
270
  }
356
- function move(late, phase, second) {
357
- const seconds = [...late.seconds, second].slice(-60);
358
- const waiting = {
271
+ function move(late, phase, second, seconds) {
272
+ const wait = () => ({
359
273
  ...late,
360
274
  phase: {
361
275
  ...phase,
362
276
  waited: phase.waited + 1
363
277
  },
364
278
  seconds
365
- };
366
- const done = (landedMs) => ({
279
+ });
280
+ const done = (stepMs) => ({
367
281
  ...late,
368
282
  caused: {
369
283
  ...phase.caused,
370
- stepMs: landedMs
284
+ stepMs
371
285
  },
372
286
  phase: WATCHING,
373
287
  seconds: []
374
288
  });
375
289
  if (phase.askedMs > phase.landedMs) {
376
- if (!(phase.sendAheadMs !== void 0 && second.sendAheadMs !== void 0 && second.sendAheadMs >= phase.sendAheadMs + (phase.askedMs + phase.landedMs) / 2)) return phase.waited + 1 < MOVING_SECONDS ? waiting : {
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() : {
377
291
  ...late,
378
292
  phase: WATCHING,
379
293
  seconds
380
294
  };
381
- if (second.syncErrorMs === void 0 && phase.askedMs === phase.caused.stepMs) return done(phase.askedMs);
382
- return {
295
+ return second.syncErrorMs === void 0 && phase.askedMs === phase.caused.stepMs ? done(phase.askedMs) : {
383
296
  ...late,
384
297
  phase: {
385
298
  ...phase,
@@ -391,31 +304,23 @@ function move(late, phase, second) {
391
304
  }
392
305
  const { syncErrorMs } = second;
393
306
  const settled = syncErrorMs !== void 0 && syncErrorMs > -8;
394
- if (!settled && phase.waited + 1 < SLEW_SECONDS) return waiting;
395
- if ((settled || syncErrorMs === void 0) && phase.landedMs < phase.caused.stepMs) return ask({
307
+ if (!settled && phase.waited + 1 < SLEW_SECONDS) return wait();
308
+ return (settled || syncErrorMs === void 0) && phase.landedMs < phase.caused.stepMs ? ask({
396
309
  ...late,
397
310
  seconds
398
- }, phase);
399
- return done(phase.landedMs);
311
+ }, phase) : done(phase.landedMs);
400
312
  }
401
- function halved(caused, recurring) {
402
- return caused.measure !== "spells" && caused.measure === recurring.measure && recurring.count * 2 <= caused.count;
403
- }
404
- /**
405
- * Advances Couch's adaptive late-step controller by one second of packet loss telemetry.
406
- */
407
313
  function nextLateSteps(before, second) {
408
314
  const late = {
409
315
  ...before,
410
316
  counted: before.counted + 1
411
317
  };
412
- const { phase } = late;
413
- if (phase.kind === "moving") return move(late, phase, second);
414
318
  const seconds = [...late.seconds, second].slice(-60);
319
+ const { phase } = late;
320
+ if (phase.kind === "moving") return move(late, phase, second, seconds);
415
321
  const recurring = recurs(seconds);
416
322
  const clean = recurring ? 0 : late.clean + 1;
417
- const stopped = late.caused?.measure === "running" && second.lost === 0;
418
- const next = clean >= FORGET_SECONDS || stopped ? {
323
+ const next = clean >= FORGET_SECONDS || late.caused?.measure === "running" && second.lost === 0 ? {
419
324
  ...late,
420
325
  caused: void 0,
421
326
  clean,
@@ -436,17 +341,16 @@ function nextLateSteps(before, second) {
436
341
  };
437
342
  if (!recurring) return next;
438
343
  const { caused } = next;
439
- if (caused === void 0 || running && caused.measure !== "running") return step(next, seconds, recurring);
440
- if (halved(caused, recurring)) return step({
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({
441
346
  ...next,
442
347
  unhelpful: 0
443
348
  }, seconds, recurring);
444
349
  const unhelpful = next.unhelpful + caused.stepMs / 10;
445
- if (running) return step({
350
+ return running ? step({
446
351
  ...next,
447
352
  unhelpful
448
- }, seconds, recurring);
449
- return {
353
+ }, seconds, recurring) : {
450
354
  ...next,
451
355
  caused: void 0,
452
356
  phase: {
@@ -456,19 +360,34 @@ function nextLateSteps(before, second) {
456
360
  unhelpful
457
361
  };
458
362
  }
459
- function withLateSteps(needMs, lateMs) {
460
- return Math.min(LIMIT_MS, needMs + lateMs);
461
- }
462
363
  // src/sync/live-lead.ts
463
364
  const LOG_EVERY_MS = 1e4;
464
365
  const INPUT_READINGS = 30;
465
366
  const INPUT_PART_SECONDS = 2;
466
367
  const MEASURE_MS = 1e3;
467
- /**
468
- * Tracks capture-to-send input-side latency per codec wire (`"opus" | "pcm"`)
469
- * and computes monotonically non-decreasing 5 ms quantized playback leads per listener.
470
- */
471
- function createLiveLead(log = () => {}, nowMs = () => Date.now()) {
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()) {
472
391
  const inputs = /* @__PURE__ */ new Map();
473
392
  const listeners = /* @__PURE__ */ new Map();
474
393
  const logged = /* @__PURE__ */ new Map();
@@ -486,27 +405,7 @@ function createLiveLead(log = () => {}, nowMs = () => Date.now()) {
486
405
  input.firstUs ??= nowUs;
487
406
  const second = Math.floor((nowUs - input.firstUs) / 1e6);
488
407
  if (second !== input.second) {
489
- if (input.second > 0) {
490
- input.readings = [...input.readings, input.highest].slice(-30);
491
- const beforeMs = input.ms;
492
- const beforeRisen = input.risen;
493
- if (input.ms === void 0 || input.held) {
494
- const initial = risenNeed(void 0, input.readings);
495
- input.ms = initial;
496
- input.risen = initial;
497
- input.held = false;
498
- } else {
499
- input.risen = risenNeed(input.risen, input.readings, 0, INPUT_READINGS);
500
- if (input.risen !== void 0 && input.ms < input.risen && second - (input.partSecond ?? Number.NEGATIVE_INFINITY) >= INPUT_PART_SECONDS) {
501
- input.ms = Math.min(input.risen, input.ms + 5);
502
- input.partSecond = second;
503
- }
504
- }
505
- if (input.ms !== beforeMs || input.risen !== beforeRisen) {
506
- const risingNote = input.ms !== void 0 && input.risen !== void 0 && input.ms < input.risen ? `, rising to ${input.risen} ms` : "";
507
- log(`live input side ${wire}: ${String(input.ms)} ms${risingNote}`);
508
- }
509
- }
408
+ if (input.second > 0) advanceWireSecond(wire, input, second, log);
510
409
  input.second = second;
511
410
  input.highest = Number.NEGATIVE_INFINITY;
512
411
  }
@@ -531,22 +430,21 @@ function createLiveLead(log = () => {}, nowMs = () => Date.now()) {
531
430
  });
532
431
  return step;
533
432
  },
534
- left(clientId) {
433
+ left: (clientId) => {
535
434
  listeners.delete(clientId);
536
435
  },
537
- measureMs(wire) {
436
+ measureMs: (wire) => {
538
437
  const inputMs = inputs.get(wire)?.ms;
539
438
  return inputMs === void 0 ? void 0 : liveStep(inputMs + MEASURE_MS);
540
439
  },
541
440
  restart() {
542
441
  for (const input of inputs.values()) {
543
- const held = input.ms !== void 0;
442
+ input.held = input.ms !== void 0;
544
443
  input.firstUs = void 0;
545
444
  input.second = 0;
546
445
  input.highest = Number.NEGATIVE_INFINITY;
547
446
  input.readings = [];
548
447
  input.partSecond = void 0;
549
- input.held = held;
550
448
  }
551
449
  listeners.clear();
552
450
  }
@@ -558,15 +456,7 @@ const DEADBAND_SEC = .001;
558
456
  const SLEW_RATE = .003;
559
457
  const REPLACE_SEC = .2;
560
458
  const JOIN_US = 1e3;
561
- /**
562
- * Maps a page performance timestamp (ms) to the corresponding AudioContext frame.
563
- */
564
- function contextFrame(clock, pageMs) {
565
- return (clock.offset + pageMs / 1e3) * clock.sampleRate;
566
- }
567
- /**
568
- * Estimates Worker-vs-Page monotonic clock skew using the minimum observed offset.
569
- */
459
+ const contextFrame = (clock, pageMs) => (clock.offset + pageMs / 1e3) * clock.sampleRate;
570
460
  function pageClock() {
571
461
  let aheadMs = Number.POSITIVE_INFINITY;
572
462
  return {
@@ -576,18 +466,16 @@ function pageClock() {
576
466
  }
577
467
  };
578
468
  }
579
- function noStats() {
580
- return {
581
- chunks: 0,
582
- corrections: 0,
583
- errorMax: Number.NEGATIVE_INFINITY,
584
- errorMin: Number.POSITIVE_INFINITY,
585
- filled: 0,
586
- lost: 0,
587
- skipped: 0,
588
- slack: Number.POSITIVE_INFINITY
589
- };
590
- }
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
+ });
591
479
  function addStats(totals, stats) {
592
480
  totals.chunks += stats.chunks;
593
481
  totals.lost += stats.lost;
@@ -598,20 +486,21 @@ function addStats(totals, stats) {
598
486
  totals.errorMax = Math.max(totals.errorMax, stats.errorMax);
599
487
  totals.corrections += stats.corrections;
600
488
  }
601
- function interpolateSample(samples, nextChunk, channelIndex, index, fraction) {
602
- const sample = samples[index] ?? 0;
603
- if (fraction === 0) return sample;
604
- if (index + 1 < samples.length) return sample + ((samples[index + 1] ?? sample) - sample) * fraction;
605
- const nextSamples = nextChunk?.channels[channelIndex] ?? nextChunk?.channels[0];
606
- return sample + ((nextSamples && nextSamples.length > 0 ? nextSamples[0] ?? sample : sample) - sample) * fraction;
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;
607
503
  }
608
- /**
609
- * Sample-accurate audio timeline used inside the `"couch-live"` AudioWorklet.
610
- * Backed by a fixed-capacity ring buffer (zero `Array.prototype.shift()`, zero
611
- * allocations during `render()`), dropping the oldest chunk on overflow,
612
- * slewing smoothly at ±0.3% outside a 1 ms deadband, and hard re-placing beyond
613
- * 200 ms error.
614
- */
615
504
  var LiveTimeline = class {
616
505
  capacity;
617
506
  ring;
@@ -629,9 +518,8 @@ var LiveTimeline = class {
629
518
  stats = noStats();
630
519
  constructor(sampleRate, capacity = 256) {
631
520
  this.sampleRate = sampleRate;
632
- const normalizedCapacity = Number.isFinite(capacity) ? Math.max(2, Math.floor(capacity)) : 256;
633
- this.capacity = normalizedCapacity;
634
- this.ring = Array.from({ length: normalizedCapacity });
521
+ this.capacity = Number.isFinite(capacity) ? Math.max(2, Math.floor(capacity)) : 256;
522
+ this.ring = Array.from({ length: this.capacity });
635
523
  }
636
524
  get length() {
637
525
  return this.count;
@@ -640,37 +528,20 @@ var LiveTimeline = class {
640
528
  return this.capacity;
641
529
  }
642
530
  reset() {
643
- for (let i = 0; i < this.capacity; i += 1) this.ring[i] = void 0;
531
+ this.ring.fill(void 0);
644
532
  this.head = 0;
645
533
  this.tail = 0;
646
534
  this.count = 0;
647
- this.position = 0;
648
- this.playing = false;
649
535
  this.dry = false;
650
- this.settling = false;
651
- this.correcting = 0;
652
- this.rate = 1;
653
536
  this.endStampUs = void 0;
654
- this.resetStatsInPlace();
537
+ this.stopSlew(true);
538
+ resetStats(this.stats);
655
539
  }
656
540
  takeStats() {
657
- const snapshot = {
658
- chunks: this.stats.chunks,
659
- corrections: this.stats.corrections,
660
- errorMax: this.stats.errorMax,
661
- errorMin: this.stats.errorMin,
662
- filled: this.stats.filled,
663
- lost: this.stats.lost,
664
- skipped: this.stats.skipped,
665
- slack: this.stats.slack
666
- };
667
- this.resetStatsInPlace();
668
- return snapshot;
541
+ const snap = noStats();
542
+ this.takeStatsInto(snap);
543
+ return snap;
669
544
  }
670
- /**
671
- * Copies accumulated stats into a preallocated target object and resets
672
- * counters in place with zero heap allocation (safe for AudioWorklet use).
673
- */
674
545
  takeStatsInto(target) {
675
546
  target.chunks = this.stats.chunks;
676
547
  target.corrections = this.stats.corrections;
@@ -680,47 +551,22 @@ var LiveTimeline = class {
680
551
  target.lost = this.stats.lost;
681
552
  target.skipped = this.stats.skipped;
682
553
  target.slack = this.stats.slack;
683
- this.resetStatsInPlace();
554
+ resetStats(this.stats);
684
555
  }
685
- resetStatsInPlace() {
686
- this.stats.chunks = 0;
687
- this.stats.corrections = 0;
688
- this.stats.errorMax = Number.NEGATIVE_INFINITY;
689
- this.stats.errorMin = Number.POSITIVE_INFINITY;
690
- this.stats.filled = 0;
691
- this.stats.lost = 0;
692
- this.stats.skipped = 0;
693
- this.stats.slack = Number.POSITIVE_INFINITY;
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;
694
562
  }
695
- peek(offset) {
696
- if (offset < 0 || offset >= this.count) return;
697
- return this.ring[(this.head + offset) % this.capacity];
563
+ at(offset) {
564
+ return offset < this.count ? this.ring[(this.head + offset) % this.capacity] : void 0;
698
565
  }
699
- dequeue() {
700
- if (this.count === 0) return;
701
- const item = this.ring[this.head];
566
+ dropHead() {
702
567
  this.ring[this.head] = void 0;
703
568
  this.head = (this.head + 1) % this.capacity;
704
569
  this.count -= 1;
705
- return item;
706
- }
707
- enqueue(chunk) {
708
- if (this.count === this.capacity) {
709
- this.ring[this.head] = void 0;
710
- this.head = (this.head + 1) % this.capacity;
711
- this.count -= 1;
712
- this.stats.lost += 1;
713
- if (this.playing) {
714
- this.playing = false;
715
- this.position = 0;
716
- this.settling = false;
717
- this.correcting = 0;
718
- this.rate = 1;
719
- }
720
- }
721
- this.ring[this.tail] = chunk;
722
- this.tail = (this.tail + 1) % this.capacity;
723
- this.count += 1;
724
570
  }
725
571
  push(chunk, next) {
726
572
  if ((chunk.channels[0]?.length ?? 0) === 0) return;
@@ -730,17 +576,24 @@ var LiveTimeline = class {
730
576
  this.stats.slack = Math.min(this.stats.slack, slack);
731
577
  if (slack < 0 || this.dry && follows) this.stats.lost += 1;
732
578
  this.dry = false;
733
- this.enqueue(chunk);
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;
734
587
  }
735
588
  render(frame, output) {
736
589
  const frames = output[0]?.length ?? 0;
737
590
  if (this.playing) this.steer(frame);
738
- const channelCount = output.length;
591
+ const chCount = output.length;
739
592
  for (let i = 0; i < frames; i += 1) {
740
593
  if (!this.playing && !this.place(frame + i)) {
741
- for (let c = 0; c < channelCount; c += 1) {
742
- const outChannel = output[c];
743
- if (outChannel) outChannel[i] = 0;
594
+ for (let c = 0; c < chCount; c += 1) {
595
+ const outCh = output[c];
596
+ if (outCh) outCh[i] = 0;
744
597
  }
745
598
  if (this.dry) this.stats.filled += 1;
746
599
  continue;
@@ -750,98 +603,75 @@ var LiveTimeline = class {
750
603
  }
751
604
  queued() {
752
605
  let frames = -this.position;
753
- for (let i = 0; i < this.count; i += 1) {
754
- const chunk = this.ring[(this.head + i) % this.capacity];
755
- frames += chunk?.channels[0]?.length ?? 0;
756
- }
606
+ for (let i = 0; i < this.count; i += 1) frames += this.ring[(this.head + i) % this.capacity]?.channels[0]?.length ?? 0;
757
607
  return frames / this.rate;
758
608
  }
759
609
  place(frame) {
760
610
  while (this.count > 0) {
761
- const chunk = this.peek(0);
611
+ const chunk = this.at(0);
762
612
  if (!chunk) return false;
763
613
  const offset = Math.round(frame - chunk.frame);
764
- const length = chunk.channels[0]?.length ?? 0;
614
+ const len = chunk.channels[0]?.length ?? 0;
765
615
  if (offset < 0) return false;
766
- if (offset < length) {
616
+ if (offset < len) {
767
617
  this.stats.skipped += offset;
768
618
  this.position = offset;
769
619
  this.playing = true;
770
620
  return true;
771
621
  }
772
- this.stats.skipped += length;
773
- this.dequeue();
622
+ this.stats.skipped += len;
623
+ this.dropHead();
774
624
  }
775
625
  return false;
776
626
  }
777
627
  steer(frame) {
778
- const chunk = this.peek(0);
628
+ const chunk = this.at(0);
779
629
  if (!chunk) return;
780
- const error = chunk.frame + this.position - frame;
781
- this.stats.errorMin = Math.min(this.stats.errorMin, error);
782
- this.stats.errorMax = Math.max(this.stats.errorMax, error);
783
- if (Math.abs(error) > REPLACE_SEC * this.sampleRate) {
784
- this.playing = false;
785
- this.settling = false;
786
- this.correcting = 0;
787
- this.rate = 1;
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();
788
635
  return;
789
636
  }
790
- const sign = Math.sign(error);
791
- if (this.correcting === 0 && Math.abs(error) > DEADBAND_SEC * this.sampleRate) {
637
+ const sign = Math.sign(err);
638
+ if (this.correcting === 0 && Math.abs(err) > DEADBAND_SEC * this.sampleRate) {
792
639
  this.correcting = sign;
793
640
  this.settling = false;
794
641
  this.rate = 1 - sign * SLEW_RATE;
795
642
  this.stats.corrections += 1;
796
643
  } else if (this.correcting !== 0 && sign !== this.correcting) this.settling = true;
797
644
  }
798
- advancePosition(chunk, currentFrameIndex) {
799
- this.position += this.rate;
800
- if (this.settling) {
801
- const whole = Math.round(this.position);
802
- if (Math.abs(this.position - whole) < SLEW_RATE) {
803
- this.position = whole;
804
- this.rate = 1;
805
- this.correcting = 0;
806
- this.settling = false;
807
- }
808
- }
809
- const length = chunk.channels[0]?.length ?? 0;
810
- if (this.position < length) return;
811
- this.position -= length;
812
- this.endStampUs = chunk.stampUs + length / this.sampleRate * 1e6;
813
- this.dequeue();
814
- const nextChunk = this.peek(0);
815
- if (nextChunk) {
816
- const nextFrameIndex = currentFrameIndex + 1;
817
- const boundaryError = nextChunk.frame + this.position - nextFrameIndex;
818
- if (Math.abs(boundaryError) > REPLACE_SEC * this.sampleRate) {
819
- this.playing = false;
820
- this.settling = false;
821
- this.correcting = 0;
822
- this.rate = 1;
823
- this.position = 0;
824
- }
825
- return;
826
- }
827
- this.playing = false;
828
- this.dry = true;
829
- this.correcting = 0;
830
- this.settling = false;
831
- this.rate = 1;
832
- }
833
- read(output, i, currentFrameIndex) {
834
- const chunk = this.peek(0);
645
+ read(output, i, frameIdx) {
646
+ const chunk = this.at(0);
835
647
  if (!chunk) return;
836
- const next = this.peek(1);
837
- const index = Math.floor(this.position);
838
- const fraction = this.position - index;
839
- for (let c = 0; c < output.length; c += 1) {
840
- const outChannel = output[c];
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];
841
654
  const samples = chunk.channels[c] ?? chunk.channels[0];
842
- if (outChannel && samples) outChannel[i] = interpolateSample(samples, next, c, index, fraction);
655
+ if (outCh && samples) outCh[i] = interpolateSample(samples, next, c, idx, frac);
843
656
  }
844
- this.advancePosition(chunk, currentFrameIndex);
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);
845
675
  }
846
676
  };
847
677
  // src/worklets/couch-live.ts
@@ -850,16 +680,7 @@ if (typeof registerProcessor === "function") {
850
680
  const reportFrames = sampleRate / 10;
851
681
  registerProcessor(COUCH_LIVE_PROCESSOR_NAME, class CouchLiveProcessor extends AudioWorkletProcessor {
852
682
  timeline = new LiveTimeline(sampleRate);
853
- reportStats = {
854
- chunks: 0,
855
- corrections: 0,
856
- errorMax: Number.NEGATIVE_INFINITY,
857
- errorMin: Number.POSITIVE_INFINITY,
858
- filled: 0,
859
- lost: 0,
860
- skipped: 0,
861
- slack: Number.POSITIVE_INFINITY
862
- };
683
+ reportStats = noStats();
863
684
  reportPayload;
864
685
  epoch = 0;
865
686
  next = currentFrame;
@@ -867,39 +688,26 @@ if (typeof registerProcessor === "function") {
867
688
  feed;
868
689
  disposed = false;
869
690
  onFeedMessage = (msgEvent) => {
870
- if (this.disposed) return;
871
691
  const msg = msgEvent.data;
872
- if (!msg || typeof msg !== "object") return;
873
- if (msg.type === "dispose") {
874
- this.dispose();
875
- return;
876
- }
877
- if (msg.type === "chunk") {
878
- if (msg.chunk) this.timeline.push(msg.chunk, this.next);
879
- return;
880
- }
881
- if (msg.type === "reset") {
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") {
882
696
  this.timeline.reset();
883
697
  this.epoch = typeof msg.epoch === "number" ? msg.epoch : 0;
884
698
  }
885
699
  };
886
700
  onPortMessage = (event) => {
887
- if (this.disposed) return;
888
701
  const { data } = event;
889
- if (!data || typeof data !== "object") return;
890
- if (data.type === "dispose") {
891
- this.dispose();
892
- return;
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?.();
893
710
  }
894
- if (data.type === "poll") {
895
- this.flushReport();
896
- return;
897
- }
898
- if (!data.port) return;
899
- this.detachFeed();
900
- this.feed = data.port;
901
- this.feed.addEventListener("message", this.onFeedMessage);
902
- if (typeof this.feed.start === "function") this.feed.start();
903
711
  };
904
712
  constructor() {
905
713
  super();
@@ -908,12 +716,12 @@ if (typeof registerProcessor === "function") {
908
716
  stats: this.reportStats
909
717
  };
910
718
  this.port.addEventListener("message", this.onPortMessage);
911
- if (typeof this.port.start === "function") this.port.start();
719
+ this.port.start?.();
912
720
  }
913
721
  detachFeed() {
914
722
  if (!this.feed) return;
915
723
  this.feed.removeEventListener("message", this.onFeedMessage);
916
- if (typeof this.feed.close === "function") this.feed.close();
724
+ this.feed.close?.();
917
725
  this.feed = void 0;
918
726
  }
919
727
  dispose() {
@@ -922,7 +730,7 @@ if (typeof registerProcessor === "function") {
922
730
  this.detachFeed();
923
731
  this.timeline.reset();
924
732
  this.port.removeEventListener("message", this.onPortMessage);
925
- if (typeof this.port.close === "function") this.port.close();
733
+ this.port.close?.();
926
734
  }
927
735
  flushReport() {
928
736
  if (this.disposed || !this.feed) return;
@@ -947,17 +755,9 @@ if (typeof registerProcessor === "function") {
947
755
  // src/sync/sendspin.ts
948
756
  const SENDSPIN_BINARY_AUDIO_TYPE = 4;
949
757
  const SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S = .015;
950
- /**
951
- * Computes Couch's perceptual volume curve (`muted ? 0 : (volume / 100) ** 1.5`).
952
- */
953
758
  function computeLiveVolumeGain(volumePercent, muted) {
954
- if (muted) return 0;
955
- return (Math.max(0, Math.min(100, Number.isFinite(volumePercent) ? volumePercent : 100)) / 100) ** 1.5;
759
+ return muted ? 0 : (clampFinite(volumePercent, 0, 100, 100) / 100) ** 1.5;
956
760
  }
957
- /**
958
- * Sniffs a Sendspin binary audio packet header (`byte 0 === 4`, `int64BE` stamp
959
- * at bytes `1..8`, `uint32BE` `send_ahead` in µs at bytes `9..12`).
960
- */
961
761
  function sniffSendspinAudioHeader(data) {
962
762
  const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
963
763
  if (bytes.byteLength < 13 || bytes[0] !== 4) return;
@@ -968,22 +768,11 @@ function sniffSendspinAudioHeader(data) {
968
768
  stampUs: Number(view.getBigInt64(1, false))
969
769
  };
970
770
  }
971
- function collectTransferableBuffers(chunk) {
972
- const buffers = [];
771
+ function collectTransferables(chunk) {
973
772
  const seen = /* @__PURE__ */ new Set();
974
- for (const channel of chunk.channels) {
975
- const buf = channel.buffer;
976
- if (buf instanceof ArrayBuffer && buf.byteLength > 0 && !seen.has(buf)) {
977
- seen.add(buf);
978
- buffers.push(buf);
979
- }
980
- }
981
- return buffers;
773
+ for (const ch of chunk.channels) if (ch.buffer instanceof ArrayBuffer && ch.buffer.byteLength > 0) seen.add(ch.buffer);
774
+ return [...seen];
982
775
  }
983
- /**
984
- * Loads the standalone `@avoid.quest/audio/worklets/couch-live` AudioWorklet module
985
- * into `context` with Blob-URL fallback support.
986
- */
987
776
  function loadCouchLiveWorklet(context, options = {}) {
988
777
  return loadAudioWorklet(context, {
989
778
  fallbackToBlob: options.fallbackToBlob ?? true,
@@ -993,108 +782,97 @@ function loadCouchLiveWorklet(context, options = {}) {
993
782
  processorName: COUCH_LIVE_PROCESSOR_NAME
994
783
  });
995
784
  }
996
- /**
997
- * Creates a `Scope`-managed Sendspin / `LivePlayer` receiver wrapping the
998
- * `"couch-live"` AudioWorklet with an **injectable downstream `outputNode`**
999
- * (never hardcoded to `context.destination`).
1000
- */
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
+ }
1001
864
  function createSendspinReceiver(context, options = {}) {
1002
865
  return Effect.gen(function* () {
1003
866
  yield* loadCouchLiveWorklet(context, options.workletOptions);
1004
867
  if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
1005
868
  feature: "AudioWorkletNode",
1006
- message: "AudioWorkletNode is not available in this environment."
1007
- }));
1008
- const workletNode = new globalThis.AudioWorkletNode(context, COUCH_LIVE_PROCESSOR_NAME, {
1009
- numberOfInputs: 0,
1010
- numberOfOutputs: 1,
1011
- outputChannelCount: [2]
1012
- });
1013
- const outputGain = context.createGain();
1014
- let volumePercent = options.initialVolume ?? 100;
1015
- let muted = options.initialMuted ?? false;
1016
- outputGain.gain.value = computeLiveVolumeGain(volumePercent, muted);
1017
- let currentTarget = options.outputNode ?? context.destination;
1018
- workletNode.connect(outputGain);
1019
- outputGain.connect(currentTarget);
1020
- const channel = new MessageChannel();
1021
- const feedPort = channel.port2;
1022
- workletNode.port.postMessage({ port: channel.port1 }, [channel.port1]);
1023
- const onFeedMessage = (event) => {
1024
- if (event.data?.stats) options.onStats?.(event.data.epoch, event.data.stats);
1025
- };
1026
- if (options.onStats) {
1027
- feedPort.addEventListener("message", onFeedMessage);
1028
- if (typeof feedPort.start === "function") feedPort.start();
1029
- }
1030
- let epoch = 0;
1031
- let disposed = false;
1032
- const applyGain = () => {
1033
- const gain = computeLiveVolumeGain(volumePercent, muted);
1034
- if (typeof outputGain.gain.setTargetAtTime === "function") outputGain.gain.setTargetAtTime(gain, context.currentTime, SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S);
1035
- else outputGain.gain.value = gain;
1036
- return gain;
1037
- };
1038
- const dispose = () => {
1039
- if (disposed) return;
1040
- disposed = true;
1041
- try {
1042
- workletNode.port.postMessage({ type: "dispose" });
1043
- } catch {}
1044
- if (typeof workletNode.port.close === "function") workletNode.port.close();
1045
- feedPort.removeEventListener("message", onFeedMessage);
1046
- if (typeof feedPort.close === "function") feedPort.close();
1047
- workletNode.disconnect();
1048
- outputGain.disconnect();
1049
- };
1050
- yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(() => {
1051
- dispose();
869
+ message: "AudioWorkletNode is not available."
1052
870
  }));
1053
- return {
1054
- dispose,
1055
- feedPort,
1056
- outputGain,
1057
- pushChunk: (chunk) => {
1058
- if (disposed) return;
1059
- const transfer = collectTransferableBuffers(chunk);
1060
- feedPort.postMessage({
1061
- chunk,
1062
- type: "chunk"
1063
- }, transfer);
1064
- },
1065
- reconnectOutput: (nextOutputNode) => {
1066
- try {
1067
- outputGain.disconnect(currentTarget);
1068
- } catch {}
1069
- currentTarget = nextOutputNode;
1070
- outputGain.connect(currentTarget);
1071
- },
1072
- resetTimeline: (nextEpoch) => {
1073
- epoch = nextEpoch ?? epoch + 1;
1074
- feedPort.postMessage({
1075
- epoch,
1076
- type: "reset"
1077
- });
1078
- return epoch;
1079
- },
1080
- setMuted: (nextMuted) => {
1081
- muted = nextMuted;
1082
- applyGain();
1083
- return muted;
1084
- },
1085
- setVolume: (nextVolume) => {
1086
- volumePercent = Math.max(0, Math.min(100, nextVolume));
1087
- applyGain();
1088
- return volumePercent;
1089
- },
1090
- get targetNode() {
1091
- return currentTarget;
1092
- },
1093
- workletNode
1094
- };
871
+ const receiver = buildSendspinReceiver(context, options);
872
+ yield* Scope.addFinalizer(yield* Scope.Scope, Effect.sync(receiver.dispose));
873
+ return receiver;
1095
874
  });
1096
875
  }
1097
- /** Couch naming parity wrapper (`LivePlayer`) delegating to `createSendspinReceiver`. */
1098
876
  function createLivePlayer(context, options = {}) {
1099
877
  return createSendspinReceiver(context, options);
1100
878
  }