@avoid.quest/audio 0.0.0-stage → 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +70 -2
- package/dist/effects/index.d.ts +266 -0
- package/dist/effects/index.js +744 -0
- package/dist/effects/index.js.map +1 -0
- package/dist/errors-BT9HxDLn.js +74 -0
- package/dist/errors-BT9HxDLn.js.map +1 -0
- package/dist/errors-ChTQFwuZ.d.ts +53 -0
- package/dist/index.d.ts +3 -0
- package/dist/index.js +3 -0
- package/dist/midi/index.d.ts +162 -0
- package/dist/midi/index.js +338 -0
- package/dist/midi/index.js.map +1 -0
- package/dist/playback/index.d.ts +349 -0
- package/dist/playback/index.js +1372 -0
- package/dist/playback/index.js.map +1 -0
- package/dist/queue/index.d.ts +144 -0
- package/dist/queue/index.js +1062 -0
- package/dist/queue/index.js.map +1 -0
- package/dist/recognize/index.d.ts +161 -0
- package/dist/recognize/index.js +2816 -0
- package/dist/recognize/index.js.map +1 -0
- package/dist/routing/index.d.ts +140 -0
- package/dist/routing/index.js +678 -0
- package/dist/routing/index.js.map +1 -0
- package/dist/sync/index.d.ts +282 -0
- package/dist/sync/index.js +1103 -0
- package/dist/sync/index.js.map +1 -0
- package/dist/worklet-loader-BvEW0oVO.d.ts +44 -0
- package/dist/worklet-loader-S7R8ZAmP.js +175 -0
- package/dist/worklet-loader-S7R8ZAmP.js.map +1 -0
- package/dist/worklets/couch-live.d.ts +1 -0
- package/dist/worklets/couch-live.js +365 -0
- package/dist/worklets/couch-live.js.map +1 -0
- package/dist/worklets/meter.d.ts +7 -0
- package/dist/worklets/meter.js +80 -0
- package/dist/worklets/meter.js.map +1 -0
- package/package.json +109 -4
|
@@ -0,0 +1,1103 @@
|
|
|
1
|
+
import { i as loadAudioWorklet, n as createWorkletBlobUrl, r as createWorkletModuleUrl, t as VITE_AUDIO_WORKLET_OPTIMIZE_DEPS_EXCLUDE } from "../worklet-loader-S7R8ZAmP.js";
|
|
2
|
+
import { Effect, Scope } from "effect";
|
|
3
|
+
import { c as AudioSyncError, l as AudioUnsupportedError } from "../errors-BT9HxDLn.js";
|
|
4
|
+
// src/sync/cca1.ts
|
|
5
|
+
/** ASCII `"CCA1"` little-endian uint32 magic (`0x31414343`). */
|
|
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
|
+
/**
|
|
19
|
+
* Validates a `"CCA1"` timestamped audio packet's header fields and PCM samples.
|
|
20
|
+
*/
|
|
21
|
+
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
|
+
}));
|
|
38
|
+
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
|
+
}));
|
|
43
|
+
for (let i = 0; i < packet.pcm.length; i += 1) {
|
|
44
|
+
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
|
+
}));
|
|
49
|
+
}
|
|
50
|
+
return Effect.succeed(packet);
|
|
51
|
+
}
|
|
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
|
+
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);
|
|
61
|
+
const view = new DataView(out.buffer);
|
|
62
|
+
view.setUint32(0, CCA1_MAGIC, true);
|
|
63
|
+
view.setUint8(4, valid.channels);
|
|
64
|
+
view.setUint8(5, 1);
|
|
65
|
+
view.setUint16(6, 40, true);
|
|
66
|
+
view.setUint32(8, valid.sampleRate, true);
|
|
67
|
+
view.setUint32(12, valid.sequence, true);
|
|
68
|
+
view.setBigUint64(16, BigInt(valid.samplePosition), true);
|
|
69
|
+
view.setBigInt64(24, BigInt(valid.capturedAtUs), true);
|
|
70
|
+
view.setUint32(32, frames, true);
|
|
71
|
+
view.setUint32(36, 0, true);
|
|
72
|
+
for (let i = 0; i < valid.pcm.length; i += 1) view.setFloat32(40 + i * 4, valid.pcm[i] ?? 0, true);
|
|
73
|
+
return out;
|
|
74
|
+
});
|
|
75
|
+
}
|
|
76
|
+
/**
|
|
77
|
+
* Decodes a 40-byte little-endian `"CCA1"` binary frame into a validated `Cca1Packet`.
|
|
78
|
+
* Optionally adds `clockOffsetUs` and attaches `generation`.
|
|
79
|
+
*/
|
|
80
|
+
function decodeCca1Frame(data, options = {}) {
|
|
81
|
+
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
|
+
}));
|
|
86
|
+
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
|
+
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
|
+
}));
|
|
106
|
+
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
|
+
}));
|
|
115
|
+
const pcm = new Float32Array(sampleCount);
|
|
116
|
+
for (let i = 0; i < sampleCount; i += 1) pcm[i] = view.getFloat32(40 + i * 4, true);
|
|
117
|
+
return validateCca1Packet({
|
|
118
|
+
capturedAtUs: Math.round(rawCapturedAtUs + (options.clockOffsetUs ?? 0)),
|
|
119
|
+
channels,
|
|
120
|
+
generation: options.generation,
|
|
121
|
+
pcm,
|
|
122
|
+
samplePosition,
|
|
123
|
+
sampleRate,
|
|
124
|
+
sequence
|
|
125
|
+
});
|
|
126
|
+
}
|
|
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
|
+
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
|
+
let best;
|
|
137
|
+
let bestRtt = Number.POSITIVE_INFINITY;
|
|
138
|
+
for (const sample of samples) {
|
|
139
|
+
const rtt = sample.clientReceivedUs - sample.clientSentUs;
|
|
140
|
+
if (rtt >= 0 && rtt < bestRtt) {
|
|
141
|
+
bestRtt = rtt;
|
|
142
|
+
best = sample;
|
|
143
|
+
}
|
|
144
|
+
}
|
|
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);
|
|
151
|
+
return Effect.succeed({
|
|
152
|
+
offsetUs,
|
|
153
|
+
rttUs: bestRtt
|
|
154
|
+
});
|
|
155
|
+
}
|
|
156
|
+
// src/sync/live-need.ts
|
|
157
|
+
const LIVE_STEP_MS = 5;
|
|
158
|
+
const LIVE_LATE_STEP_MS = 10;
|
|
159
|
+
const LIVE_READINGS = 5;
|
|
160
|
+
function liveStep(needMs) {
|
|
161
|
+
return Math.ceil(needMs / 5) * 5;
|
|
162
|
+
}
|
|
163
|
+
/**
|
|
164
|
+
* Computes a monotonically rising buffered need from recent once-a-second readings.
|
|
165
|
+
* Sets immediately on the first reading; subsequently raises only when the median
|
|
166
|
+
* of the last `window` readings exceeds `currentMs + LIVE_STEP_MS`.
|
|
167
|
+
*/
|
|
168
|
+
function risenNeed(currentMs, readingsMs, allowanceMs = 0, window = 5) {
|
|
169
|
+
const recent = readingsMs.slice(-window).toSorted((a, b) => a - b);
|
|
170
|
+
if (recent.length === 0 || currentMs !== void 0 && recent.length < window) return currentMs;
|
|
171
|
+
const mid = recent[Math.floor(recent.length / 2)] ?? 0;
|
|
172
|
+
const need = Math.ceil(mid + allowanceMs);
|
|
173
|
+
return currentMs === void 0 || need > currentMs + 5 ? need : currentMs;
|
|
174
|
+
}
|
|
175
|
+
// src/sync/live-buffer.ts
|
|
176
|
+
const SDK_BATCH_MS = 15;
|
|
177
|
+
const LIMIT_MS = 5e3;
|
|
178
|
+
const MEASURE_SECONDS = 5;
|
|
179
|
+
const SLEW_SECONDS = 10;
|
|
180
|
+
const WINDOW_SECONDS = 10;
|
|
181
|
+
const RUN_SECONDS = 3;
|
|
182
|
+
const APART_SECONDS = 2;
|
|
183
|
+
const HORIZON_SPELLS = 3;
|
|
184
|
+
const MOVING_SECONDS = 3;
|
|
185
|
+
const PAUSE_SECONDS = 24;
|
|
186
|
+
const LONGEST_PAUSE_SECONDS = 384;
|
|
187
|
+
const FORGET_SECONDS = 960;
|
|
188
|
+
const HOUR_SECONDS = 3600;
|
|
189
|
+
const WATCHING = { kind: "watching" };
|
|
190
|
+
const NO_LATE_STEPS = {
|
|
191
|
+
clean: 0,
|
|
192
|
+
counted: 0,
|
|
193
|
+
lateMs: 0,
|
|
194
|
+
phase: WATCHING,
|
|
195
|
+
seconds: [],
|
|
196
|
+
taken: [],
|
|
197
|
+
unhelpful: 0
|
|
198
|
+
};
|
|
199
|
+
const SDK_LATE_STEPS = {
|
|
200
|
+
...NO_LATE_STEPS,
|
|
201
|
+
partMs: 10
|
|
202
|
+
};
|
|
203
|
+
function partPause(part) {
|
|
204
|
+
return Math.min(LONGEST_PAUSE_SECONDS, PAUSE_SECONDS * 2 ** part);
|
|
205
|
+
}
|
|
206
|
+
function pauseAfter(unhelpful, stepMs) {
|
|
207
|
+
let left = 0;
|
|
208
|
+
for (let part = 0; part < stepMs / 10; part += 1) left += partPause(unhelpful + part);
|
|
209
|
+
return Math.min(LONGEST_PAUSE_SECONDS, left);
|
|
210
|
+
}
|
|
211
|
+
function mostMs(unhelpful) {
|
|
212
|
+
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;
|
|
217
|
+
parts -= 1;
|
|
218
|
+
}
|
|
219
|
+
return Math.max(1, parts) * 10;
|
|
220
|
+
}
|
|
221
|
+
const FIRST_HOUR_MAX_LATE_MS = mostMs(0);
|
|
222
|
+
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
|
+
}
|
|
226
|
+
function measuredLateMs(seconds) {
|
|
227
|
+
const last = seconds.slice(-5);
|
|
228
|
+
if (last.length < MEASURE_SECONDS) return;
|
|
229
|
+
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
|
+
}
|
|
235
|
+
return Math.min(FIRST_HOUR_MAX_LATE_MS, Math.round(lateMs));
|
|
236
|
+
}
|
|
237
|
+
function declareLiveBuffer(declaredMs, latencyMs = [], allowanceMs = 0) {
|
|
238
|
+
const need = risenNeed(declaredMs, latencyMs, allowanceMs);
|
|
239
|
+
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
|
+
}
|
|
249
|
+
function spellsIn(seconds) {
|
|
250
|
+
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) {
|
|
257
|
+
run = 0;
|
|
258
|
+
clean += 1;
|
|
259
|
+
continue;
|
|
260
|
+
}
|
|
261
|
+
const lateMs = second.lateMs ?? 0;
|
|
262
|
+
if (run === 0) spells += 1;
|
|
263
|
+
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
|
+
}
|
|
268
|
+
clean = 0;
|
|
269
|
+
run += 1;
|
|
270
|
+
longest = Math.max(longest, run);
|
|
271
|
+
}
|
|
272
|
+
return {
|
|
273
|
+
apart,
|
|
274
|
+
longest,
|
|
275
|
+
spells
|
|
276
|
+
};
|
|
277
|
+
}
|
|
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
|
+
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
|
+
};
|
|
298
|
+
if (seconds.length < WINDOW_SECONDS) return;
|
|
299
|
+
const recent = spellsIn(window);
|
|
300
|
+
if (recent.spells >= 2 || recent.longest >= RUN_SECONDS) return {
|
|
301
|
+
count: lostIn(window),
|
|
302
|
+
measure: "chunks",
|
|
303
|
+
stepMs: stepFor(recent.apart)
|
|
304
|
+
};
|
|
305
|
+
const { spells, apart } = spellsIn(seconds);
|
|
306
|
+
return spells >= HORIZON_SPELLS ? {
|
|
307
|
+
count: spells,
|
|
308
|
+
measure: "spells",
|
|
309
|
+
stepMs: stepFor(apart)
|
|
310
|
+
} : void 0;
|
|
311
|
+
}
|
|
312
|
+
function ask(late, phase) {
|
|
313
|
+
const partMs = Math.min(phase.caused.stepMs - phase.askedMs, late.partMs ?? Number.POSITIVE_INFINITY);
|
|
314
|
+
return {
|
|
315
|
+
...late,
|
|
316
|
+
lateMs: late.lateMs + partMs,
|
|
317
|
+
phase: {
|
|
318
|
+
...phase,
|
|
319
|
+
askedMs: phase.askedMs + partMs,
|
|
320
|
+
waited: 0
|
|
321
|
+
},
|
|
322
|
+
taken: [...late.taken, {
|
|
323
|
+
at: late.counted,
|
|
324
|
+
ms: partMs
|
|
325
|
+
}]
|
|
326
|
+
};
|
|
327
|
+
}
|
|
328
|
+
function step(late, seconds, recurring) {
|
|
329
|
+
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);
|
|
332
|
+
if (stepMs <= 0) return {
|
|
333
|
+
...late,
|
|
334
|
+
caused: void 0,
|
|
335
|
+
seconds,
|
|
336
|
+
taken
|
|
337
|
+
};
|
|
338
|
+
return ask({
|
|
339
|
+
...late,
|
|
340
|
+
caused: void 0,
|
|
341
|
+
clean: 0,
|
|
342
|
+
seconds,
|
|
343
|
+
taken
|
|
344
|
+
}, {
|
|
345
|
+
askedMs: 0,
|
|
346
|
+
caused: {
|
|
347
|
+
...recurring,
|
|
348
|
+
stepMs
|
|
349
|
+
},
|
|
350
|
+
kind: "moving",
|
|
351
|
+
landedMs: 0,
|
|
352
|
+
sendAheadMs: median(seconds.flatMap((second) => second.sendAheadMs ?? [])),
|
|
353
|
+
waited: 0
|
|
354
|
+
});
|
|
355
|
+
}
|
|
356
|
+
function move(late, phase, second) {
|
|
357
|
+
const seconds = [...late.seconds, second].slice(-60);
|
|
358
|
+
const waiting = {
|
|
359
|
+
...late,
|
|
360
|
+
phase: {
|
|
361
|
+
...phase,
|
|
362
|
+
waited: phase.waited + 1
|
|
363
|
+
},
|
|
364
|
+
seconds
|
|
365
|
+
};
|
|
366
|
+
const done = (landedMs) => ({
|
|
367
|
+
...late,
|
|
368
|
+
caused: {
|
|
369
|
+
...phase.caused,
|
|
370
|
+
stepMs: landedMs
|
|
371
|
+
},
|
|
372
|
+
phase: WATCHING,
|
|
373
|
+
seconds: []
|
|
374
|
+
});
|
|
375
|
+
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 : {
|
|
377
|
+
...late,
|
|
378
|
+
phase: WATCHING,
|
|
379
|
+
seconds
|
|
380
|
+
};
|
|
381
|
+
if (second.syncErrorMs === void 0 && phase.askedMs === phase.caused.stepMs) return done(phase.askedMs);
|
|
382
|
+
return {
|
|
383
|
+
...late,
|
|
384
|
+
phase: {
|
|
385
|
+
...phase,
|
|
386
|
+
landedMs: phase.askedMs,
|
|
387
|
+
waited: 0
|
|
388
|
+
},
|
|
389
|
+
seconds
|
|
390
|
+
};
|
|
391
|
+
}
|
|
392
|
+
const { syncErrorMs } = second;
|
|
393
|
+
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({
|
|
396
|
+
...late,
|
|
397
|
+
seconds
|
|
398
|
+
}, phase);
|
|
399
|
+
return done(phase.landedMs);
|
|
400
|
+
}
|
|
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
|
+
function nextLateSteps(before, second) {
|
|
408
|
+
const late = {
|
|
409
|
+
...before,
|
|
410
|
+
counted: before.counted + 1
|
|
411
|
+
};
|
|
412
|
+
const { phase } = late;
|
|
413
|
+
if (phase.kind === "moving") return move(late, phase, second);
|
|
414
|
+
const seconds = [...late.seconds, second].slice(-60);
|
|
415
|
+
const recurring = recurs(seconds);
|
|
416
|
+
const clean = recurring ? 0 : late.clean + 1;
|
|
417
|
+
const stopped = late.caused?.measure === "running" && second.lost === 0;
|
|
418
|
+
const next = clean >= FORGET_SECONDS || stopped ? {
|
|
419
|
+
...late,
|
|
420
|
+
caused: void 0,
|
|
421
|
+
clean,
|
|
422
|
+
seconds,
|
|
423
|
+
unhelpful: 0
|
|
424
|
+
} : {
|
|
425
|
+
...late,
|
|
426
|
+
clean,
|
|
427
|
+
seconds
|
|
428
|
+
};
|
|
429
|
+
const running = recurring?.measure === "running";
|
|
430
|
+
if (phase.kind === "pausing" && !running) return {
|
|
431
|
+
...next,
|
|
432
|
+
phase: phase.left > 1 ? {
|
|
433
|
+
kind: "pausing",
|
|
434
|
+
left: phase.left - 1
|
|
435
|
+
} : WATCHING
|
|
436
|
+
};
|
|
437
|
+
if (!recurring) return next;
|
|
438
|
+
const { caused } = next;
|
|
439
|
+
if (caused === void 0 || running && caused.measure !== "running") return step(next, seconds, recurring);
|
|
440
|
+
if (halved(caused, recurring)) return step({
|
|
441
|
+
...next,
|
|
442
|
+
unhelpful: 0
|
|
443
|
+
}, seconds, recurring);
|
|
444
|
+
const unhelpful = next.unhelpful + caused.stepMs / 10;
|
|
445
|
+
if (running) return step({
|
|
446
|
+
...next,
|
|
447
|
+
unhelpful
|
|
448
|
+
}, seconds, recurring);
|
|
449
|
+
return {
|
|
450
|
+
...next,
|
|
451
|
+
caused: void 0,
|
|
452
|
+
phase: {
|
|
453
|
+
kind: "pausing",
|
|
454
|
+
left: pauseAfter(next.unhelpful, caused.stepMs)
|
|
455
|
+
},
|
|
456
|
+
unhelpful
|
|
457
|
+
};
|
|
458
|
+
}
|
|
459
|
+
function withLateSteps(needMs, lateMs) {
|
|
460
|
+
return Math.min(LIMIT_MS, needMs + lateMs);
|
|
461
|
+
}
|
|
462
|
+
// src/sync/live-lead.ts
|
|
463
|
+
const LOG_EVERY_MS = 1e4;
|
|
464
|
+
const INPUT_READINGS = 30;
|
|
465
|
+
const INPUT_PART_SECONDS = 2;
|
|
466
|
+
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()) {
|
|
472
|
+
const inputs = /* @__PURE__ */ new Map();
|
|
473
|
+
const listeners = /* @__PURE__ */ new Map();
|
|
474
|
+
const logged = /* @__PURE__ */ new Map();
|
|
475
|
+
return {
|
|
476
|
+
arrived(wire, capturedAtUs, nowUs) {
|
|
477
|
+
let input = inputs.get(wire);
|
|
478
|
+
if (!input) {
|
|
479
|
+
input = {
|
|
480
|
+
highest: Number.NEGATIVE_INFINITY,
|
|
481
|
+
readings: [],
|
|
482
|
+
second: 0
|
|
483
|
+
};
|
|
484
|
+
inputs.set(wire, input);
|
|
485
|
+
}
|
|
486
|
+
input.firstUs ??= nowUs;
|
|
487
|
+
const second = Math.floor((nowUs - input.firstUs) / 1e6);
|
|
488
|
+
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
|
+
}
|
|
510
|
+
input.second = second;
|
|
511
|
+
input.highest = Number.NEGATIVE_INFINITY;
|
|
512
|
+
}
|
|
513
|
+
input.highest = Math.max(input.highest, (nowUs - capturedAtUs) / 1e3);
|
|
514
|
+
},
|
|
515
|
+
leadMs(clientId, wire, declaredMs, name = clientId) {
|
|
516
|
+
const known = listeners.get(clientId);
|
|
517
|
+
const inputMs = inputs.get(wire)?.ms;
|
|
518
|
+
if (inputMs === void 0 || declaredMs === void 0) return known?.step ?? 0;
|
|
519
|
+
const step = Math.max(known?.step ?? 0, liveStep(declaredMs + inputMs));
|
|
520
|
+
const last = logged.get(clientId);
|
|
521
|
+
if ((step !== known?.step || declaredMs !== known?.declared) && (!last || step > last.step || nowMs() - last.atMs >= LOG_EVERY_MS)) {
|
|
522
|
+
log(`live listener ${JSON.stringify(name)} ${wire}: declares ${declaredMs} ms, input side ${inputMs} ms, plays ${step} ms after capture`);
|
|
523
|
+
logged.set(clientId, {
|
|
524
|
+
atMs: nowMs(),
|
|
525
|
+
step
|
|
526
|
+
});
|
|
527
|
+
}
|
|
528
|
+
listeners.set(clientId, {
|
|
529
|
+
declared: declaredMs,
|
|
530
|
+
step
|
|
531
|
+
});
|
|
532
|
+
return step;
|
|
533
|
+
},
|
|
534
|
+
left(clientId) {
|
|
535
|
+
listeners.delete(clientId);
|
|
536
|
+
},
|
|
537
|
+
measureMs(wire) {
|
|
538
|
+
const inputMs = inputs.get(wire)?.ms;
|
|
539
|
+
return inputMs === void 0 ? void 0 : liveStep(inputMs + MEASURE_MS);
|
|
540
|
+
},
|
|
541
|
+
restart() {
|
|
542
|
+
for (const input of inputs.values()) {
|
|
543
|
+
const held = input.ms !== void 0;
|
|
544
|
+
input.firstUs = void 0;
|
|
545
|
+
input.second = 0;
|
|
546
|
+
input.highest = Number.NEGATIVE_INFINITY;
|
|
547
|
+
input.readings = [];
|
|
548
|
+
input.partSecond = void 0;
|
|
549
|
+
input.held = held;
|
|
550
|
+
}
|
|
551
|
+
listeners.clear();
|
|
552
|
+
}
|
|
553
|
+
};
|
|
554
|
+
}
|
|
555
|
+
// src/sync/live-timeline.ts
|
|
556
|
+
const DEFAULT_LIVE_TIMELINE_CAPACITY = 256;
|
|
557
|
+
const DEADBAND_SEC = .001;
|
|
558
|
+
const SLEW_RATE = .003;
|
|
559
|
+
const REPLACE_SEC = .2;
|
|
560
|
+
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
|
+
*/
|
|
570
|
+
function pageClock() {
|
|
571
|
+
let aheadMs = Number.POSITIVE_INFINITY;
|
|
572
|
+
return {
|
|
573
|
+
pageMs: (ownMs = performance.now()) => ownMs - aheadMs,
|
|
574
|
+
saw: (pageMs, ownMs = performance.now()) => {
|
|
575
|
+
aheadMs = Math.min(aheadMs, ownMs - pageMs);
|
|
576
|
+
}
|
|
577
|
+
};
|
|
578
|
+
}
|
|
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
|
+
}
|
|
591
|
+
function addStats(totals, stats) {
|
|
592
|
+
totals.chunks += stats.chunks;
|
|
593
|
+
totals.lost += stats.lost;
|
|
594
|
+
totals.slack = Math.min(totals.slack, stats.slack);
|
|
595
|
+
totals.filled += stats.filled;
|
|
596
|
+
totals.skipped += stats.skipped;
|
|
597
|
+
totals.errorMin = Math.min(totals.errorMin, stats.errorMin);
|
|
598
|
+
totals.errorMax = Math.max(totals.errorMax, stats.errorMax);
|
|
599
|
+
totals.corrections += stats.corrections;
|
|
600
|
+
}
|
|
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;
|
|
607
|
+
}
|
|
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
|
+
var LiveTimeline = class {
|
|
616
|
+
capacity;
|
|
617
|
+
ring;
|
|
618
|
+
head = 0;
|
|
619
|
+
tail = 0;
|
|
620
|
+
count = 0;
|
|
621
|
+
position = 0;
|
|
622
|
+
playing = false;
|
|
623
|
+
dry = false;
|
|
624
|
+
endStampUs;
|
|
625
|
+
correcting = 0;
|
|
626
|
+
settling = false;
|
|
627
|
+
rate = 1;
|
|
628
|
+
sampleRate;
|
|
629
|
+
stats = noStats();
|
|
630
|
+
constructor(sampleRate, capacity = 256) {
|
|
631
|
+
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 });
|
|
635
|
+
}
|
|
636
|
+
get length() {
|
|
637
|
+
return this.count;
|
|
638
|
+
}
|
|
639
|
+
get maxCapacity() {
|
|
640
|
+
return this.capacity;
|
|
641
|
+
}
|
|
642
|
+
reset() {
|
|
643
|
+
for (let i = 0; i < this.capacity; i += 1) this.ring[i] = void 0;
|
|
644
|
+
this.head = 0;
|
|
645
|
+
this.tail = 0;
|
|
646
|
+
this.count = 0;
|
|
647
|
+
this.position = 0;
|
|
648
|
+
this.playing = false;
|
|
649
|
+
this.dry = false;
|
|
650
|
+
this.settling = false;
|
|
651
|
+
this.correcting = 0;
|
|
652
|
+
this.rate = 1;
|
|
653
|
+
this.endStampUs = void 0;
|
|
654
|
+
this.resetStatsInPlace();
|
|
655
|
+
}
|
|
656
|
+
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;
|
|
669
|
+
}
|
|
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
|
+
takeStatsInto(target) {
|
|
675
|
+
target.chunks = this.stats.chunks;
|
|
676
|
+
target.corrections = this.stats.corrections;
|
|
677
|
+
target.errorMax = this.stats.errorMax;
|
|
678
|
+
target.errorMin = this.stats.errorMin;
|
|
679
|
+
target.filled = this.stats.filled;
|
|
680
|
+
target.lost = this.stats.lost;
|
|
681
|
+
target.skipped = this.stats.skipped;
|
|
682
|
+
target.slack = this.stats.slack;
|
|
683
|
+
this.resetStatsInPlace();
|
|
684
|
+
}
|
|
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;
|
|
694
|
+
}
|
|
695
|
+
peek(offset) {
|
|
696
|
+
if (offset < 0 || offset >= this.count) return;
|
|
697
|
+
return this.ring[(this.head + offset) % this.capacity];
|
|
698
|
+
}
|
|
699
|
+
dequeue() {
|
|
700
|
+
if (this.count === 0) return;
|
|
701
|
+
const item = this.ring[this.head];
|
|
702
|
+
this.ring[this.head] = void 0;
|
|
703
|
+
this.head = (this.head + 1) % this.capacity;
|
|
704
|
+
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
|
+
}
|
|
725
|
+
push(chunk, next) {
|
|
726
|
+
if ((chunk.channels[0]?.length ?? 0) === 0) return;
|
|
727
|
+
const slack = this.playing ? this.queued() : chunk.frame - next;
|
|
728
|
+
const follows = this.endStampUs !== void 0 && Math.abs(chunk.stampUs - this.endStampUs) <= JOIN_US;
|
|
729
|
+
this.stats.chunks += 1;
|
|
730
|
+
this.stats.slack = Math.min(this.stats.slack, slack);
|
|
731
|
+
if (slack < 0 || this.dry && follows) this.stats.lost += 1;
|
|
732
|
+
this.dry = false;
|
|
733
|
+
this.enqueue(chunk);
|
|
734
|
+
}
|
|
735
|
+
render(frame, output) {
|
|
736
|
+
const frames = output[0]?.length ?? 0;
|
|
737
|
+
if (this.playing) this.steer(frame);
|
|
738
|
+
const channelCount = output.length;
|
|
739
|
+
for (let i = 0; i < frames; i += 1) {
|
|
740
|
+
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;
|
|
744
|
+
}
|
|
745
|
+
if (this.dry) this.stats.filled += 1;
|
|
746
|
+
continue;
|
|
747
|
+
}
|
|
748
|
+
this.read(output, i, frame + i);
|
|
749
|
+
}
|
|
750
|
+
}
|
|
751
|
+
queued() {
|
|
752
|
+
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
|
+
}
|
|
757
|
+
return frames / this.rate;
|
|
758
|
+
}
|
|
759
|
+
place(frame) {
|
|
760
|
+
while (this.count > 0) {
|
|
761
|
+
const chunk = this.peek(0);
|
|
762
|
+
if (!chunk) return false;
|
|
763
|
+
const offset = Math.round(frame - chunk.frame);
|
|
764
|
+
const length = chunk.channels[0]?.length ?? 0;
|
|
765
|
+
if (offset < 0) return false;
|
|
766
|
+
if (offset < length) {
|
|
767
|
+
this.stats.skipped += offset;
|
|
768
|
+
this.position = offset;
|
|
769
|
+
this.playing = true;
|
|
770
|
+
return true;
|
|
771
|
+
}
|
|
772
|
+
this.stats.skipped += length;
|
|
773
|
+
this.dequeue();
|
|
774
|
+
}
|
|
775
|
+
return false;
|
|
776
|
+
}
|
|
777
|
+
steer(frame) {
|
|
778
|
+
const chunk = this.peek(0);
|
|
779
|
+
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;
|
|
788
|
+
return;
|
|
789
|
+
}
|
|
790
|
+
const sign = Math.sign(error);
|
|
791
|
+
if (this.correcting === 0 && Math.abs(error) > DEADBAND_SEC * this.sampleRate) {
|
|
792
|
+
this.correcting = sign;
|
|
793
|
+
this.settling = false;
|
|
794
|
+
this.rate = 1 - sign * SLEW_RATE;
|
|
795
|
+
this.stats.corrections += 1;
|
|
796
|
+
} else if (this.correcting !== 0 && sign !== this.correcting) this.settling = true;
|
|
797
|
+
}
|
|
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);
|
|
835
|
+
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];
|
|
841
|
+
const samples = chunk.channels[c] ?? chunk.channels[0];
|
|
842
|
+
if (outChannel && samples) outChannel[i] = interpolateSample(samples, next, c, index, fraction);
|
|
843
|
+
}
|
|
844
|
+
this.advancePosition(chunk, currentFrameIndex);
|
|
845
|
+
}
|
|
846
|
+
};
|
|
847
|
+
// src/worklets/couch-live.ts
|
|
848
|
+
const COUCH_LIVE_PROCESSOR_NAME = "couch-live";
|
|
849
|
+
if (typeof registerProcessor === "function") {
|
|
850
|
+
const reportFrames = sampleRate / 10;
|
|
851
|
+
registerProcessor(COUCH_LIVE_PROCESSOR_NAME, class CouchLiveProcessor extends AudioWorkletProcessor {
|
|
852
|
+
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
|
+
};
|
|
863
|
+
reportPayload;
|
|
864
|
+
epoch = 0;
|
|
865
|
+
next = currentFrame;
|
|
866
|
+
reported = currentFrame;
|
|
867
|
+
feed;
|
|
868
|
+
disposed = false;
|
|
869
|
+
onFeedMessage = (msgEvent) => {
|
|
870
|
+
if (this.disposed) return;
|
|
871
|
+
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") {
|
|
882
|
+
this.timeline.reset();
|
|
883
|
+
this.epoch = typeof msg.epoch === "number" ? msg.epoch : 0;
|
|
884
|
+
}
|
|
885
|
+
};
|
|
886
|
+
onPortMessage = (event) => {
|
|
887
|
+
if (this.disposed) return;
|
|
888
|
+
const { data } = event;
|
|
889
|
+
if (!data || typeof data !== "object") return;
|
|
890
|
+
if (data.type === "dispose") {
|
|
891
|
+
this.dispose();
|
|
892
|
+
return;
|
|
893
|
+
}
|
|
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
|
+
};
|
|
904
|
+
constructor() {
|
|
905
|
+
super();
|
|
906
|
+
this.reportPayload = {
|
|
907
|
+
epoch: 0,
|
|
908
|
+
stats: this.reportStats
|
|
909
|
+
};
|
|
910
|
+
this.port.addEventListener("message", this.onPortMessage);
|
|
911
|
+
if (typeof this.port.start === "function") this.port.start();
|
|
912
|
+
}
|
|
913
|
+
detachFeed() {
|
|
914
|
+
if (!this.feed) return;
|
|
915
|
+
this.feed.removeEventListener("message", this.onFeedMessage);
|
|
916
|
+
if (typeof this.feed.close === "function") this.feed.close();
|
|
917
|
+
this.feed = void 0;
|
|
918
|
+
}
|
|
919
|
+
dispose() {
|
|
920
|
+
if (this.disposed) return;
|
|
921
|
+
this.disposed = true;
|
|
922
|
+
this.detachFeed();
|
|
923
|
+
this.timeline.reset();
|
|
924
|
+
this.port.removeEventListener("message", this.onPortMessage);
|
|
925
|
+
if (typeof this.port.close === "function") this.port.close();
|
|
926
|
+
}
|
|
927
|
+
flushReport() {
|
|
928
|
+
if (this.disposed || !this.feed) return;
|
|
929
|
+
this.timeline.takeStatsInto(this.reportStats);
|
|
930
|
+
this.reportPayload.epoch = this.epoch;
|
|
931
|
+
this.feed.postMessage(this.reportPayload);
|
|
932
|
+
}
|
|
933
|
+
process(_inputs, outputs) {
|
|
934
|
+
if (this.disposed) return false;
|
|
935
|
+
const [output] = outputs;
|
|
936
|
+
if (!output) return true;
|
|
937
|
+
this.timeline.render(currentFrame, output);
|
|
938
|
+
this.next = currentFrame + (output[0]?.length ?? 0);
|
|
939
|
+
if (this.next - this.reported >= reportFrames) {
|
|
940
|
+
this.reported = this.next;
|
|
941
|
+
this.flushReport();
|
|
942
|
+
}
|
|
943
|
+
return true;
|
|
944
|
+
}
|
|
945
|
+
});
|
|
946
|
+
}
|
|
947
|
+
// src/sync/sendspin.ts
|
|
948
|
+
const SENDSPIN_BINARY_AUDIO_TYPE = 4;
|
|
949
|
+
const SENDSPIN_VOLUME_RAMP_TIME_CONSTANT_S = .015;
|
|
950
|
+
/**
|
|
951
|
+
* Computes Couch's perceptual volume curve (`muted ? 0 : (volume / 100) ** 1.5`).
|
|
952
|
+
*/
|
|
953
|
+
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;
|
|
956
|
+
}
|
|
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
|
+
function sniffSendspinAudioHeader(data) {
|
|
962
|
+
const bytes = data instanceof Uint8Array ? data : new Uint8Array(data);
|
|
963
|
+
if (bytes.byteLength < 13 || bytes[0] !== 4) return;
|
|
964
|
+
const view = new DataView(bytes.buffer, bytes.byteOffset, bytes.byteLength);
|
|
965
|
+
return {
|
|
966
|
+
messageType: 4,
|
|
967
|
+
sendAheadUs: view.getUint32(9, false),
|
|
968
|
+
stampUs: Number(view.getBigInt64(1, false))
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
function collectTransferableBuffers(chunk) {
|
|
972
|
+
const buffers = [];
|
|
973
|
+
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;
|
|
982
|
+
}
|
|
983
|
+
/**
|
|
984
|
+
* Loads the standalone `@avoid.quest/audio/worklets/couch-live` AudioWorklet module
|
|
985
|
+
* into `context` with Blob-URL fallback support.
|
|
986
|
+
*/
|
|
987
|
+
function loadCouchLiveWorklet(context, options = {}) {
|
|
988
|
+
return loadAudioWorklet(context, {
|
|
989
|
+
fallbackToBlob: options.fallbackToBlob ?? true,
|
|
990
|
+
fetchImpl: options.fetchImpl,
|
|
991
|
+
inlineSource: options.inlineSource,
|
|
992
|
+
moduleUrl: options.inlineSource === void 0 ? options.moduleUrl ?? createWorkletModuleUrl("couch-live") : void 0,
|
|
993
|
+
processorName: COUCH_LIVE_PROCESSOR_NAME
|
|
994
|
+
});
|
|
995
|
+
}
|
|
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
|
+
*/
|
|
1001
|
+
function createSendspinReceiver(context, options = {}) {
|
|
1002
|
+
return Effect.gen(function* () {
|
|
1003
|
+
yield* loadCouchLiveWorklet(context, options.workletOptions);
|
|
1004
|
+
if (typeof globalThis.AudioWorkletNode !== "function") return yield* Effect.fail(new AudioUnsupportedError({
|
|
1005
|
+
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();
|
|
1052
|
+
}));
|
|
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
|
+
};
|
|
1095
|
+
});
|
|
1096
|
+
}
|
|
1097
|
+
/** Couch naming parity wrapper (`LivePlayer`) delegating to `createSendspinReceiver`. */
|
|
1098
|
+
function createLivePlayer(context, options = {}) {
|
|
1099
|
+
return createSendspinReceiver(context, options);
|
|
1100
|
+
}
|
|
1101
|
+
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 };
|
|
1102
|
+
|
|
1103
|
+
//# sourceMappingURL=index.js.map
|