@hussmartinez/audio-sdk 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 +202 -0
- package/README.md +133 -2
- package/dist/assets/audio/audio.worker.js +1 -0
- package/dist/element.d.ts +12 -0
- package/dist/element.js +0 -0
- package/dist/index.d.ts +1017 -0
- package/dist/index.js +447 -0
- package/dist/index.js.map +1 -0
- package/dist/lazy/inline-worker-CexEKodJ.js +30 -0
- package/dist/lazy/inline-worker-CexEKodJ.js.map +1 -0
- package/dist/react.d.ts +12 -0
- package/dist/react.js +1 -0
- package/dist/styles.css +9 -0
- package/package.json +107 -3
package/dist/index.js
ADDED
|
@@ -0,0 +1,447 @@
|
|
|
1
|
+
import { SdkError, coreLimits, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, sdkCoreMessages } from "@hussmartinez/sdk-core";
|
|
2
|
+
// src/core/errors/audio-error.ts
|
|
3
|
+
var AudioError = class extends SdkError {
|
|
4
|
+
name = "AudioError";
|
|
5
|
+
};
|
|
6
|
+
function isAudioError(value, code) {
|
|
7
|
+
return isSdkError(value, code) && value.name === "AudioError";
|
|
8
|
+
}
|
|
9
|
+
// src/core/errors/abort.ts
|
|
10
|
+
function asAudioError(reason, message = "Audio processing failed.") {
|
|
11
|
+
if (reason instanceof AudioError) return reason;
|
|
12
|
+
if (isSdkError(reason)) return new AudioError(reason.code, reason.message, {
|
|
13
|
+
...reason.details === void 0 ? {} : { details: reason.details },
|
|
14
|
+
cause: reason
|
|
15
|
+
});
|
|
16
|
+
return new AudioError("UNKNOWN", message, { cause: reason });
|
|
17
|
+
}
|
|
18
|
+
function abortError(signal) {
|
|
19
|
+
const { reason } = signal;
|
|
20
|
+
if (reason instanceof AudioError) return reason;
|
|
21
|
+
if (isSdkError(reason)) return asAudioError(reason);
|
|
22
|
+
const timedOut = reason instanceof DOMException && reason.name === "TimeoutError";
|
|
23
|
+
return new AudioError(timedOut ? "TIMEOUT" : "ABORTED", timedOut ? "The operation timed out." : "The operation was cancelled.", { cause: reason });
|
|
24
|
+
}
|
|
25
|
+
function throwIfAborted(signal) {
|
|
26
|
+
if (signal?.aborted) throw abortError(signal);
|
|
27
|
+
}
|
|
28
|
+
// src/adapters/assets-url.ts
|
|
29
|
+
function assetsBase(assetsUrl) {
|
|
30
|
+
if (assetsUrl === void 0) return void 0;
|
|
31
|
+
const base = new URL(String(assetsUrl), globalThis.location?.href).href;
|
|
32
|
+
return base.endsWith("/") ? base : `${base}/`;
|
|
33
|
+
}
|
|
34
|
+
var LEVEL_FACTOR = 4;
|
|
35
|
+
function buildPyramid(finest, bucket = 256) {
|
|
36
|
+
const levels = [];
|
|
37
|
+
let current = finest;
|
|
38
|
+
let framesPerBucket = bucket;
|
|
39
|
+
for (;;) {
|
|
40
|
+
levels.push({
|
|
41
|
+
framesPerBucket,
|
|
42
|
+
channels: current.min.map((min, c) => ({
|
|
43
|
+
min,
|
|
44
|
+
max: current.max[c]
|
|
45
|
+
}))
|
|
46
|
+
});
|
|
47
|
+
if ((current.min[0]?.length ?? 0) <= 1) break;
|
|
48
|
+
current = {
|
|
49
|
+
min: current.min.map((values) => combine(values, Math.min)),
|
|
50
|
+
max: current.max.map((values) => combine(values, Math.max))
|
|
51
|
+
};
|
|
52
|
+
framesPerBucket *= LEVEL_FACTOR;
|
|
53
|
+
}
|
|
54
|
+
return { levels };
|
|
55
|
+
}
|
|
56
|
+
function combine(values, pick) {
|
|
57
|
+
const out = new Float32Array(Math.ceil(values.length / LEVEL_FACTOR));
|
|
58
|
+
for (let i = 0; i < out.length; i += 1) {
|
|
59
|
+
let value = values[i * LEVEL_FACTOR];
|
|
60
|
+
const end = Math.min(values.length, (i + 1) * LEVEL_FACTOR);
|
|
61
|
+
for (let j = i * LEVEL_FACTOR + 1; j < end; j += 1) value = pick(value, values[j]);
|
|
62
|
+
out[i] = value;
|
|
63
|
+
}
|
|
64
|
+
return out;
|
|
65
|
+
}
|
|
66
|
+
// src/adapters/web-audio/platform-decode.ts
|
|
67
|
+
var webAudioDecoder = (bytes, { sampleRate, channels }) => {
|
|
68
|
+
const Offline = globalThis.OfflineAudioContext;
|
|
69
|
+
if (typeof Offline !== "function") throw new AudioError("UNSUPPORTED_ENVIRONMENT", "Web Audio isn't available.", { details: { feature: "OfflineAudioContext" } });
|
|
70
|
+
let context;
|
|
71
|
+
try {
|
|
72
|
+
context = new Offline({
|
|
73
|
+
numberOfChannels: channels,
|
|
74
|
+
length: 1,
|
|
75
|
+
sampleRate
|
|
76
|
+
});
|
|
77
|
+
} catch (error) {
|
|
78
|
+
throw new AudioError("UNSUPPORTED_FORMAT", "This browser can't decode at this rate.", {
|
|
79
|
+
details: { sampleRate },
|
|
80
|
+
cause: error
|
|
81
|
+
});
|
|
82
|
+
}
|
|
83
|
+
return context.decodeAudioData(bytes);
|
|
84
|
+
};
|
|
85
|
+
function untilAborted(work, signal) {
|
|
86
|
+
work.catch(() => {});
|
|
87
|
+
if (!signal) return work;
|
|
88
|
+
return new Promise((resolve, reject) => {
|
|
89
|
+
const onAbort = () => reject(abortError(signal));
|
|
90
|
+
if (signal.aborted) {
|
|
91
|
+
onAbort();
|
|
92
|
+
return;
|
|
93
|
+
}
|
|
94
|
+
signal.addEventListener("abort", onAbort, { once: true });
|
|
95
|
+
work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
async function decodeOnPage(file, probe, decoder, createBuffer, signal) {
|
|
99
|
+
const { container, codec, sampleRate, channels, frameBound, frameTolerance } = probe;
|
|
100
|
+
throwIfAborted(signal);
|
|
101
|
+
const bytes = await untilAborted(file.arrayBuffer(), signal);
|
|
102
|
+
let decoded;
|
|
103
|
+
try {
|
|
104
|
+
decoded = await untilAborted(Promise.resolve().then(() => decoder(bytes, {
|
|
105
|
+
sampleRate,
|
|
106
|
+
channels
|
|
107
|
+
})), signal);
|
|
108
|
+
} catch (error) {
|
|
109
|
+
if (isAudioError(error)) throw error;
|
|
110
|
+
throw new AudioError("DECODE_FAILED", "The browser couldn't decode this file.", {
|
|
111
|
+
details: {
|
|
112
|
+
container,
|
|
113
|
+
codec
|
|
114
|
+
},
|
|
115
|
+
cause: error
|
|
116
|
+
});
|
|
117
|
+
}
|
|
118
|
+
if (decoded.length === 0) throw new AudioError("DECODE_FAILED", "The browser decoded no audio from this file.", { details: {
|
|
119
|
+
container,
|
|
120
|
+
codec,
|
|
121
|
+
reason: "no audio decoded"
|
|
122
|
+
} });
|
|
123
|
+
const invalid = (reason) => new AudioError("INVALID_AUDIO", `The decoded audio ${reason}.`, { details: {
|
|
124
|
+
container,
|
|
125
|
+
codec,
|
|
126
|
+
reason: `decoded ${reason}`
|
|
127
|
+
} });
|
|
128
|
+
if (decoded.sampleRate !== sampleRate) throw invalid("rate differs from the probe");
|
|
129
|
+
if (decoded.numberOfChannels > channels) throw invalid("channel count exceeds the probe");
|
|
130
|
+
if (decoded.length > frameBound + frameTolerance) throw invalid("length exceeds the bound");
|
|
131
|
+
if (decoded.length <= frameBound) return decoded;
|
|
132
|
+
const capped = createBuffer({
|
|
133
|
+
numberOfChannels: decoded.numberOfChannels,
|
|
134
|
+
length: frameBound,
|
|
135
|
+
sampleRate
|
|
136
|
+
});
|
|
137
|
+
for (let c = 0; c < decoded.numberOfChannels; c += 1) capped.copyToChannel(decoded.getChannelData(c).subarray(0, frameBound), c, 0);
|
|
138
|
+
return capped;
|
|
139
|
+
}
|
|
140
|
+
// src/adapters/audio-engine.ts
|
|
141
|
+
var BLOCK_FRAMES = 65536;
|
|
142
|
+
function createAudioEngine(options = {}) {
|
|
143
|
+
const base = assetsBase(options.assetsUrl);
|
|
144
|
+
const selfHosted = base === void 0 ? void 0 : `${base}audio/audio.worker.js`;
|
|
145
|
+
return createEngine({
|
|
146
|
+
loadWorker: selfHosted ? async () => () => new Worker(selfHosted, {
|
|
147
|
+
type: "module",
|
|
148
|
+
name: "hm-audio"
|
|
149
|
+
}) : async () => (await import("./lazy/inline-worker-CexEKodJ.js")).createInlineWorker,
|
|
150
|
+
version: "0.1.0",
|
|
151
|
+
...selfHosted ? { asset: selfHosted } : {},
|
|
152
|
+
createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),
|
|
153
|
+
decodePlatform: webAudioDecoder,
|
|
154
|
+
...options.idleTimeout === void 0 ? {} : { idleTimeout: options.idleTimeout }
|
|
155
|
+
});
|
|
156
|
+
}
|
|
157
|
+
function createEngine(environment) {
|
|
158
|
+
let startWorker;
|
|
159
|
+
let destroyed = false;
|
|
160
|
+
const layouts = /* @__PURE__ */ new WeakMap();
|
|
161
|
+
const compressedProbes = /* @__PURE__ */ new WeakSet();
|
|
162
|
+
const finestPeaks = /* @__PURE__ */ new WeakMap();
|
|
163
|
+
const newClient = () => createWorkerClient({
|
|
164
|
+
createWorker: () => {
|
|
165
|
+
if (!startWorker) throw new AudioError("WORKER_START_FAILED", "The audio worker hasn't loaded.");
|
|
166
|
+
return startWorker();
|
|
167
|
+
},
|
|
168
|
+
errorClasses: { AudioError },
|
|
169
|
+
...environment.idleTimeout === void 0 ? {} : { idleTimeout: environment.idleTimeout }
|
|
170
|
+
});
|
|
171
|
+
let main;
|
|
172
|
+
let analysis;
|
|
173
|
+
let versionChecked;
|
|
174
|
+
async function ready() {
|
|
175
|
+
if (destroyed) throw new Error("The audio engine has been destroyed.");
|
|
176
|
+
startWorker ??= await environment.loadWorker();
|
|
177
|
+
versionChecked ??= (async () => {
|
|
178
|
+
main ??= newClient();
|
|
179
|
+
const actual = await main.call("version", void 0);
|
|
180
|
+
if (actual !== environment.version) throw new AudioError("WORKER_START_FAILED", "The audio worker isn't this version of the SDK. Copy dist/assets again after upgrading.", { details: {
|
|
181
|
+
asset: environment.asset ?? "inline",
|
|
182
|
+
expected: environment.version,
|
|
183
|
+
actual
|
|
184
|
+
} });
|
|
185
|
+
})();
|
|
186
|
+
try {
|
|
187
|
+
await versionChecked;
|
|
188
|
+
} catch (error) {
|
|
189
|
+
versionChecked = void 0;
|
|
190
|
+
throw error;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
async function run(work) {
|
|
194
|
+
try {
|
|
195
|
+
return await work();
|
|
196
|
+
} catch (error) {
|
|
197
|
+
throw error instanceof RangeError || error instanceof TypeError ? error : asAudioError(error);
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
async function reprobe(file, probe, signal) {
|
|
201
|
+
main ??= newClient();
|
|
202
|
+
const fresh = await main.call("probe", { file }, signal ? { signal } : {});
|
|
203
|
+
if (!(fresh.probe.codec === probe.codec && fresh.probe.sampleRate === probe.sampleRate && fresh.probe.channels === probe.channels && fresh.probe.frameBound === probe.frameBound)) throw new AudioError("INVALID_AUDIO", "The probe doesn't describe this file.", { details: { container: probe.container } });
|
|
204
|
+
return fresh.probe;
|
|
205
|
+
}
|
|
206
|
+
async function layoutOf(file, probe, signal) {
|
|
207
|
+
const known = layouts.get(probe);
|
|
208
|
+
if (known) return known;
|
|
209
|
+
main ??= newClient();
|
|
210
|
+
const fresh = await main.call("probe", { file }, signal ? { signal } : {});
|
|
211
|
+
if (!(fresh.probe.sampleRate === probe.sampleRate && fresh.probe.channels === probe.channels && fresh.probe.frameBound === probe.frameBound)) throw new AudioError("INVALID_AUDIO", "The probe doesn't describe this file.", { details: { container: probe.container } });
|
|
212
|
+
if (!fresh.layout) throw new AudioError("UNSUPPORTED_FORMAT", "Compressed formats aren't supported yet.", { details: {
|
|
213
|
+
container: probe.container,
|
|
214
|
+
codec: probe.codec
|
|
215
|
+
} });
|
|
216
|
+
return fresh.layout;
|
|
217
|
+
}
|
|
218
|
+
return {
|
|
219
|
+
probe(file, options = {}) {
|
|
220
|
+
return run(async () => {
|
|
221
|
+
throwIfAborted(options.signal);
|
|
222
|
+
await ready();
|
|
223
|
+
main ??= newClient();
|
|
224
|
+
const result = await main.call("probe", { file }, options.signal ? { signal: options.signal } : {});
|
|
225
|
+
if (result.layout) layouts.set(result.probe, result.layout);
|
|
226
|
+
else compressedProbes.add(result.probe);
|
|
227
|
+
return result.probe;
|
|
228
|
+
});
|
|
229
|
+
},
|
|
230
|
+
decode(file, probe, options = {}) {
|
|
231
|
+
return run(async () => {
|
|
232
|
+
throwIfAborted(options.signal);
|
|
233
|
+
await ready();
|
|
234
|
+
if (probe.codec !== "pcm") {
|
|
235
|
+
const audio = await decodeOnPage(file, compressedProbes.has(probe) ? probe : await reprobe(file, probe, options.signal), environment.decodePlatform, environment.createBuffer, options.signal);
|
|
236
|
+
options.onProgress?.(1);
|
|
237
|
+
return audio;
|
|
238
|
+
}
|
|
239
|
+
const layout = await layoutOf(file, probe, options.signal);
|
|
240
|
+
const { frames, channels, sampleRate } = layout;
|
|
241
|
+
let buffer;
|
|
242
|
+
try {
|
|
243
|
+
buffer = environment.createBuffer({
|
|
244
|
+
numberOfChannels: channels,
|
|
245
|
+
length: frames,
|
|
246
|
+
sampleRate
|
|
247
|
+
});
|
|
248
|
+
} catch (error) {
|
|
249
|
+
throw new AudioError("UNSUPPORTED_FORMAT", "This browser can't hold audio at this rate.", {
|
|
250
|
+
details: {
|
|
251
|
+
container: layout.container,
|
|
252
|
+
sampleRate
|
|
253
|
+
},
|
|
254
|
+
cause: error
|
|
255
|
+
});
|
|
256
|
+
}
|
|
257
|
+
const buckets = Math.ceil(frames / 256);
|
|
258
|
+
const peaks = {
|
|
259
|
+
min: Array.from({ length: channels }, () => new Float32Array(buckets)),
|
|
260
|
+
max: Array.from({ length: channels }, () => new Float32Array(buckets))
|
|
261
|
+
};
|
|
262
|
+
main ??= newClient();
|
|
263
|
+
for (let start = 0; start < frames; start += BLOCK_FRAMES) {
|
|
264
|
+
const block = await main.call("readBlock", {
|
|
265
|
+
file,
|
|
266
|
+
layout,
|
|
267
|
+
start,
|
|
268
|
+
frames: Math.min(BLOCK_FRAMES, frames - start),
|
|
269
|
+
bucket: 256
|
|
270
|
+
}, options.signal ? { signal: options.signal } : {});
|
|
271
|
+
const at = start / 256;
|
|
272
|
+
for (let c = 0; c < channels; c += 1) {
|
|
273
|
+
buffer.copyToChannel(block.channels[c], c, start);
|
|
274
|
+
peaks.min[c]?.set(block.min[c], at);
|
|
275
|
+
peaks.max[c]?.set(block.max[c], at);
|
|
276
|
+
}
|
|
277
|
+
options.onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);
|
|
278
|
+
}
|
|
279
|
+
if (frames === 0) options.onProgress?.(1);
|
|
280
|
+
finestPeaks.set(buffer, peaks);
|
|
281
|
+
return buffer;
|
|
282
|
+
});
|
|
283
|
+
},
|
|
284
|
+
peaks(audio, options = {}) {
|
|
285
|
+
return run(async () => {
|
|
286
|
+
throwIfAborted(options.signal);
|
|
287
|
+
const known = finestPeaks.get(audio);
|
|
288
|
+
if (known) return buildPyramid(known, 256);
|
|
289
|
+
await ready();
|
|
290
|
+
analysis ??= newClient();
|
|
291
|
+
const buckets = Math.ceil(audio.length / 256);
|
|
292
|
+
const peaks = {
|
|
293
|
+
min: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),
|
|
294
|
+
max: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets))
|
|
295
|
+
};
|
|
296
|
+
for (let start = 0; start < audio.length; start += BLOCK_FRAMES) {
|
|
297
|
+
const end = Math.min(audio.length, start + BLOCK_FRAMES);
|
|
298
|
+
const channels = Array.from({ length: audio.numberOfChannels }, (_, c) => audio.getChannelData(c).slice(start, end));
|
|
299
|
+
const block = await analysis.call("peaks", {
|
|
300
|
+
channels,
|
|
301
|
+
bucket: 256
|
|
302
|
+
}, {
|
|
303
|
+
transfer: true,
|
|
304
|
+
...options.signal ? { signal: options.signal } : {}
|
|
305
|
+
});
|
|
306
|
+
const at = start / 256;
|
|
307
|
+
for (let c = 0; c < audio.numberOfChannels; c += 1) {
|
|
308
|
+
peaks.min[c]?.set(block.min[c], at);
|
|
309
|
+
peaks.max[c]?.set(block.max[c], at);
|
|
310
|
+
}
|
|
311
|
+
}
|
|
312
|
+
finestPeaks.set(audio, peaks);
|
|
313
|
+
return buildPyramid(peaks, 256);
|
|
314
|
+
});
|
|
315
|
+
},
|
|
316
|
+
async destroy() {
|
|
317
|
+
destroyed = true;
|
|
318
|
+
main?.destroy();
|
|
319
|
+
analysis?.destroy();
|
|
320
|
+
}
|
|
321
|
+
};
|
|
322
|
+
}
|
|
323
|
+
// src/core/errors/audio-limits.ts
|
|
324
|
+
var audioLimitDefinitions = {
|
|
325
|
+
...coreLimits,
|
|
326
|
+
maxFileSize: {
|
|
327
|
+
...coreLimits.maxFileSize,
|
|
328
|
+
default: 1e9,
|
|
329
|
+
warning: 25e7
|
|
330
|
+
},
|
|
331
|
+
maxDecodedSize: {
|
|
332
|
+
...coreLimits.maxDecodedSize,
|
|
333
|
+
default: 1e9,
|
|
334
|
+
warning: 4e8
|
|
335
|
+
},
|
|
336
|
+
maxDuration: {
|
|
337
|
+
code: "DURATION_TOO_LONG",
|
|
338
|
+
unit: "milliseconds",
|
|
339
|
+
default: 108e5,
|
|
340
|
+
warning: 36e5
|
|
341
|
+
},
|
|
342
|
+
maxChannels: {
|
|
343
|
+
code: "TOO_MANY_CHANNELS",
|
|
344
|
+
unit: "count",
|
|
345
|
+
default: 8
|
|
346
|
+
},
|
|
347
|
+
maxSampleRate: {
|
|
348
|
+
code: "SAMPLE_RATE_TOO_HIGH",
|
|
349
|
+
unit: "count",
|
|
350
|
+
default: 192e3
|
|
351
|
+
},
|
|
352
|
+
maxSessionSize: {
|
|
353
|
+
code: "SESSION_TOO_LARGE",
|
|
354
|
+
unit: "bytes",
|
|
355
|
+
default: 15e8,
|
|
356
|
+
warning: 75e7
|
|
357
|
+
},
|
|
358
|
+
maxClips: {
|
|
359
|
+
code: "TOO_MANY_CLIPS",
|
|
360
|
+
unit: "count",
|
|
361
|
+
default: 2e3
|
|
362
|
+
}
|
|
363
|
+
};
|
|
364
|
+
var audioLimits = /* @__PURE__ */ defineLimits(audioLimitDefinitions, { errorClass: AudioError });
|
|
365
|
+
// src/core/model/envelope.ts
|
|
366
|
+
function dbToGain(db) {
|
|
367
|
+
return 10 ** (db / 20);
|
|
368
|
+
}
|
|
369
|
+
function fadeShape(curve, position) {
|
|
370
|
+
return curve === "equalPower" ? Math.sin(position * Math.PI / 2) : position;
|
|
371
|
+
}
|
|
372
|
+
function gainAt(clip, frame) {
|
|
373
|
+
const length = clip.end - clip.start;
|
|
374
|
+
let gain = dbToGain(clip.gainDb);
|
|
375
|
+
const { fadeIn, fadeOut } = clip;
|
|
376
|
+
if (fadeIn.frames > 0 && frame < fadeIn.frames) gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);
|
|
377
|
+
const fromEnd = length - 1 - frame;
|
|
378
|
+
if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);
|
|
379
|
+
return gain;
|
|
380
|
+
}
|
|
381
|
+
// src/core/model/time.ts
|
|
382
|
+
function framesToSeconds(frames, sampleRate) {
|
|
383
|
+
return frames / sampleRate;
|
|
384
|
+
}
|
|
385
|
+
function secondsToFrames(seconds, sampleRate) {
|
|
386
|
+
return Math.round(seconds * sampleRate);
|
|
387
|
+
}
|
|
388
|
+
// src/core/model/plan.ts
|
|
389
|
+
var EMPTY_METADATA = Object.freeze({
|
|
390
|
+
title: "",
|
|
391
|
+
artist: "",
|
|
392
|
+
album: "",
|
|
393
|
+
year: "",
|
|
394
|
+
comment: ""
|
|
395
|
+
});
|
|
396
|
+
var NO_FADE = Object.freeze({
|
|
397
|
+
frames: 0,
|
|
398
|
+
curve: "linear"
|
|
399
|
+
});
|
|
400
|
+
function clipLength(clip) {
|
|
401
|
+
return clip.end - clip.start;
|
|
402
|
+
}
|
|
403
|
+
function planLength(plan) {
|
|
404
|
+
let total = 0;
|
|
405
|
+
for (const clip of plan.clips) total += clipLength(clip);
|
|
406
|
+
return total;
|
|
407
|
+
}
|
|
408
|
+
function clipOffsets(plan) {
|
|
409
|
+
const offsets = [];
|
|
410
|
+
let at = 0;
|
|
411
|
+
for (const clip of plan.clips) {
|
|
412
|
+
offsets.push(at);
|
|
413
|
+
at += clipLength(clip);
|
|
414
|
+
}
|
|
415
|
+
return offsets;
|
|
416
|
+
}
|
|
417
|
+
// src/core/operations/commands.ts
|
|
418
|
+
var MIN_GAIN_DB = -120;
|
|
419
|
+
var MAX_GAIN_DB = 120;
|
|
420
|
+
var MAX_METADATA_LENGTH = 1e3;
|
|
421
|
+
// src/messages/en.ts
|
|
422
|
+
var audioMessages = /* @__PURE__ */ defineMessages({
|
|
423
|
+
...sdkCoreMessages,
|
|
424
|
+
"errors.INVALID_AUDIO": "This file isn't valid audio, or it's too damaged to open.",
|
|
425
|
+
"errors.UNSUPPORTED_FORMAT": "This audio format isn't supported. Try converting the file to WAV, then open it again.",
|
|
426
|
+
"errors.DECODE_FAILED": "This browser can't play this kind of audio. Try another browser, or convert the file to WAV.",
|
|
427
|
+
"errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
|
|
428
|
+
"errors.DURATION_TOO_LONG": "This recording is longer than the editor can open.",
|
|
429
|
+
"errors.TOO_MANY_CHANNELS": "This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.",
|
|
430
|
+
"errors.SAMPLE_RATE_TOO_HIGH": "This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.",
|
|
431
|
+
"errors.SESSION_TOO_LARGE": "The open recordings would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Remove a recording, or clear the undo history, and try again.",
|
|
432
|
+
"errors.TOO_MANY_CLIPS": /* @__PURE__ */ plural("maximum", {
|
|
433
|
+
one: "A recording can have {maximum} clip. Join or delete clips, and try again.",
|
|
434
|
+
other: "A recording can have up to {maximum} clips. Join or delete clips, and try again."
|
|
435
|
+
}),
|
|
436
|
+
"warnings.maxDuration": "This recording is long, and may be slow to open and edit.",
|
|
437
|
+
"warnings.maxChannels": "This recording has {actual, number} channels, and may be slow to edit.",
|
|
438
|
+
"warnings.maxSampleRate": "This recording's sample rate is {actual, number} Hz, and it may be slow to edit.",
|
|
439
|
+
"warnings.maxSessionSize": "The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.",
|
|
440
|
+
"warnings.maxClips": /* @__PURE__ */ plural("actual", {
|
|
441
|
+
one: "This recording has {actual} clip. Many clips may be slow to play and export.",
|
|
442
|
+
other: "This recording has {actual} clips. Many clips may be slow to play and export."
|
|
443
|
+
})
|
|
444
|
+
});
|
|
445
|
+
export { AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, createAudioEngine, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, secondsToFrames };
|
|
446
|
+
|
|
447
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","names":[],"sources":["../src/core/errors/audio-error.ts","../src/core/errors/abort.ts","../src/adapters/assets-url.ts","../src/adapters/peaks.ts","../src/adapters/web-audio/platform-decode.ts","../src/adapters/audio-engine.ts","../src/core/errors/audio-limits.ts","../src/core/model/envelope.ts","../src/core/model/time.ts","../src/core/model/plan.ts","../src/core/operations/commands.ts","../src/messages/en.ts"],"sourcesContent":["import { isSdkError, type SdkCoreErrorCode, SdkError } from \"@hussmartinez/sdk-core\";\n\n/**\n * Error codes of `@hussmartinez/audio-sdk`: sdk-core's own codes, such as\n * `ABORTED`, `WORKER_CRASHED` and `FILE_TOO_LARGE`, plus the audio SDK's\n * (ADR 0004). They never change meaning once released.\n *\n * - `INVALID_AUDIO`: the file is malformed, its headers claim more audio than\n * its packets carry, or it decodes to more than its bound allows.\n * - `UNSUPPORTED_FORMAT`: the container or codec isn't recognised, the file's\n * packets can't be walked to a bound, or the browser can't decode at its\n * sample rate.\n * - `DECODE_FAILED`: the browser couldn't decode a file the SDK probed,\n * usually because it lacks the codec. `details.codec` names it.\n * - `INVALID_COMMAND`: an edit command doesn't apply to the clip plan, such\n * as a range outside its source or an unknown clip key.\n * - `DURATION_TOO_LONG`: a file exceeds the `maxDuration` limit.\n * - `TOO_MANY_CHANNELS`: a file exceeds the `maxChannels` limit.\n * - `SAMPLE_RATE_TOO_HIGH`: a file exceeds the `maxSampleRate` limit.\n * - `SESSION_TOO_LARGE`: the decoded audio the session holds exceeds the\n * `maxSessionSize` limit.\n * - `TOO_MANY_CLIPS`: the clip plan exceeds the `maxClips` limit.\n *\n * Limit codes carry `details` with the `limit`, its `maximum`, the `actual`\n * value and the `unit`. Other codes' `details` name the container, codec or\n * sample rate involved, never data from the file.\n *\n * @public\n */\nexport type AudioErrorCode =\n | SdkCoreErrorCode\n | \"INVALID_AUDIO\"\n | \"UNSUPPORTED_FORMAT\"\n | \"DECODE_FAILED\"\n | \"INVALID_COMMAND\"\n | \"DURATION_TOO_LONG\"\n | \"TOO_MANY_CHANNELS\"\n | \"SAMPLE_RATE_TOO_HIGH\"\n | \"SESSION_TOO_LARGE\"\n | \"TOO_MANY_CLIPS\";\n\n/**\n * The error `@hussmartinez/audio-sdk` throws and rejects with, with a stable\n * `code`, structured `details` and the underlying error as `cause`. Show\n * users the text for its code from {@link audioMessages}, never its\n * `message`, which is for developers and may contain text from the file.\n *\n * @example\n * ```ts\n * try {\n * await session.open(file);\n * } catch (error) {\n * if (isAudioError(error, \"DECODE_FAILED\")) {\n * suggestConvertingToWav();\n * } else {\n * show(messages.error(error));\n * }\n * }\n * ```\n *\n * @public\n */\nexport class AudioError extends SdkError<AudioErrorCode> {\n /** Always `\"AudioError\"`, which survives minification and worker boundaries. */\n override readonly name = \"AudioError\";\n}\n\n/**\n * Checks whether a value is an {@link AudioError}, optionally with a given\n * code.\n *\n * Unlike `instanceof`, it recognises errors from another copy of this\n * package or another realm, and errors rebuilt after crossing a worker\n * boundary.\n *\n * @param value - Any thrown value.\n * @param code - When given, the error must also have this code.\n * @public\n */\nexport function isAudioError<Code extends AudioErrorCode = AudioErrorCode>(\n value: unknown,\n code?: Code,\n): value is AudioError & { readonly code: Code } {\n return isSdkError(value, code) && value.name === \"AudioError\";\n}\n","import { isSdkError } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * Makes any failure an `AudioError`, as every port promises: an\n * `AudioError` as it is, another `SdkError`, such as the worker client's own\n * `ABORTED` or `WORKER_CRASHED`, with its code, details and message kept, and\n * anything else as `UNKNOWN`. The original is kept as `cause`.\n *\n * @internal\n */\nexport function asAudioError(reason: unknown, message = \"Audio processing failed.\"): AudioError {\n if (reason instanceof AudioError) {\n return reason;\n }\n if (isSdkError(reason)) {\n return new AudioError(reason.code as never, reason.message, {\n ...(reason.details === undefined ? {} : { details: reason.details }),\n cause: reason,\n });\n }\n return new AudioError(\"UNKNOWN\", message, { cause: reason });\n}\n\n/**\n * The error an aborted call rejects with, as the family's worker client does\n * (ADR 0018, ADR 0020): the reason itself when it's an `SdkError`, such as a\n * file policy's `PROCESSING_TIME_EXCEEDED`, `TIMEOUT` for a timeout, and\n * `ABORTED` otherwise. The reason is kept as `cause`.\n *\n * @internal\n */\nexport function abortError(signal: AbortSignal): AudioError {\n const { reason } = signal;\n if (reason instanceof AudioError) {\n return reason;\n }\n if (isSdkError(reason)) {\n return asAudioError(reason);\n }\n const timedOut = reason instanceof DOMException && reason.name === \"TimeoutError\";\n return new AudioError(\n timedOut ? \"TIMEOUT\" : \"ABORTED\",\n timedOut ? \"The operation timed out.\" : \"The operation was cancelled.\",\n { cause: reason },\n );\n}\n\n/**\n * Throws {@link abortError} if the signal has been aborted.\n *\n * @internal\n */\nexport function throwIfAborted(signal: AbortSignal | undefined): void {\n if (signal?.aborted) {\n throw abortError(signal);\n }\n}\n","/**\n * `assetsUrl` as an absolute URL ending in a slash. `assetsUrl` is where the\n * application serves the package's `dist/assets/` directory, which holds\n * `audio/audio.worker.js` (docs/adr/0002). Relative URLs resolve against the\n * page.\n */\nexport function assetsBase(assetsUrl: string | URL | undefined): string | undefined {\n if (assetsUrl === undefined) return undefined;\n const base = new URL(String(assetsUrl), globalThis.location?.href).href;\n return base.endsWith(\"/\") ? base : `${base}/`;\n}\n","import type { AudioPeakLevel, AudioPeaks } from \"../core/model/source.js\";\n\n/**\n * Frames per bucket at the finest level of a waveform overview. Each coarser\n * level groups four buckets of the one before (docs/adr/0002).\n *\n * @internal\n */\nexport const FINEST_BUCKET = 256;\n\n/** How many buckets each coarser level combines. */\nconst LEVEL_FACTOR = 4;\n\n/** Each channel's minimum and maximum per bucket. */\nexport interface BucketPeaks {\n readonly min: Float32Array[];\n readonly max: Float32Array[];\n}\n\n/**\n * The minimum and maximum of each bucket of `bucket` frames, per channel.\n * Called on a block whose first frame starts a bucket; a last, shorter\n * bucket covers what's left.\n *\n * @internal\n */\nexport function blockPeaks(channels: readonly Float32Array[], bucket: number): BucketPeaks {\n const min: Float32Array[] = [];\n const max: Float32Array[] = [];\n for (const samples of channels) {\n const count = Math.ceil(samples.length / bucket);\n const low = new Float32Array(count);\n const high = new Float32Array(count);\n for (let b = 0; b < count; b += 1) {\n const end = Math.min(samples.length, (b + 1) * bucket);\n let lo = Number.POSITIVE_INFINITY;\n let hi = Number.NEGATIVE_INFINITY;\n for (let i = b * bucket; i < end; i += 1) {\n const sample = samples[i] as number;\n if (sample < lo) lo = sample;\n if (sample > hi) hi = sample;\n }\n low[b] = lo;\n high[b] = hi;\n }\n min.push(low);\n max.push(high);\n }\n return { min, max };\n}\n\n/**\n * Builds the whole pyramid from the finest level, each level combining four\n * buckets of the one before, until a level has one bucket.\n *\n * @internal\n */\nexport function buildPyramid(finest: BucketPeaks, bucket = FINEST_BUCKET): AudioPeaks {\n const levels: AudioPeakLevel[] = [];\n let current = finest;\n let framesPerBucket = bucket;\n for (;;) {\n levels.push({\n framesPerBucket,\n channels: current.min.map((min, c) => ({ min, max: current.max[c] as Float32Array })),\n });\n const count = current.min[0]?.length ?? 0;\n if (count <= 1) break;\n current = {\n min: current.min.map((values) => combine(values, Math.min)),\n max: current.max.map((values) => combine(values, Math.max)),\n };\n framesPerBucket *= LEVEL_FACTOR;\n }\n return { levels };\n}\n\nfunction combine(values: Float32Array, pick: (a: number, b: number) => number): Float32Array {\n const out = new Float32Array(Math.ceil(values.length / LEVEL_FACTOR));\n for (let i = 0; i < out.length; i += 1) {\n let value = values[i * LEVEL_FACTOR] as number;\n const end = Math.min(values.length, (i + 1) * LEVEL_FACTOR);\n for (let j = i * LEVEL_FACTOR + 1; j < end; j += 1) value = pick(value, values[j] as number);\n out[i] = value;\n }\n return out;\n}\n","import { abortError, throwIfAborted } from \"../../core/errors/abort.js\";\nimport { AudioError, isAudioError } from \"../../core/errors/audio-error.js\";\nimport type { AudioProbe, DecodedAudio } from \"../../core/model/source.js\";\n\n/**\n * Decodes a file's bytes with a platform decoder, at the given rate and\n * channel count. The SDK's is Web Audio's; tests pass their own.\n *\n * @internal\n */\nexport type PlatformDecoder = (\n bytes: ArrayBuffer,\n format: { readonly sampleRate: number; readonly channels: number },\n) => Promise<DecodedAudio>;\n\n/** A buffer the decoded audio can be copied into, when it must be shortened. */\nexport type CreateBuffer = (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n}) => DecodedAudio & {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n};\n\n/**\n * Web Audio's decoder: `decodeAudioData` on a fresh `OfflineAudioContext` at\n * the file's probed rate, so nothing is resampled (docs/adr/0001). It exists\n * only on the page.\n *\n * @internal\n */\nexport const webAudioDecoder: PlatformDecoder = (bytes, { sampleRate, channels }) => {\n const Offline = (globalThis as { OfflineAudioContext?: typeof OfflineAudioContext })\n .OfflineAudioContext;\n if (typeof Offline !== \"function\") {\n throw new AudioError(\"UNSUPPORTED_ENVIRONMENT\", \"Web Audio isn't available.\", {\n details: { feature: \"OfflineAudioContext\" },\n });\n }\n let context: OfflineAudioContext;\n try {\n context = new Offline({ numberOfChannels: channels, length: 1, sampleRate });\n } catch (error) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"This browser can't decode at this rate.\", {\n details: { sampleRate },\n cause: error,\n });\n }\n return context.decodeAudioData(bytes);\n};\n\n/** Settles with the decode, or rejects as soon as the signal aborts. */\nfunction untilAborted<T>(work: Promise<T>, signal: AbortSignal | undefined): Promise<T> {\n // A result that arrives after an abort is dropped, and so is a late\n // failure, which would otherwise be reported as unhandled.\n work.catch(() => {});\n if (!signal) return work;\n return new Promise<T>((resolve, reject) => {\n const onAbort = () => reject(abortError(signal));\n if (signal.aborted) {\n onAbort();\n return;\n }\n signal.addEventListener(\"abort\", onAbort, { once: true });\n work.then(resolve, reject).finally(() => signal.removeEventListener(\"abort\", onAbort));\n });\n}\n\n/**\n * Decodes a probed compressed file on the page, under sdk-core ADR 0031's\n * rules for platform decoders that only run there:\n *\n * - **Only probed files:** the caller passes the probe that walked this\n * file's packets, and the limits have been checked against its bound.\n * - **A fresh buffer:** the decoder gets bytes read from the `Blob` for it,\n * which it may detach; no caller-owned buffer is ever handed over.\n * - **The output is checked against the bound:** a different rate, more\n * channels than the probe allows, or more frames than the bound plus the\n * codec's tolerance,\n * fails with `INVALID_AUDIO`, and the output is discarded. A result within\n * the tolerance but past the bound is shortened to the bound.\n * - **Never the decoder's errors:** a failure becomes `DECODE_FAILED`, with\n * `details` naming the container and codec, never the browser's message,\n * which is kept only as the error's `cause`.\n * - **The time limit:** a page-side decode can't be terminated, so when the\n * signal aborts, as `maxProcessingTime` does, it stops waiting and rejects\n * with the abort's code, such as `PROCESSING_TIME_EXCEEDED`; the result is\n * discarded whenever it arrives.\n *\n * @internal\n */\nexport async function decodeOnPage(\n file: Blob,\n probe: AudioProbe,\n decoder: PlatformDecoder,\n createBuffer: CreateBuffer,\n signal?: AbortSignal,\n): Promise<DecodedAudio> {\n const { container, codec, sampleRate, channels, frameBound, frameTolerance } = probe;\n throwIfAborted(signal);\n const bytes = await untilAborted(file.arrayBuffer(), signal);\n\n let decoded: DecodedAudio;\n try {\n decoded = await untilAborted(\n Promise.resolve().then(() => decoder(bytes, { sampleRate, channels })),\n signal,\n );\n } catch (error) {\n if (isAudioError(error)) throw error;\n throw new AudioError(\"DECODE_FAILED\", \"The browser couldn't decode this file.\", {\n details: { container, codec },\n cause: error,\n });\n }\n\n // A decoder that \"succeeds\" with no audio, as WebKit does on some crafted\n // Opus, hasn't decoded the file.\n if (decoded.length === 0) {\n throw new AudioError(\"DECODE_FAILED\", \"The browser decoded no audio from this file.\", {\n details: { container, codec, reason: \"no audio decoded\" },\n });\n }\n\n const invalid = (reason: string) =>\n new AudioError(\"INVALID_AUDIO\", `The decoded audio ${reason}.`, {\n details: { container, codec, reason: `decoded ${reason}` },\n });\n if (decoded.sampleRate !== sampleRate) throw invalid(\"rate differs from the probe\");\n // The probe allows for the most channels a decoder may output, such as\n // stereo for mono AAC that may carry parametric stereo; fewer is fine.\n if (decoded.numberOfChannels > channels) throw invalid(\"channel count exceeds the probe\");\n if (decoded.length > frameBound + frameTolerance) throw invalid(\"length exceeds the bound\");\n if (decoded.length <= frameBound) return decoded;\n\n // Within the tolerance but past the bound: the source is the bound's length.\n const capped = createBuffer({\n numberOfChannels: decoded.numberOfChannels,\n length: frameBound,\n sampleRate,\n });\n for (let c = 0; c < decoded.numberOfChannels; c += 1) {\n capped.copyToChannel(decoded.getChannelData(c).subarray(0, frameBound), c, 0);\n }\n return capped;\n}\n","import { createWorkerClient, type WorkerClient, type WorkerLike } from \"@hussmartinez/sdk-core\";\nimport { asAudioError, throwIfAborted } from \"../core/errors/abort.js\";\nimport { AudioError } from \"../core/errors/audio-error.js\";\nimport type { AudioPeaks, AudioProbe, DecodedAudio } from \"../core/model/source.js\";\nimport type { AudioEngine } from \"../core/ports/audio-engine.js\";\nimport { assetsBase } from \"./assets-url.js\";\nimport type { AudioWorkerContract } from \"./audio-worker/contract.js\";\nimport type { PcmLayout } from \"./pcm/layout.js\";\nimport { type BucketPeaks, buildPyramid, FINEST_BUCKET } from \"./peaks.js\";\nimport {\n decodeOnPage,\n type PlatformDecoder,\n webAudioDecoder,\n} from \"./web-audio/platform-decode.js\";\n\n/**\n * Frames per block between the page and the worker: at most 2¹⁶ per\n * channel (docs/adr/0002), and a whole number of finest peak buckets.\n */\nconst BLOCK_FRAMES = 65_536;\n\n/**\n * Options for {@link createAudioEngine}.\n *\n * @public\n */\nexport interface AudioEngineOptions {\n /**\n * Milliseconds without calls after which the worker stops. It starts again\n * on the next call. Defaults to sdk-core's 30 seconds.\n */\n readonly idleTimeout?: number;\n /**\n * Where the application serves the package's `dist/assets/` directory, to\n * load the worker from its own origin instead of a `blob:` URL. The worker\n * is then `audio/audio.worker.js` there, and a Content Security Policy\n * needs `worker-src 'self'` and no `blob:` (docs/adr/0002). Copy\n * `dist/assets` again after every upgrade: a worker from another version\n * is refused with `WORKER_START_FAILED`. By default the worker is inlined.\n */\n readonly assetsUrl?: string | URL;\n}\n\n/** An `AudioBuffer`, or what tests use in its place. */\nexport interface WritableAudio extends DecodedAudio {\n copyToChannel(source: Float32Array, channel: number, startInChannel: number): void;\n}\n\n/** What the engine needs from its environment, replaceable in tests. */\nexport interface EngineEnvironment {\n /** Loads the worker's code, on the first call, and returns how to start it. */\n readonly loadWorker: () => Promise<() => WorkerLike>;\n /** Creates an empty buffer for a decoded source. Throws for a sample rate it can't hold. */\n readonly createBuffer: (options: {\n numberOfChannels: number;\n length: number;\n sampleRate: number;\n }) => WritableAudio;\n /** Decodes compressed files on the page (sdk-core ADR 0031). */\n readonly decodePlatform: PlatformDecoder;\n readonly idleTimeout?: number;\n /** The version the worker must report: this package's. */\n readonly version: string;\n /** Where the worker comes from, for the version error's details. */\n readonly asset?: string;\n}\n\n/**\n * Creates the SDK's audio engine (docs/adr/0001, docs/adr/0002). It probes\n * files in its worker: WAV and AIFF, FLAC (native or in Ogg), MP3, AAC in\n * ADTS, AAC or ALAC in MP4, Opus or Vorbis in Ogg, and Opus, Vorbis, FLAC\n * or AAC in WebM and Matroska, walking every frame of a compressed file to\n * bound its decoded length. It parses WAV and AIFF block by block into an\n * `AudioBuffer`, building the waveform overview as it goes. It decodes\n * compressed files with the browser's own decoder, on the page, under\n * sdk-core ADR 0031's rules: only probed files, a fresh buffer, the output\n * checked against the probe's bound, errors by code, and the time limit of\n * the caller's signal. Other containers fail with `UNSUPPORTED_FORMAT`.\n *\n * Nothing starts until the first call. By default the worker is inlined,\n * which needs `worker-src blob:` in a Content Security Policy; with\n * `assetsUrl` it loads from your own origin, which needs `worker-src 'self'`\n * instead. Either way it makes no requests of its own.\n *\n * @example\n * ```ts\n * const engine = createAudioEngine();\n * const probe = await engine.probe(file);\n * policy.check(\"maxDuration\", (probe.frameBound / probe.sampleRate) * 1000);\n * const audio = await engine.decode(file, probe, { onProgress });\n * ```\n *\n * @public\n */\nexport function createAudioEngine(options: AudioEngineOptions = {}): AudioEngine {\n const base = assetsBase(options.assetsUrl);\n const selfHosted = base === undefined ? undefined : `${base}audio/audio.worker.js`;\n return createEngine({\n loadWorker: selfHosted\n ? async () => () => new Worker(selfHosted, { type: \"module\", name: \"hm-audio\" })\n : async () => (await import(\"./audio-worker/inline-worker.js\")).createInlineWorker,\n version: __AUDIO_SDK_VERSION__,\n ...(selfHosted ? { asset: selfHosted } : {}),\n createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),\n decodePlatform: webAudioDecoder,\n ...(options.idleTimeout === undefined ? {} : { idleTimeout: options.idleTimeout }),\n });\n}\n\n/**\n * The engine, with its environment passed in.\n *\n * @internal\n */\nexport function createEngine(environment: EngineEnvironment): AudioEngine {\n let startWorker: (() => WorkerLike) | undefined;\n let destroyed = false;\n const layouts = new WeakMap<AudioProbe, PcmLayout>();\n /** Probes of compressed files this engine made, which decode can trust. */\n const compressedProbes = new WeakSet<AudioProbe>();\n const finestPeaks = new WeakMap<DecodedAudio, BucketPeaks>();\n\n const newClient = () =>\n createWorkerClient<AudioWorkerContract>({\n createWorker: () => {\n if (!startWorker) {\n throw new AudioError(\"WORKER_START_FAILED\", \"The audio worker hasn't loaded.\");\n }\n return startWorker();\n },\n errorClasses: { AudioError },\n ...(environment.idleTimeout === undefined ? {} : { idleTimeout: environment.idleTimeout }),\n });\n // Probing, parsing and exports run in order on one client; analysis, such\n // as peaks for audio the worker didn't parse, on another, so cancelling it\n // never fails them as collateral (docs/adr/0002).\n let main: WorkerClient<AudioWorkerContract> | undefined;\n let analysis: WorkerClient<AudioWorkerContract> | undefined;\n\n let versionChecked: Promise<void> | undefined;\n\n async function ready(): Promise<void> {\n if (destroyed) throw new Error(\"The audio engine has been destroyed.\");\n startWorker ??= await environment.loadWorker();\n // A self-hosted worker copied before an upgrade would speak the same\n // protocol but run older code, so the first call checks its version.\n versionChecked ??= (async () => {\n main ??= newClient();\n const actual = await main.call(\"version\", undefined);\n if (actual !== environment.version) {\n throw new AudioError(\n \"WORKER_START_FAILED\",\n \"The audio worker isn't this version of the SDK. Copy dist/assets again after upgrading.\",\n {\n details: {\n asset: environment.asset ?? \"inline\",\n expected: environment.version,\n actual,\n },\n },\n );\n }\n })();\n try {\n await versionChecked;\n } catch (error) {\n versionChecked = undefined;\n throw error;\n }\n }\n\n async function run<T>(work: () => Promise<T>): Promise<T> {\n try {\n return await work();\n } catch (error) {\n throw error instanceof RangeError || error instanceof TypeError ? error : asAudioError(error);\n }\n }\n\n /**\n * Probes the file again for a probe this engine didn't make, such as a\n * copy, and requires it to describe the same audio: a decoder only ever\n * runs on a file whose bound this engine established (sdk-core ADR 0031).\n */\n async function reprobe(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.codec === probe.codec &&\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n return fresh.probe;\n }\n\n async function layoutOf(file: Blob, probe: AudioProbe, signal?: AbortSignal) {\n const known = layouts.get(probe);\n if (known) return known;\n // A probe the caller rebuilt or copied: read the header again, and make\n // sure it describes the same audio.\n main ??= newClient();\n const fresh = await main.call(\"probe\", { file }, signal ? { signal } : {});\n const same =\n fresh.probe.sampleRate === probe.sampleRate &&\n fresh.probe.channels === probe.channels &&\n fresh.probe.frameBound === probe.frameBound;\n if (!same) {\n throw new AudioError(\"INVALID_AUDIO\", \"The probe doesn't describe this file.\", {\n details: { container: probe.container },\n });\n }\n if (!fresh.layout) {\n throw new AudioError(\"UNSUPPORTED_FORMAT\", \"Compressed formats aren't supported yet.\", {\n details: { container: probe.container, codec: probe.codec },\n });\n }\n return fresh.layout;\n }\n\n return {\n probe(file, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n await ready();\n main ??= newClient();\n const result = await main.call(\n \"probe\",\n { file },\n options.signal ? { signal: options.signal } : {},\n );\n if (result.layout) layouts.set(result.probe, result.layout);\n else compressedProbes.add(result.probe);\n return result.probe;\n });\n },\n\n decode(file, probe, options = {}) {\n return run(async () => {\n throwIfAborted(options.signal);\n await ready();\n if (probe.codec !== \"pcm\") {\n const trusted = compressedProbes.has(probe)\n ? probe\n : await reprobe(file, probe, options.signal);\n const audio = await decodeOnPage(\n file,\n trusted,\n environment.decodePlatform,\n environment.createBuffer,\n options.signal,\n );\n options.onProgress?.(1);\n return audio;\n }\n const layout = await layoutOf(file, probe, options.signal);\n const { frames, channels, sampleRate } = layout;\n let buffer: WritableAudio;\n try {\n buffer = environment.createBuffer({\n numberOfChannels: channels,\n length: frames,\n sampleRate,\n });\n } catch (error) {\n throw new AudioError(\n \"UNSUPPORTED_FORMAT\",\n \"This browser can't hold audio at this rate.\",\n {\n details: { container: layout.container, sampleRate },\n cause: error,\n },\n );\n }\n\n const buckets = Math.ceil(frames / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: channels }, () => new Float32Array(buckets)),\n max: Array.from({ length: channels }, () => new Float32Array(buckets)),\n };\n main ??= newClient();\n for (let start = 0; start < frames; start += BLOCK_FRAMES) {\n const block = await main.call(\n \"readBlock\",\n {\n file,\n layout,\n start,\n frames: Math.min(BLOCK_FRAMES, frames - start),\n bucket: FINEST_BUCKET,\n },\n options.signal ? { signal: options.signal } : {},\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < channels; c += 1) {\n buffer.copyToChannel(block.channels[c] as Float32Array, c, start);\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n options.onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);\n }\n if (frames === 0) options.onProgress?.(1);\n finestPeaks.set(buffer, peaks);\n return buffer;\n });\n },\n\n peaks(audio, options = {}) {\n return run(async (): Promise<AudioPeaks> => {\n throwIfAborted(options.signal);\n const known = finestPeaks.get(audio);\n if (known) return buildPyramid(known, FINEST_BUCKET);\n await ready();\n analysis ??= newClient();\n const buckets = Math.ceil(audio.length / FINEST_BUCKET);\n const peaks: BucketPeaks = {\n min: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n max: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),\n };\n for (let start = 0; start < audio.length; start += BLOCK_FRAMES) {\n const end = Math.min(audio.length, start + BLOCK_FRAMES);\n // Copies of one block, so the source is never transferred away.\n const channels = Array.from({ length: audio.numberOfChannels }, (_, c) =>\n audio.getChannelData(c).slice(start, end),\n );\n const block = await analysis.call(\n \"peaks\",\n { channels, bucket: FINEST_BUCKET },\n { transfer: true, ...(options.signal ? { signal: options.signal } : {}) },\n );\n const at = start / FINEST_BUCKET;\n for (let c = 0; c < audio.numberOfChannels; c += 1) {\n peaks.min[c]?.set(block.min[c] as Float32Array, at);\n peaks.max[c]?.set(block.max[c] as Float32Array, at);\n }\n }\n finestPeaks.set(audio, peaks);\n return buildPyramid(peaks, FINEST_BUCKET);\n });\n },\n\n async destroy() {\n destroyed = true;\n main?.destroy();\n analysis?.destroy();\n },\n };\n}\n","import {\n coreLimits,\n defineLimits,\n type FilePolicy,\n type FilePolicyOverrides,\n type Limits,\n} from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"./audio-error.js\";\n\n/**\n * The audio SDK's limit definitions: sdk-core's core limits with audio\n * defaults, plus five for audio (ADR 0004).\n *\n * | Limit | Code | Default maximum | Default warning |\n * |---|---|---|---|\n * | `maxFileSize` | `FILE_TOO_LARGE` | 1 GB | 250 MB |\n * | `maxFiles` | `TOO_MANY_FILES` | 20 | none |\n * | `maxDecodedSize` | `DECODED_SIZE_TOO_LARGE` | 1 GB | 400 MB |\n * | `maxProcessingTime` | `PROCESSING_TIME_EXCEEDED` | 120 s | none |\n * | `maxDuration` | `DURATION_TOO_LONG` | 3 hours | 1 hour |\n * | `maxChannels` | `TOO_MANY_CHANNELS` | 8 | none |\n * | `maxSampleRate` | `SAMPLE_RATE_TOO_HIGH` | 192 kHz | none |\n * | `maxSessionSize` | `SESSION_TOO_LARGE` | 1.5 GB | 750 MB |\n * | `maxClips` | `TOO_MANY_CLIPS` | 2,000 | none |\n *\n * Sizes are decimal: 1 MB is 1,000,000 bytes. Decoded sizes count 32-bit\n * floats: frames × channels × 4 bytes. `maxDuration` is in milliseconds, and\n * `maxSampleRate` counts samples per second (hertz).\n *\n * @public\n */\nexport const audioLimitDefinitions = {\n ...coreLimits,\n maxFileSize: { ...coreLimits.maxFileSize, default: 1_000_000_000, warning: 250_000_000 },\n maxDecodedSize: { ...coreLimits.maxDecodedSize, default: 1_000_000_000, warning: 400_000_000 },\n maxDuration: {\n code: \"DURATION_TOO_LONG\",\n unit: \"milliseconds\",\n default: 3 * 60 * 60 * 1_000,\n warning: 60 * 60 * 1_000,\n },\n maxChannels: { code: \"TOO_MANY_CHANNELS\", unit: \"count\", default: 8 },\n // TODO(sdk-core#59): use a \"hertz\" unit once LimitUnit has one, before the\n // first release, since `details.unit` is public.\n // https://github.com/ie-huss-martinez/sdk-core/issues/59\n maxSampleRate: { code: \"SAMPLE_RATE_TOO_HIGH\", unit: \"count\", default: 192_000 },\n maxSessionSize: {\n code: \"SESSION_TOO_LARGE\",\n unit: \"bytes\",\n default: 1_500_000_000,\n warning: 750_000_000,\n },\n maxClips: { code: \"TOO_MANY_CLIPS\", unit: \"count\", default: 2_000 },\n} as const;\n\n/**\n * The type of {@link audioLimitDefinitions}.\n *\n * @public\n */\nexport type AudioLimitDefinitions = typeof audioLimitDefinitions;\n\n/**\n * The names of the audio SDK's limits.\n *\n * @public\n */\nexport type AudioLimitName = keyof AudioLimitDefinitions;\n\n/**\n * A host's `filePolicy`: a new maximum, or `{ maximum, warning }`, for any of\n * the audio SDK's limits. `Infinity` disables a maximum, which removes a\n * protection against hostile files, or disables a warning. Unknown limit\n * names throw `TypeError` when the policy is resolved.\n *\n * @example\n * ```ts\n * // Long recordings: raise the decoded and session sizes together.\n * const filePolicy: AudioFilePolicyOverrides = {\n * maxDecodedSize: 2e9,\n * maxSessionSize: { maximum: 3e9, warning: 1.5e9 },\n * };\n * ```\n *\n * @public\n */\nexport type AudioFilePolicyOverrides = FilePolicyOverrides<AudioLimitDefinitions>;\n\n/**\n * A resolved file policy for the audio SDK. Violations throw\n * {@link AudioError}.\n *\n * @public\n */\nexport type AudioFilePolicy = FilePolicy<AudioLimitDefinitions>;\n\n/**\n * The audio SDK's limits, ready to resolve a host's `filePolicy`. Violations\n * are thrown as {@link AudioError}, with `details` naming the limit.\n *\n * @example\n * ```ts\n * const policy = audioLimits.resolve(props.filePolicy);\n * policy.check(\"maxChannels\", channels); // throws AudioError(\"TOO_MANY_CHANNELS\") above 8\n * ```\n *\n * @public\n */\nexport const audioLimits: Limits<AudioLimitDefinitions> = /* @__PURE__ */ defineLimits(\n audioLimitDefinitions,\n { errorClass: AudioError },\n);\n","import type { AudioClip, AudioFadeCurve } from \"./plan.js\";\n\n/**\n * Converts decibels to a linear gain factor.\n *\n * @public\n */\nexport function dbToGain(db: number): number {\n return 10 ** (db / 20);\n}\n\n/** A fade's gain at `position`, from 0 (silent) to 1 (full). */\nfunction fadeShape(curve: AudioFadeCurve, position: number): number {\n return curve === \"equalPower\" ? Math.sin((position * Math.PI) / 2) : position;\n}\n\n/**\n * The gain at one frame of a clip, from its gain and its fades: the single\n * definition of the envelope, which export applies per sample and playback\n * samples into the clip's `GainNode` (ADR 0001).\n *\n * A fade in starts at silence on the clip's first frame, and a fade out\n * reaches silence on its last frame.\n *\n * @param clip - The clip.\n * @param frame - A frame within the clip, from 0 to its length minus one.\n * @public\n */\nexport function gainAt(clip: AudioClip, frame: number): number {\n const length = clip.end - clip.start;\n let gain = dbToGain(clip.gainDb);\n const { fadeIn, fadeOut } = clip;\n if (fadeIn.frames > 0 && frame < fadeIn.frames) {\n gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);\n }\n const fromEnd = length - 1 - frame;\n if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) {\n gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);\n }\n return gain;\n}\n","/**\n * Every position and length in the model is a whole number of frames, at the\n * session's sample rate (ADR 0003). A frame is one sample on every channel.\n * Seconds appear only at the edges: in the UI and in events.\n */\n\n/**\n * Converts frames to seconds, for display and events.\n *\n * @param frames - A whole number of frames.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function framesToSeconds(frames: number, sampleRate: number): number {\n return frames / sampleRate;\n}\n\n/**\n * Converts seconds to the nearest whole frame, for input from the UI, such\n * as a typed trim point.\n *\n * @param seconds - A time in seconds.\n * @param sampleRate - Frames per second.\n * @public\n */\nexport function secondsToFrames(seconds: number, sampleRate: number): number {\n return Math.round(seconds * sampleRate);\n}\n\n/**\n * Throws `RangeError` unless the value is a non-negative whole number of\n * frames.\n *\n * @internal\n */\nexport function assertFrames(name: string, value: number): void {\n if (!Number.isSafeInteger(value) || value < 0) {\n throw new RangeError(`${name} must be a non-negative whole number of frames, not ${value}.`);\n }\n}\n","import { assertFrames } from \"./time.js\";\n\n/**\n * The shape of a fade: `linear` changes the gain at a constant rate, and\n * `equalPower` keeps the perceived loudness steadier, which suits crossfades.\n *\n * @public\n */\nexport type AudioFadeCurve = \"linear\" | \"equalPower\";\n\n/**\n * A fade at one end of a clip. `frames: 0` is no fade.\n *\n * @public\n */\nexport interface AudioFade {\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * One piece of a source, played in the plan (ADR 0003).\n *\n * @public\n */\nexport interface AudioClip {\n /** Stable across edits, so selection and waveform tiles follow a clip that moves. */\n readonly key: string;\n /** The id of the source the clip plays. */\n readonly source: string;\n /** The first source frame the clip plays, inclusive. */\n readonly start: number;\n /** The source frame the clip stops before, exclusive. */\n readonly end: number;\n /** The clip's gain in decibels. 0 leaves it unchanged. */\n readonly gainDb: number;\n readonly fadeIn: AudioFade;\n readonly fadeOut: AudioFade;\n}\n\n/**\n * Metadata that export writes into the file (ADR 0001).\n *\n * @public\n */\nexport interface AudioMetadata {\n readonly title: string;\n readonly artist: string;\n readonly album: string;\n readonly year: string;\n readonly comment: string;\n}\n\n/**\n * The session's document: clips played back to back on one track, over\n * immutable sources, with the metadata (ADR 0003). Every position and length\n * is a whole number of frames at `sampleRate`.\n *\n * @public\n */\nexport interface AudioPlan {\n /** The session's sample rate, from its first source. */\n readonly sampleRate: number;\n /** The session's channel count, from its first source. */\n readonly channels: number;\n readonly clips: readonly AudioClip[];\n readonly metadata: AudioMetadata;\n}\n\n/**\n * Metadata with every field empty.\n *\n * @public\n */\nexport const EMPTY_METADATA: AudioMetadata = Object.freeze({\n title: \"\",\n artist: \"\",\n album: \"\",\n year: \"\",\n comment: \"\",\n});\n\n/**\n * No fade.\n *\n * @public\n */\nexport const NO_FADE: AudioFade = Object.freeze({ frames: 0, curve: \"linear\" });\n\n/**\n * A clip's length in frames.\n *\n * @public\n */\nexport function clipLength(clip: AudioClip): number {\n return clip.end - clip.start;\n}\n\n/**\n * The plan's length in frames: the sum of its clips' lengths.\n *\n * @public\n */\nexport function planLength(plan: AudioPlan): number {\n let total = 0;\n for (const clip of plan.clips) total += clipLength(clip);\n return total;\n}\n\n/**\n * Where each clip starts on the timeline, in frames. It's derived from the\n * clips before it, never stored, so it can't disagree with them (ADR 0003).\n *\n * @public\n */\nexport function clipOffsets(plan: AudioPlan): readonly number[] {\n const offsets: number[] = [];\n let at = 0;\n for (const clip of plan.clips) {\n offsets.push(at);\n at += clipLength(clip);\n }\n return offsets;\n}\n\n/**\n * Throws `RangeError` unless the clip is well formed within a source of\n * `sourceFrames` frames: whole, non-negative frames, at least one frame\n * long, inside the source, with a finite gain and fades that fit the clip\n * together.\n *\n * @internal\n */\nexport function assertClip(clip: AudioClip, sourceFrames: number): void {\n assertFrames(\"start\", clip.start);\n assertFrames(\"end\", clip.end);\n assertFrames(\"fadeIn.frames\", clip.fadeIn.frames);\n assertFrames(\"fadeOut.frames\", clip.fadeOut.frames);\n if (clip.end <= clip.start) {\n throw new RangeError(`Clip ${clip.key} must be at least one frame long.`);\n }\n if (clip.end > sourceFrames) {\n throw new RangeError(`Clip ${clip.key} ends after its source's ${sourceFrames} frames.`);\n }\n if (!Number.isFinite(clip.gainDb)) {\n throw new RangeError(`Clip ${clip.key} has a gain that isn't a finite number.`);\n }\n if (clip.fadeIn.frames + clip.fadeOut.frames > clipLength(clip)) {\n throw new RangeError(`Clip ${clip.key}'s fades are longer than the clip.`);\n }\n}\n","import type { Reducer } from \"@hussmartinez/sdk-core\";\nimport { AudioError } from \"../errors/audio-error.js\";\nimport {\n type AudioClip,\n type AudioFade,\n type AudioFadeCurve,\n type AudioMetadata,\n type AudioPlan,\n assertClip,\n clipLength,\n EMPTY_METADATA,\n NO_FADE,\n planLength,\n} from \"../model/plan.js\";\n\n/**\n * Inserts clips at a timeline frame. When the frame falls inside a clip,\n * that clip is split there: its first part keeps its key, and its second\n * part takes `splitKey`.\n *\n * @public\n */\nexport interface AudioInsertClipsCommand {\n readonly type: \"audio.insertClips\";\n /** The timeline frame to insert at, from 0 to the plan's length. */\n readonly at: number;\n /** The clips, in order, with keys the plan doesn't have. */\n readonly clips: readonly AudioClip[];\n /** The key of the second part of a clip that `at` splits. Required only then. */\n readonly splitKey?: string;\n}\n\n/**\n * Removes clips. Their sources stay, so undo can bring them back.\n *\n * @public\n */\nexport interface AudioRemoveClipsCommand {\n readonly type: \"audio.removeClips\";\n readonly keys: readonly string[];\n}\n\n/**\n * Puts removed clips back at their indexes, with every field as it was.\n * It's what undoing a removal runs.\n *\n * @public\n */\nexport interface AudioRestoreClipsCommand {\n readonly type: \"audio.restoreClips\";\n /** Each clip, and the index it takes in the resulting plan, in increasing order. */\n readonly entries: readonly { readonly index: number; readonly clip: AudioClip }[];\n}\n\n/**\n * Replaces `count` clips from `index` with `clips`. It's what undoing an\n * insert, a split or a range deletion runs: those change a run of\n * neighbouring clips.\n *\n * @public\n */\nexport interface AudioReplaceClipsCommand {\n readonly type: \"audio.replaceClips\";\n readonly index: number;\n readonly count: number;\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Sets clips to new states, matched by key, with every field given. It's\n * what undoing a trim, a gain or a fade runs.\n *\n * @public\n */\nexport interface AudioUpdateClipsCommand {\n readonly type: \"audio.updateClips\";\n readonly clips: readonly AudioClip[];\n}\n\n/**\n * Removes the timeline range from `start` to `end`, trimming the clips at\n * its edges. A range inside one clip splits it: the part after the range\n * takes `newKey`.\n *\n * @public\n */\nexport interface AudioDeleteRangeCommand {\n readonly type: \"audio.deleteRange\";\n /** The first timeline frame removed, inclusive. */\n readonly start: number;\n /** The timeline frame the range stops before, exclusive. */\n readonly end: number;\n /** The key of the part after the range, when the range is inside one clip. Required only then. */\n readonly newKey?: string;\n}\n\n/**\n * Changes the range of its source a clip plays. Fades that no longer fit\n * are shortened in proportion.\n *\n * @public\n */\nexport interface AudioTrimClipCommand {\n readonly type: \"audio.trimClip\";\n readonly key: string;\n /** The first source frame, inclusive. */\n readonly start: number;\n /** The source frame the clip stops before, exclusive. */\n readonly end: number;\n}\n\n/**\n * Splits a clip in two at a timeline frame inside it. The first part keeps\n * the clip's key and fade in, and the second takes `newKey` and the fade out.\n *\n * @public\n */\nexport interface AudioSplitClipCommand {\n readonly type: \"audio.splitClip\";\n readonly key: string;\n /** A timeline frame strictly inside the clip. */\n readonly at: number;\n readonly newKey: string;\n}\n\n/**\n * Moves clips, keeping their relative order, so that the first of them\n * ends up at index `to` of the resulting plan.\n *\n * @public\n */\nexport interface AudioMoveClipsCommand {\n readonly type: \"audio.moveClips\";\n readonly keys: readonly string[];\n readonly to: number;\n}\n\n/**\n * Puts every clip in a new order, given as every key exactly once. It's\n * what undoing a move runs.\n *\n * @public\n */\nexport interface AudioReorderClipsCommand {\n readonly type: \"audio.reorderClips\";\n readonly order: readonly string[];\n}\n\n/**\n * Sets the gain of clips.\n *\n * @public\n */\nexport interface AudioSetGainCommand {\n readonly type: \"audio.setGain\";\n readonly keys: readonly string[];\n /** Decibels, from {@link MIN_GAIN_DB} to {@link MAX_GAIN_DB}. */\n readonly gainDb: number;\n}\n\n/**\n * Sets a clip's fade in or fade out. Together, the two fades must fit in\n * the clip.\n *\n * @public\n */\nexport interface AudioSetFadeCommand {\n readonly type: \"audio.setFade\";\n readonly key: string;\n readonly edge: \"in\" | \"out\";\n /** The fade's length in frames. 0 removes it. */\n readonly frames: number;\n readonly curve: AudioFadeCurve;\n}\n\n/**\n * Sets one metadata field, which export writes into the file.\n *\n * @public\n */\nexport interface AudioSetMetadataCommand {\n readonly type: \"audio.setMetadata\";\n readonly field: keyof AudioMetadata;\n /** At most {@link MAX_METADATA_LENGTH} characters. */\n readonly value: string;\n}\n\n/**\n * An edit to the clip plan (docs/adr/0003). Commands are plain,\n * structured-cloneable data, never carry samples, and each has an exact\n * inverse, which is how undo works (ADR 0010, ADR 0029).\n *\n * @public\n */\nexport type AudioCommand =\n | AudioInsertClipsCommand\n | AudioRemoveClipsCommand\n | AudioRestoreClipsCommand\n | AudioReplaceClipsCommand\n | AudioUpdateClipsCommand\n | AudioDeleteRangeCommand\n | AudioTrimClipCommand\n | AudioSplitClipCommand\n | AudioMoveClipsCommand\n | AudioReorderClipsCommand\n | AudioSetGainCommand\n | AudioSetFadeCommand\n | AudioSetMetadataCommand;\n\n/**\n * The lowest clip gain, in decibels: far below audibility, so it serves as\n * silence.\n *\n * @public\n */\nexport const MIN_GAIN_DB = -120;\n\n/**\n * The highest clip gain, in decibels: enough to normalize a very quiet\n * recording, while every gain stays a finite factor.\n *\n * @public\n */\nexport const MAX_GAIN_DB = 120;\n\n/**\n * The longest metadata value, in UTF-16 code units, so that history steps\n * stay small.\n *\n * @public\n */\nexport const MAX_METADATA_LENGTH = 1_000;\n\nconst CURVES: ReadonlySet<string> = new Set<AudioFadeCurve>([\"linear\", \"equalPower\"]);\n\n/**\n * The frames of each registered source, or `undefined` for an id the\n * session doesn't have. Sources never change, so the reducer stays pure.\n *\n * @internal\n */\nexport type SourceFrames = (source: string) => number | undefined;\n\nclass Invalid extends Error {}\n\nfunction invalid(reason: string): never {\n throw new Invalid(reason);\n}\n\n/** An object whose fields, from a command that may have been stored or sent, are unchecked. */\ntype Unchecked<T> = { readonly [Key in keyof T]?: unknown };\n\nfunction isRecord<T>(value: unknown): value is Unchecked<T> {\n return typeof value === \"object\" && value !== null;\n}\n\nfunction isKey(value: unknown): value is string {\n return typeof value === \"string\" && value.length > 0;\n}\n\nfunction isIndex(value: unknown, max: number): value is number {\n return Number.isSafeInteger(value) && (value as number) >= 0 && (value as number) <= max;\n}\n\nfunction fade(value: unknown, name: string): AudioFade {\n if (!isRecord<AudioFade>(value) || typeof value.curve !== \"string\" || !CURVES.has(value.curve)) {\n invalid(`${name} isn't a fade`);\n }\n return { frames: value.frames as number, curve: value.curve as AudioFadeCurve };\n}\n\nfunction checkGain(gainDb: unknown): number {\n if (typeof gainDb !== \"number\" || !(gainDb >= MIN_GAIN_DB && gainDb <= MAX_GAIN_DB)) {\n invalid(`gain must be from ${MIN_GAIN_DB} to ${MAX_GAIN_DB} dB`);\n }\n return gainDb;\n}\n\n/**\n * A clean copy of a clip from a command, with only its own fields, or a\n * failure if it isn't valid within its source.\n */\nfunction checkClip(value: unknown, sourceFrames: SourceFrames): AudioClip {\n if (!isRecord<AudioClip>(value) || !isKey(value.key) || !isKey(value.source)) {\n invalid(\"a clip needs a key and a source\");\n }\n const clip: AudioClip = {\n key: value.key,\n source: value.source,\n start: value.start as number,\n end: value.end as number,\n gainDb: checkGain(value.gainDb),\n fadeIn: fade(value.fadeIn, \"fadeIn\"),\n fadeOut: fade(value.fadeOut, \"fadeOut\"),\n };\n const frames = sourceFrames(clip.source);\n if (frames === undefined) invalid(`the session has no source ${clip.source}`);\n try {\n assertClip(clip, frames);\n } catch (error) {\n if (error instanceof RangeError) invalid(error.message);\n throw error;\n }\n return clip;\n}\n\nfunction checkClips(values: unknown, sourceFrames: SourceFrames): AudioClip[] {\n if (!Array.isArray(values)) invalid(\"clips must be a list\");\n return values.map((value) => checkClip(value, sourceFrames));\n}\n\n/** Fails unless every key is new: absent from `existing`, and not repeated. */\nfunction checkNewKeys(keys: readonly string[], existing: Iterable<string>): void {\n const seen = new Set(existing);\n for (const key of keys) {\n if (!isKey(key) || seen.has(key)) invalid(`the key ${String(key)} is taken`);\n seen.add(key);\n }\n}\n\n/** The indexes of the given keys, in plan order, failing on unknown or repeated keys. */\nfunction positions(plan: AudioPlan, keys: unknown): number[] {\n if (!Array.isArray(keys) || keys.length === 0) invalid(\"it needs at least one clip\");\n const wanted = new Set<unknown>(keys);\n if (wanted.size !== keys.length) invalid(\"a clip appears twice\");\n const found: number[] = [];\n plan.clips.forEach((clip, index) => {\n if (wanted.has(clip.key)) found.push(index);\n });\n if (found.length !== wanted.size) invalid(\"the plan doesn't have every clip\");\n return found;\n}\n\nfunction position(plan: AudioPlan, key: unknown): number {\n return positions(plan, [key])[0] as number;\n}\n\n/**\n * Shortens fades that no longer fit their clip, in proportion, so that\n * neither reaches into the other.\n */\nfunction fitFades(clip: AudioClip): AudioClip {\n const length = clipLength(clip);\n const total = clip.fadeIn.frames + clip.fadeOut.frames;\n if (total <= length) return clip;\n return {\n ...clip,\n fadeIn: { ...clip.fadeIn, frames: Math.floor((clip.fadeIn.frames * length) / total) },\n fadeOut: { ...clip.fadeOut, frames: Math.floor((clip.fadeOut.frames * length) / total) },\n };\n}\n\n/**\n * The part of a clip from `from` to `to`, in frames from its start. A part\n * keeps the fades of the edges it shares with the clip, and has none at a\n * cut.\n */\nfunction part(clip: AudioClip, from: number, to: number, key: string): AudioClip {\n const length = clipLength(clip);\n return fitFades({\n ...clip,\n key,\n start: clip.start + from,\n end: clip.start + to,\n fadeIn: from === 0 ? clip.fadeIn : NO_FADE,\n fadeOut: to === length ? clip.fadeOut : NO_FADE,\n });\n}\n\n/**\n * Where a timeline frame falls: the index of the clip that contains it and\n * the offset into that clip, or the index after the last clip, at offset 0,\n * for the plan's end.\n */\nfunction locate(plan: AudioPlan, frame: unknown): { index: number; offset: number } {\n if (!isIndex(frame, planLength(plan))) invalid(\"the frame is outside the plan\");\n let at = 0;\n for (const [index, clip] of plan.clips.entries()) {\n const length = clipLength(clip);\n if (frame < at + length) return { index, offset: frame - at };\n at += length;\n }\n return { index: plan.clips.length, offset: 0 };\n}\n\nfunction withClips(plan: AudioPlan, clips: readonly AudioClip[]): AudioPlan {\n return { ...plan, clips };\n}\n\nfunction splice(\n plan: AudioPlan,\n index: number,\n count: number,\n clips: readonly AudioClip[],\n): AudioPlan {\n return withClips(plan, [\n ...plan.clips.slice(0, index),\n ...clips,\n ...plan.clips.slice(index + count),\n ]);\n}\n\nfunction updateByKey(plan: AudioPlan, clips: readonly AudioClip[]): AudioPlan {\n const byKey = new Map(clips.map((clip) => [clip.key, clip]));\n return withClips(\n plan,\n plan.clips.map((clip) => byKey.get(clip.key) ?? clip),\n );\n}\n\ntype Applied = { state: AudioPlan; inverse: AudioCommand };\n\nfunction apply(plan: AudioPlan, command: AudioCommand, sourceFrames: SourceFrames): Applied {\n if (!isRecord<AudioCommand>(command)) invalid(\"a command is an object\");\n switch (command.type) {\n case \"audio.insertClips\": {\n const clips = checkClips(command.clips, sourceFrames);\n if (clips.length === 0) invalid(\"it needs at least one clip\");\n const keys = clips.map((clip) => clip.key);\n checkNewKeys(\n keys,\n plan.clips.map((clip) => clip.key),\n );\n const { index, offset } = locate(plan, command.at);\n if (offset === 0) {\n return {\n state: splice(plan, index, 0, clips),\n inverse: { type: \"audio.replaceClips\", index, count: clips.length, clips: [] },\n };\n }\n const { splitKey } = command;\n if (!isKey(splitKey)) invalid(\"inserting inside a clip needs a splitKey\");\n checkNewKeys([splitKey], [...plan.clips.map((clip) => clip.key), ...keys]);\n const split = plan.clips[index] as AudioClip;\n const parts = [\n part(split, 0, offset, split.key),\n ...clips,\n part(split, offset, clipLength(split), splitKey),\n ];\n return {\n state: splice(plan, index, 1, parts),\n inverse: { type: \"audio.replaceClips\", index, count: parts.length, clips: [split] },\n };\n }\n\n case \"audio.removeClips\": {\n const at = positions(plan, command.keys);\n const removed = new Set(at);\n return {\n state: withClips(\n plan,\n plan.clips.filter((_, index) => !removed.has(index)),\n ),\n inverse: {\n type: \"audio.restoreClips\",\n entries: at.map((index) => ({ index, clip: plan.clips[index] as AudioClip })),\n },\n };\n }\n\n case \"audio.restoreClips\": {\n if (!Array.isArray(command.entries) || command.entries.length === 0) {\n invalid(\"it needs at least one clip\");\n }\n const entries = command.entries.map((entry: unknown) => {\n if (!isRecord<{ index: number; clip: AudioClip }>(entry))\n invalid(\"an entry needs an index and a clip\");\n return { index: entry.index, clip: checkClip(entry.clip, sourceFrames) };\n });\n checkNewKeys(\n entries.map(({ clip }) => clip.key),\n plan.clips.map((clip) => clip.key),\n );\n const clips = [...plan.clips];\n let previous = -1;\n for (const { index, clip } of entries) {\n if (!isIndex(index, clips.length) || index <= previous) {\n invalid(`clip ${clip.key} can't be restored at index ${String(index)}`);\n }\n clips.splice(index, 0, clip);\n previous = index;\n }\n return {\n state: withClips(plan, clips),\n inverse: { type: \"audio.removeClips\", keys: entries.map(({ clip }) => clip.key) },\n };\n }\n\n case \"audio.replaceClips\": {\n const { index, count } = command;\n if (!isIndex(index, plan.clips.length) || !isIndex(count, plan.clips.length - index)) {\n invalid(\"the run of clips is outside the plan\");\n }\n const clips = checkClips(command.clips, sourceFrames);\n if (count === 0 && clips.length === 0) invalid(\"it changes nothing\");\n const removed = plan.clips.slice(index, index + count);\n checkNewKeys(\n clips.map((clip) => clip.key),\n [...plan.clips.slice(0, index), ...plan.clips.slice(index + count)].map((clip) => clip.key),\n );\n return {\n state: splice(plan, index, count, clips),\n inverse: { type: \"audio.replaceClips\", index, count: clips.length, clips: removed },\n };\n }\n\n case \"audio.updateClips\": {\n const clips = checkClips(command.clips, sourceFrames);\n const at = positions(\n plan,\n clips.map((clip) => clip.key),\n );\n return {\n state: updateByKey(plan, clips),\n inverse: {\n type: \"audio.updateClips\",\n clips: at.map((index) => plan.clips[index] as AudioClip),\n },\n };\n }\n\n case \"audio.deleteRange\": {\n const { start, end } = command;\n if (!isIndex(end, planLength(plan)) || !isIndex(start, end - 1)) {\n invalid(\"the range must be at least one frame inside the plan\");\n }\n const first = locate(plan, start);\n const last = locate(plan, end - 1);\n const firstClip = plan.clips[first.index] as AudioClip;\n const lastClip = plan.clips[last.index] as AudioClip;\n const kept: AudioClip[] = [];\n if (first.offset > 0) kept.push(part(firstClip, 0, first.offset, firstClip.key));\n if (last.offset + 1 < clipLength(lastClip)) {\n let key = lastClip.key;\n if (first.index === last.index && first.offset > 0) {\n const { newKey } = command;\n if (!isKey(newKey)) invalid(\"deleting inside a clip needs a newKey\");\n checkNewKeys(\n [newKey],\n plan.clips.map((clip) => clip.key),\n );\n key = newKey;\n }\n kept.push(part(lastClip, last.offset + 1, clipLength(lastClip), key));\n }\n const count = last.index - first.index + 1;\n return {\n state: splice(plan, first.index, count, kept),\n inverse: {\n type: \"audio.replaceClips\",\n index: first.index,\n count: kept.length,\n clips: plan.clips.slice(first.index, first.index + count),\n },\n };\n }\n\n case \"audio.trimClip\": {\n const index = position(plan, command.key);\n const clip = plan.clips[index] as AudioClip;\n const trimmed = checkClip(\n fitFades({ ...clip, start: command.start, end: command.end }),\n sourceFrames,\n );\n return {\n state: updateByKey(plan, [trimmed]),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.splitClip\": {\n const index = position(plan, command.key);\n const clip = plan.clips[index] as AudioClip;\n const { index: within, offset } = locate(plan, command.at);\n if (within !== index || offset === 0) invalid(\"the frame must be strictly inside the clip\");\n checkNewKeys(\n [command.newKey],\n plan.clips.map((entry) => entry.key),\n );\n const parts = [\n part(clip, 0, offset, clip.key),\n part(clip, offset, clipLength(clip), command.newKey),\n ];\n return {\n state: splice(plan, index, 1, parts),\n inverse: { type: \"audio.replaceClips\", index, count: 2, clips: [clip] },\n };\n }\n\n case \"audio.moveClips\": {\n const moved = new Set(positions(plan, command.keys));\n const block = plan.clips.filter((_, index) => moved.has(index));\n const rest = plan.clips.filter((_, index) => !moved.has(index));\n if (!isIndex(command.to, rest.length)) invalid(\"the clips can't move there\");\n return {\n state: withClips(plan, [...rest.slice(0, command.to), ...block, ...rest.slice(command.to)]),\n inverse: { type: \"audio.reorderClips\", order: plan.clips.map((clip) => clip.key) },\n };\n }\n\n case \"audio.reorderClips\": {\n const { order } = command;\n const byKey = new Map(plan.clips.map((clip) => [clip.key, clip]));\n if (\n !Array.isArray(order) ||\n order.length !== plan.clips.length ||\n new Set(order).size !== order.length ||\n order.some((key) => !byKey.has(key))\n ) {\n invalid(\"the order must list every clip exactly once\");\n }\n return {\n state: withClips(\n plan,\n order.map((key) => byKey.get(key) as AudioClip),\n ),\n inverse: { type: \"audio.reorderClips\", order: plan.clips.map((clip) => clip.key) },\n };\n }\n\n case \"audio.setGain\": {\n const at = positions(plan, command.keys);\n const gainDb = checkGain(command.gainDb);\n const before = at.map((index) => plan.clips[index] as AudioClip);\n return {\n state: updateByKey(\n plan,\n before.map((clip) => ({ ...clip, gainDb })),\n ),\n inverse: { type: \"audio.updateClips\", clips: before },\n };\n }\n\n case \"audio.setFade\": {\n const clip = plan.clips[position(plan, command.key)] as AudioClip;\n const { edge, frames } = command;\n if (edge !== \"in\" && edge !== \"out\") invalid(\"the edge must be in or out\");\n const next = { frames, curve: fade(command, \"the fade\").curve };\n const updated = checkClip(\n edge === \"in\" ? { ...clip, fadeIn: next } : { ...clip, fadeOut: next },\n sourceFrames,\n );\n return {\n state: updateByKey(plan, [updated]),\n inverse: { type: \"audio.updateClips\", clips: [clip] },\n };\n }\n\n case \"audio.setMetadata\": {\n const { field, value } = command;\n if (typeof field !== \"string\" || !Object.hasOwn(EMPTY_METADATA, field)) {\n invalid(\"there's no such metadata field\");\n }\n if (typeof value !== \"string\" || value.length > MAX_METADATA_LENGTH) {\n invalid(`a metadata value must be text of at most ${MAX_METADATA_LENGTH} characters`);\n }\n return {\n state: { ...plan, metadata: { ...plan.metadata, [field]: value } },\n inverse: { type: \"audio.setMetadata\", field, value: plan.metadata[field] },\n };\n }\n\n default:\n return invalid(\"unknown command\");\n }\n}\n\n/**\n * Creates the clip plan's reducer (docs/adr/0003): it applies one command\n * without changing the plan, and returns the new plan with the command's\n * inverse. Sources are looked up through `sourceFrames`, so commands never\n * carry samples. An invalid command throws `AudioError` with\n * `INVALID_COMMAND` and changes nothing: the reducer never corrects one.\n *\n * @internal\n */\nexport function createPlanReducer(sourceFrames: SourceFrames): Reducer<AudioPlan, AudioCommand> {\n return (plan, command) => {\n try {\n return apply(plan, command, sourceFrames);\n } catch (error) {\n if (!(error instanceof Invalid)) throw error;\n const type =\n isRecord<AudioCommand>(command) && typeof command.type === \"string\" ? command.type : \"\";\n const known = type.startsWith(\"audio.\") && type.length <= 64;\n throw new AudioError(\n \"INVALID_COMMAND\",\n `Invalid ${known ? type : \"command\"}: ${error.message}.`,\n known ? { details: { command: type } } : {},\n );\n }\n };\n}\n","import { defineMessages, type MessageValue, plural, sdkCoreMessages } from \"@hussmartinez/sdk-core\";\nimport type { AudioErrorCode } from \"../core/errors/audio-error.js\";\nimport type { AudioLimitName } from \"../core/errors/audio-limits.js\";\n\n/**\n * The audio SDK's English message catalogue: sdk-core's messages, and text\n * for every {@link AudioErrorCode} and every limit's warning. Pass it to\n * `createMessages` from `@hussmartinez/sdk-core`, with the host's locale and\n * overrides. The editor's text joins it as the editor arrives.\n *\n * Error text is looked up by code, with the error's `details` as\n * parameters, and never taken from `error.message` (ADR 0019).\n *\n * @example\n * ```ts\n * const messages = createMessages(audioMessages, { locale: \"en\", overrides: props.messages });\n * messages.error(error); // \"This recording has 12 channels, which is over the 8-channel limit.\"\n * messages.t(\"warnings.maxSessionSize\", { actual: 800e6 });\n * ```\n *\n * @public\n */\nexport const audioMessages = /* @__PURE__ */ defineMessages({\n ...sdkCoreMessages,\n \"errors.INVALID_AUDIO\": \"This file isn't valid audio, or it's too damaged to open.\",\n \"errors.UNSUPPORTED_FORMAT\":\n \"This audio format isn't supported. Try converting the file to WAV, then open it again.\",\n \"errors.DECODE_FAILED\":\n \"This browser can't play this kind of audio. Try another browser, or convert the file to WAV.\",\n \"errors.INVALID_COMMAND\": \"This edit couldn't be made. Please try again.\",\n // TODO(sdk-core#59): state the length and the limit once messages have a\n // duration format. https://github.com/ie-huss-martinez/sdk-core/issues/59\n \"errors.DURATION_TOO_LONG\": \"This recording is longer than the editor can open.\",\n \"errors.TOO_MANY_CHANNELS\":\n \"This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.\",\n \"errors.SAMPLE_RATE_TOO_HIGH\":\n \"This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.\",\n \"errors.SESSION_TOO_LARGE\":\n \"The open recordings would use {actual, fileSize} of memory, which is over the {maximum, fileSize} limit. Remove a recording, or clear the undo history, and try again.\",\n \"errors.TOO_MANY_CLIPS\": /* @__PURE__ */ plural(\"maximum\", {\n one: \"A recording can have {maximum} clip. Join or delete clips, and try again.\",\n other: \"A recording can have up to {maximum} clips. Join or delete clips, and try again.\",\n }),\n \"warnings.maxDuration\": \"This recording is long, and may be slow to open and edit.\",\n \"warnings.maxChannels\": \"This recording has {actual, number} channels, and may be slow to edit.\",\n \"warnings.maxSampleRate\":\n \"This recording's sample rate is {actual, number} Hz, and it may be slow to edit.\",\n \"warnings.maxSessionSize\":\n \"The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.\",\n \"warnings.maxClips\": /* @__PURE__ */ plural(\"actual\", {\n one: \"This recording has {actual} clip. Many clips may be slow to play and export.\",\n other: \"This recording has {actual} clips. Many clips may be slow to play and export.\",\n }),\n}) satisfies Record<`errors.${AudioErrorCode}`, MessageValue> &\n Record<`warnings.${AudioLimitName}`, MessageValue>;\n\n/**\n * The type of {@link audioMessages}, for typing a host's overrides with\n * `MessageOverrides<AudioMessageCatalogue>`.\n *\n * @public\n */\nexport type AudioMessageCatalogue = typeof audioMessages;\n"],"mappings":";;AA8DA,IAAa,aAAb,cAAgC,SAAyB;CAEvD,OAAyB;AAC3B;AAcA,SAAgB,aACd,OACA,MAC+C;CAC/C,OAAO,WAAW,OAAO,IAAI,KAAK,MAAM,SAAS;AACnD;;ACzEA,SAAgB,aAAa,QAAiB,UAAU,4BAAwC;CAC9F,IAAI,kBAAkB,YACpB,OAAO;CAET,IAAI,WAAW,MAAM,GACnB,OAAO,IAAI,WAAW,OAAO,MAAe,OAAO,SAAS;EAC1D,GAAI,OAAO,YAAY,KAAA,IAAY,CAAC,IAAI,EAAE,SAAS,OAAO,QAAQ;EAClE,OAAO;CACT,CAAC;CAEH,OAAO,IAAI,WAAW,WAAW,SAAS,EAAE,OAAO,OAAO,CAAC;AAC7D;AAUA,SAAgB,WAAW,QAAiC;CAC1D,MAAM,EAAE,WAAW;CACnB,IAAI,kBAAkB,YACpB,OAAO;CAET,IAAI,WAAW,MAAM,GACnB,OAAO,aAAa,MAAM;CAE5B,MAAM,WAAW,kBAAkB,gBAAgB,OAAO,SAAS;CACnE,OAAO,IAAI,WACT,WAAW,YAAY,WACvB,WAAW,6BAA6B,gCACxC,EAAE,OAAO,OAAO,CAClB;AACF;AAOA,SAAgB,eAAe,QAAuC;CACpE,IAAI,QAAQ,SACV,MAAM,WAAW,MAAM;AAE3B;;ACn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