@hussmartinez/audio-sdk 0.5.0 → 0.7.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/dist/index.js CHANGED
@@ -1,1250 +1,28 @@
1
- import { SdkError, applyCommands, checkFile, coreLimits, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, locate, plural, resolveAssetsBase, sdkCoreMessages, sequenceOffsets, withProcessingTime } 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
- var { adapt: asAudioError, abortError, throwIfAborted } = /* @__PURE__ */ createErrorHelpers(AudioError, {
11
- fallbackCode: "UNKNOWN",
12
- fallbackMessage: "Audio processing failed."
13
- });
14
- // src/adapters/audio-worker/loader.ts
15
- function audioWorkerSource(assetsUrl) {
16
- const selfHosted = assetsUrl === void 0 ? void 0 : new URL("audio/audio.worker.js", resolveAssetsBase(assetsUrl)).href;
17
- return {
18
- loadWorker: selfHosted ? async () => () => new Worker(selfHosted, {
19
- type: "module",
20
- name: "hm-audio"
21
- }) : async () => (await import("./lazy/inline-worker-CR5UIkzK.js")).createInlineWorker,
22
- version: "0.5.0",
23
- ...selfHosted ? { asset: selfHosted } : {}
24
- };
25
- }
26
- var LEVEL_FACTOR = 4;
27
- function buildPyramid(finest, bucket = 256) {
28
- const levels = [];
29
- let current = finest;
30
- let framesPerBucket = bucket;
31
- for (;;) {
32
- levels.push({
33
- framesPerBucket,
34
- channels: current.min.map((min, c) => ({
35
- min,
36
- max: current.max[c]
37
- }))
38
- });
39
- if ((current.min[0]?.length ?? 0) <= 1) break;
40
- current = {
41
- min: current.min.map((values) => combine(values, Math.min)),
42
- max: current.max.map((values) => combine(values, Math.max))
43
- };
44
- framesPerBucket *= LEVEL_FACTOR;
45
- }
46
- return { levels };
47
- }
48
- function combine(values, pick) {
49
- const out = new Float32Array(Math.ceil(values.length / LEVEL_FACTOR));
50
- for (let i = 0; i < out.length; i += 1) {
51
- let value = values[i * LEVEL_FACTOR];
52
- const end = Math.min(values.length, (i + 1) * LEVEL_FACTOR);
53
- for (let j = i * LEVEL_FACTOR + 1; j < end; j += 1) value = pick(value, values[j]);
54
- out[i] = value;
55
- }
56
- return out;
57
- }
58
- // src/adapters/web-audio/platform-decode.ts
59
- var webAudioDecoder = (bytes, { sampleRate, channels }) => {
60
- const Offline = globalThis.OfflineAudioContext;
61
- if (typeof Offline !== "function") throw new AudioError("UNSUPPORTED_ENVIRONMENT", "Web Audio isn't available.", { details: { feature: "OfflineAudioContext" } });
62
- let context;
63
- try {
64
- context = new Offline({
65
- numberOfChannels: channels,
66
- length: 1,
67
- sampleRate
68
- });
69
- } catch (error) {
70
- throw new AudioError("UNSUPPORTED_FORMAT", "This browser can't decode at this rate.", {
71
- details: { sampleRate },
72
- cause: error
73
- });
74
- }
75
- return context.decodeAudioData(bytes);
76
- };
77
- function untilAborted(work, signal) {
78
- work.catch(() => {});
79
- if (!signal) return work;
80
- return new Promise((resolve, reject) => {
81
- const onAbort = () => reject(abortError(signal));
82
- if (signal.aborted) {
83
- onAbort();
84
- return;
85
- }
86
- signal.addEventListener("abort", onAbort, { once: true });
87
- work.then(resolve, reject).finally(() => signal.removeEventListener("abort", onAbort));
88
- });
89
- }
90
- async function decodeOnPage(file, probe, decoder, createBuffer, signal) {
91
- const { container, codec, sampleRate, channels, frameBound, frameTolerance } = probe;
92
- throwIfAborted(signal);
93
- const bytes = await untilAborted(file.arrayBuffer(), signal);
94
- let decoded;
95
- try {
96
- decoded = await untilAborted(Promise.resolve().then(() => decoder(bytes, {
97
- sampleRate,
98
- channels
99
- })), signal);
100
- } catch (error) {
101
- if (isAudioError(error)) throw error;
102
- throw new AudioError("DECODE_FAILED", "The browser couldn't decode this file.", {
103
- details: {
104
- container,
105
- codec
106
- },
107
- cause: error
108
- });
109
- }
110
- if (decoded.length === 0) throw new AudioError("DECODE_FAILED", "The browser decoded no audio from this file.", { details: {
111
- container,
112
- codec,
113
- reason: "no audio decoded"
114
- } });
115
- const invalid = (reason) => new AudioError("INVALID_AUDIO", `The decoded audio ${reason}.`, { details: {
116
- container,
117
- codec,
118
- reason: `decoded ${reason}`
119
- } });
120
- if (decoded.sampleRate !== sampleRate) throw invalid("rate differs from the probe");
121
- if (decoded.numberOfChannels > channels) throw invalid("channel count exceeds the probe");
122
- if (decoded.length > frameBound + frameTolerance) throw invalid("length exceeds the bound");
123
- if (decoded.length <= frameBound) return decoded;
124
- const capped = createBuffer({
125
- numberOfChannels: decoded.numberOfChannels,
126
- length: frameBound,
127
- sampleRate
128
- });
129
- for (let c = 0; c < decoded.numberOfChannels; c += 1) capped.copyToChannel(decoded.getChannelData(c).subarray(0, frameBound), c, 0);
130
- return capped;
131
- }
132
- // src/adapters/audio-engine.ts
133
- var BLOCK_FRAMES = 65536;
134
- function createAudioEngine(options = {}) {
135
- return createEngine({
136
- ...audioWorkerSource(options.assetsUrl),
137
- createBuffer: (bufferOptions) => new AudioBuffer(bufferOptions),
138
- decodePlatform: webAudioDecoder,
1
+ import { A as createAudioOutput, B as clipEnd, C as onlyFields, E as createAudioProcessor, F as MAX_TRACK_NAME_LENGTH, G as AudioError, H as planLength, I as MIN_GAIN_DB, K as isAudioError, L as NO_FADE, M as gainAt, N as EMPTY_METADATA, P as MAX_GAIN_DB, R as audibleTracks, S as longerThan, T as audioLimits, U as trackLength, V as clipLength, W as createAudioEngine, _ as MAX_METADATA_LENGTH, a as createAudioSession, b as isKey, c as formatTimecode, d as MAX_SOURCE_NAME_LENGTH, f as peakColumns, g as Invalid, h as refuse, i as watchPlayhead, j as dbToGain, k as mixLength, l as framesToSeconds, m as checkUniqueKeys, n as audioWarningText, p as checkTrack, r as audioMessages, s as connectOutput, t as audioErrorText, u as secondsToFrames, v as checkClipBody, w as audioLimitDefinitions, x as isRecord, y as invalid, z as clipAt } from "./shared/text-CgDrmmTa.js";
2
+ // src/adapters/audio-adapters.ts
3
+ function createAudioAdapters(options = {}) {
4
+ const worker = {
5
+ ...options.assetsUrl === void 0 ? {} : { assetsUrl: options.assetsUrl },
139
6
  ...options.idleTimeout === void 0 ? {} : { idleTimeout: options.idleTimeout }
140
- });
141
- }
142
- function createEngine(environment) {
143
- let startWorker;
144
- let destroyed = false;
145
- const layouts = /* @__PURE__ */ new WeakMap();
146
- const compressedProbes = /* @__PURE__ */ new WeakSet();
147
- const finestPeaks = /* @__PURE__ */ new WeakMap();
148
- const newClient = () => createWorkerClient({
149
- createWorker: () => {
150
- if (!startWorker) throw new AudioError("WORKER_START_FAILED", "The audio worker hasn't loaded.");
151
- return startWorker();
152
- },
153
- errorClasses: { AudioError },
154
- packageVersion: environment.version,
155
- ...environment.asset === void 0 ? {} : { workerAsset: environment.asset },
156
- ...environment.idleTimeout === void 0 ? {} : { idleTimeout: environment.idleTimeout }
157
- });
158
- let main;
159
- let analysis;
160
- async function ready() {
161
- if (destroyed) throw new Error("The audio engine has been destroyed.");
162
- startWorker ??= await environment.loadWorker();
163
- }
164
- async function run(work) {
165
- try {
166
- return await work();
167
- } catch (error) {
168
- throw error instanceof RangeError || error instanceof TypeError ? error : asAudioError(error);
169
- }
170
- }
171
- async function reprobe(file, probe, signal) {
172
- main ??= newClient();
173
- const fresh = await main.call("probe", { file }, signal ? { signal } : {});
174
- 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 } });
175
- return fresh.probe;
176
- }
177
- async function layoutOf(file, probe, signal) {
178
- const known = layouts.get(probe);
179
- if (known) return known;
180
- main ??= newClient();
181
- const fresh = await main.call("probe", { file }, signal ? { signal } : {});
182
- 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 } });
183
- if (!fresh.layout) throw new AudioError("UNSUPPORTED_FORMAT", "Compressed formats aren't supported yet.", { details: {
184
- container: probe.container,
185
- codec: probe.codec
186
- } });
187
- return fresh.layout;
188
- }
189
- return {
190
- probe(file, options = {}) {
191
- return run(async () => {
192
- throwIfAborted(options.signal);
193
- await ready();
194
- main ??= newClient();
195
- const result = await main.call("probe", { file }, options.signal ? { signal: options.signal } : {});
196
- if (result.layout) layouts.set(result.probe, result.layout);
197
- else compressedProbes.add(result.probe);
198
- return result.probe;
199
- });
200
- },
201
- decode(file, probe, options = {}) {
202
- return run(async () => {
203
- throwIfAborted(options.signal);
204
- await ready();
205
- if (probe.codec !== "pcm") {
206
- const audio = await decodeOnPage(file, compressedProbes.has(probe) ? probe : await reprobe(file, probe, options.signal), environment.decodePlatform, environment.createBuffer, options.signal);
207
- options.onProgress?.(1);
208
- return audio;
209
- }
210
- const layout = await layoutOf(file, probe, options.signal);
211
- const { frames, channels, sampleRate } = layout;
212
- let buffer;
213
- try {
214
- buffer = environment.createBuffer({
215
- numberOfChannels: channels,
216
- length: frames,
217
- sampleRate
218
- });
219
- } catch (error) {
220
- throw new AudioError("UNSUPPORTED_FORMAT", "This browser can't hold audio at this rate.", {
221
- details: {
222
- container: layout.container,
223
- sampleRate
224
- },
225
- cause: error
226
- });
227
- }
228
- const buckets = Math.ceil(frames / 256);
229
- const peaks = {
230
- min: Array.from({ length: channels }, () => new Float32Array(buckets)),
231
- max: Array.from({ length: channels }, () => new Float32Array(buckets))
232
- };
233
- main ??= newClient();
234
- for (let start = 0; start < frames; start += BLOCK_FRAMES) {
235
- const block = await main.call("readBlock", {
236
- file,
237
- layout,
238
- start,
239
- frames: Math.min(BLOCK_FRAMES, frames - start),
240
- bucket: 256
241
- }, options.signal ? { signal: options.signal } : {});
242
- const at = start / 256;
243
- for (let c = 0; c < channels; c += 1) {
244
- buffer.copyToChannel(block.channels[c], c, start);
245
- peaks.min[c]?.set(block.min[c], at);
246
- peaks.max[c]?.set(block.max[c], at);
247
- }
248
- options.onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);
249
- }
250
- if (frames === 0) options.onProgress?.(1);
251
- finestPeaks.set(buffer, peaks);
252
- return buffer;
253
- });
254
- },
255
- peaks(audio, options = {}) {
256
- return run(async () => {
257
- throwIfAborted(options.signal);
258
- const known = finestPeaks.get(audio);
259
- if (known) return buildPyramid(known, 256);
260
- await ready();
261
- analysis ??= newClient();
262
- const buckets = Math.ceil(audio.length / 256);
263
- const peaks = {
264
- min: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets)),
265
- max: Array.from({ length: audio.numberOfChannels }, () => new Float32Array(buckets))
266
- };
267
- for (let start = 0; start < audio.length; start += BLOCK_FRAMES) {
268
- const end = Math.min(audio.length, start + BLOCK_FRAMES);
269
- const channels = Array.from({ length: audio.numberOfChannels }, (_, c) => audio.getChannelData(c).slice(start, end));
270
- const block = await analysis.call("peaks", {
271
- channels,
272
- bucket: 256
273
- }, {
274
- transfer: true,
275
- ...options.signal ? { signal: options.signal } : {}
276
- });
277
- const at = start / 256;
278
- for (let c = 0; c < audio.numberOfChannels; c += 1) {
279
- peaks.min[c]?.set(block.min[c], at);
280
- peaks.max[c]?.set(block.max[c], at);
281
- }
282
- }
283
- finestPeaks.set(audio, peaks);
284
- return buildPyramid(peaks, 256);
285
- });
286
- },
287
- async destroy() {
288
- destroyed = true;
289
- main?.destroy();
290
- analysis?.destroy();
291
- }
292
7
  };
293
- }
294
- // src/core/model/plan.ts
295
- var EMPTY_METADATA = Object.freeze({
296
- title: "",
297
- artist: "",
298
- album: "",
299
- year: "",
300
- comment: ""
301
- });
302
- var NO_FADE = Object.freeze({
303
- frames: 0,
304
- curve: "linear"
305
- });
306
- function clipLength(clip) {
307
- return clip.end - clip.start;
308
- }
309
- function planLength(plan) {
310
- let total = 0;
311
- for (const clip of plan.clips) total += clipLength(clip);
312
- return total;
313
- }
314
- function clipOffsets(plan) {
315
- return clipBoundaries(plan).slice(0, -1);
316
- }
317
- function clipBoundaries(plan) {
318
- return sequenceOffsets(plan.clips.map(clipLength));
319
- }
320
- var MIN_GAIN_DB = -120;
321
- var MAX_GAIN_DB = 120;
322
- var isFrames = (value) => Number.isSafeInteger(value) && value >= 0;
323
- function clipProblem(clip, sourceFrames) {
324
- if (![
325
- clip.start,
326
- clip.end,
327
- clip.fadeIn.frames,
328
- clip.fadeOut.frames
329
- ].every(isFrames)) return "invalid-frames";
330
- if (clip.end <= clip.start) return "clip-too-short";
331
- if (clip.end > sourceFrames) return "clip-outside-source";
332
- if (typeof clip.gainDb !== "number" || !(clip.gainDb >= -120 && clip.gainDb <= 120)) return "gain-out-of-range";
333
- if (clip.fadeIn.frames + clip.fadeOut.frames > clipLength(clip)) return "fades-too-long";
334
- }
335
- function assertClip(clip, sourceFrames) {
336
- const problem = clipProblem(clip, sourceFrames);
337
- if (problem) throw new RangeError(`Clip ${clip.key} isn't valid: ${problem}.`);
338
- }
339
- // src/core/model/envelope.ts
340
- function dbToGain(db) {
341
- return 10 ** (db / 20);
342
- }
343
- function fadeShape(curve, position) {
344
- return curve === "equalPower" ? Math.sin(position * Math.PI / 2) : position;
345
- }
346
- function gainAt(clip, frame) {
347
- const length = clip.end - clip.start;
348
- let gain = dbToGain(clip.gainDb);
349
- const { fadeIn, fadeOut } = clip;
350
- if (fadeIn.frames > 0 && frame < fadeIn.frames) gain *= fadeShape(fadeIn.curve, frame / fadeIn.frames);
351
- const fromEnd = length - 1 - frame;
352
- if (fadeOut.frames > 0 && fromEnd < fadeOut.frames) gain *= fadeShape(fadeOut.curve, Math.max(0, fromEnd) / fadeOut.frames);
353
- return gain;
354
- }
355
- // src/adapters/web-audio/gain-automation.ts
356
- var MAX_CURVE_POINTS = 1024;
357
- function curve(clip, from, to) {
358
- const points = Math.min(MAX_CURVE_POINTS, to - from + 1);
359
- const values = new Float32Array(points);
360
- for (let i = 0; i < points; i += 1) {
361
- const frame = points === 1 ? from : from + (to - from) * i / (points - 1);
362
- values[i] = gainAt(clip, Math.round(frame));
363
- }
364
- return values;
365
- }
366
- function gainEvents(clip, from, sampleRate) {
367
- const length = clipLength(clip);
368
- const fadeInEnd = clip.fadeIn.frames;
369
- const fadeOutStart = length - clip.fadeOut.frames;
370
- const at = (frame) => (frame - from) / sampleRate;
371
- const events = [];
372
- let cursor = from;
373
- if (from < fadeInEnd) {
374
- events.push({
375
- kind: "curve",
376
- time: 0,
377
- duration: at(fadeInEnd),
378
- values: curve(clip, from, fadeInEnd)
379
- });
380
- cursor = fadeInEnd;
381
- }
382
- const outFrom = Math.max(cursor, fadeOutStart);
383
- const fadingOut = clip.fadeOut.frames > 0 && outFrom < length - 1;
384
- if (events.length === 0 && !(fadingOut && outFrom === from)) events.push({
385
- kind: "set",
386
- time: 0,
387
- value: gainAt(clip, from)
388
- });
389
- if (fadingOut) events.push({
390
- kind: "curve",
391
- time: at(outFrom),
392
- duration: at(length - 1) - at(outFrom),
393
- values: curve(clip, outFrom, length - 1)
394
- });
395
- else if (clip.fadeOut.frames > 0 && outFrom > cursor) events.push({
396
- kind: "set",
397
- time: at(outFrom),
398
- value: gainAt(clip, outFrom)
399
- });
400
- return events;
401
- }
402
- // src/adapters/web-audio/play-graph.ts
403
- function schedulePlan(context, destination, plan, buffer, from, at) {
404
- const rate = plan.sampleRate;
405
- const bus = context.createGain();
406
- bus.channelCount = plan.channels;
407
- bus.channelCountMode = "explicit";
408
- bus.channelInterpretation = "speakers";
409
- bus.connect(destination);
410
- const nodes = [];
411
- const offsets = clipOffsets(plan);
412
- const end = planLength(plan);
413
- for (const [index, clip] of plan.clips.entries()) {
414
- const offset = offsets[index];
415
- const length = clipLength(clip);
416
- if (offset + length <= from || offset >= end) continue;
417
- const within = Math.max(0, from - offset);
418
- const when = at + Math.max(0, offset - from) / rate;
419
- const source = context.createBufferSource();
420
- source.buffer = buffer(clip.source);
421
- const gain = context.createGain();
422
- for (const event of gainEvents(clip, within, rate)) if (event.kind === "set") gain.gain.setValueAtTime(event.value, when + event.time);
423
- else gain.gain.setValueCurveAtTime(event.values, when + event.time, event.duration);
424
- source.connect(gain).connect(bus);
425
- source.start(when, (clip.start + within) / rate, (length - within) / rate);
426
- nodes.push({
427
- source,
428
- gain
429
- });
430
- }
431
- return { stop() {
432
- for (const { source, gain } of nodes) {
433
- try {
434
- source.stop();
435
- } catch {}
436
- source.disconnect();
437
- gain.disconnect();
438
- }
439
- bus.disconnect();
440
- } };
441
- }
442
- // src/adapters/audio-output.ts
443
- var START_LEAD = .03;
444
- var RESUME_TIMEOUT = 2e3;
445
- function createAudioOutput() {
446
- return createOutput({ createContext: () => new AudioContext() });
447
- }
448
- function createOutput(environment) {
449
- const store = createStore(Object.freeze({ state: "stopped" }));
450
- const copies = /* @__PURE__ */ new WeakMap();
451
- let context;
452
- let plan;
453
- let sources = /* @__PURE__ */ new Map();
454
- let playhead = 0;
455
- let playing;
456
- let endTimer;
457
- let destroyed = false;
458
- const length = () => plan ? planLength(plan) : 0;
459
- const assertAlive = () => {
460
- if (destroyed) throw new Error("The audio output has been destroyed.");
461
- };
462
- const setState = (state) => {
463
- if (store.getSnapshot().state !== state) store.set(Object.freeze({ state }));
464
- };
465
- function buffer(id) {
466
- const audio = sources.get(id);
467
- if (!audio) throw new TypeError(`The plan's source ${id} isn't loaded.`);
468
- if (audio instanceof AudioBuffer) return audio;
469
- let copy = copies.get(audio);
470
- if (!copy) {
471
- copy = new AudioBuffer({
472
- length: audio.length,
473
- numberOfChannels: audio.numberOfChannels,
474
- sampleRate: audio.sampleRate
475
- });
476
- for (let channel = 0; channel < audio.numberOfChannels; channel += 1) copy.copyToChannel(Float32Array.from(audio.getChannelData(channel)), channel);
477
- copies.set(audio, copy);
478
- }
479
- return copy;
480
- }
481
- function position() {
482
- if (!playing || !context || !plan) return playhead;
483
- const elapsed = Math.max(0, context.currentTime - playing.time);
484
- return Math.min(length(), Math.floor(playing.frame + elapsed * plan.sampleRate));
485
- }
486
- function unschedule() {
487
- if (!playing) return;
488
- playhead = position();
489
- playing.scheduled.stop();
490
- playing = void 0;
491
- clearTimeout(endTimer);
492
- endTimer = void 0;
493
- }
494
- function watchEnd() {
495
- clearTimeout(endTimer);
496
- if (!playing || !context || !plan) return;
497
- const remaining = playing.time - context.currentTime + (length() - playing.frame) / plan.sampleRate;
498
- endTimer = setTimeout(() => {
499
- if (position() >= length()) {
500
- unschedule();
501
- playhead = length();
502
- setState("stopped");
503
- } else watchEnd();
504
- }, Math.max(0, remaining * 1e3) + 5);
505
- }
506
- function schedule() {
507
- if (!context || !plan) return;
508
- const time = context.currentTime + START_LEAD;
509
- playing = {
510
- scheduled: schedulePlan(context, context.destination, plan, buffer, playhead, time),
511
- frame: playhead,
512
- time
513
- };
514
- watchEnd();
515
- }
516
- async function running(audio) {
517
- if (audio.state === "running") return true;
518
- let timer;
519
- const timedOut = new Promise((resolve) => {
520
- timer = setTimeout(() => resolve(false), RESUME_TIMEOUT);
521
- });
522
- try {
523
- await Promise.race([audio.resume().then(() => true), timedOut]);
524
- } finally {
525
- clearTimeout(timer);
526
- }
527
- return audio.state === "running";
528
- }
8
+ const engine = createAudioEngine(worker);
9
+ const processor = createAudioProcessor(worker);
10
+ const output = createAudioOutput();
529
11
  return {
530
- getSnapshot: store.getSnapshot,
531
- subscribe: store.subscribe,
532
- position,
533
- load(next, nextSources) {
534
- assertAlive();
535
- const wasPlaying = playing !== void 0;
536
- unschedule();
537
- plan = next;
538
- sources = nextSources;
539
- playhead = Math.min(playhead, length());
540
- if (!wasPlaying) return;
541
- if (playhead >= length()) {
542
- playhead = length();
543
- setState("stopped");
544
- } else schedule();
545
- },
546
- async play() {
547
- assertAlive();
548
- if (length() === 0 || playing) return;
549
- context ??= environment.createContext();
550
- if (!await running(context)) throw new AudioError("UNSUPPORTED_ENVIRONMENT", "The browser didn't start audio output. Play from a click or a key press.", { details: { feature: "audio-output" } });
551
- if (destroyed || playing || length() === 0) return;
552
- if (playhead >= length()) playhead = 0;
553
- schedule();
554
- setState("playing");
555
- },
556
- pause() {
557
- assertAlive();
558
- if (!playing) return;
559
- unschedule();
560
- setState("paused");
561
- },
562
- stop() {
563
- assertAlive();
564
- unschedule();
565
- playhead = 0;
566
- setState("stopped");
567
- },
568
- seek(frame) {
569
- assertAlive();
570
- const wasPlaying = playing !== void 0;
571
- unschedule();
572
- playhead = Math.max(0, Math.min(Math.round(frame), length()));
573
- if (wasPlaying && playhead < length()) schedule();
574
- else if (wasPlaying) setState("stopped");
575
- },
12
+ engine,
13
+ processor,
14
+ output,
576
15
  async destroy() {
577
- if (destroyed) return;
578
- destroyed = true;
579
- unschedule();
580
- setState("stopped");
581
- await context?.close().catch(() => {});
582
- context = void 0;
16
+ await Promise.all([
17
+ engine.destroy(),
18
+ processor.destroy(),
19
+ output.destroy()
20
+ ]);
583
21
  }
584
22
  };
585
23
  }
586
- // src/adapters/wav/wav-writer.ts
587
- var BYTES = {
588
- pcm16: 2,
589
- pcm24: 3,
590
- float32: 4
591
- };
592
- function dataSize(spec) {
593
- return spec.frames * spec.channels * BYTES[spec.sampleFormat];
594
- }
595
- // src/adapters/audio-processor.ts
596
- var EXPORT_BLOCK_FRAMES = 65536;
597
- var SAMPLE_FORMATS = /* @__PURE__ */ new Set([
598
- "pcm16",
599
- "pcm24",
600
- "float32"
601
- ]);
602
- function createAudioProcessor(options = {}) {
603
- return createProcessor({
604
- ...audioWorkerSource(options.assetsUrl),
605
- ...options.idleTimeout === void 0 ? {} : { idleTimeout: options.idleTimeout }
606
- });
607
- }
608
- function check(job) {
609
- const { plan, sources, format } = job;
610
- if (format.container !== "wav") throw new TypeError(`Can't export to ${String(format.container)}.`);
611
- const sampleFormat = format.sampleFormat ?? "pcm16";
612
- if (!SAMPLE_FORMATS.has(sampleFormat)) throw new TypeError(`Unknown sample format ${String(sampleFormat)}.`);
613
- if (!Number.isSafeInteger(plan.sampleRate) || plan.sampleRate < 1) throw new RangeError("The plan's sample rate must be a whole number above 0.");
614
- if (!Number.isSafeInteger(plan.channels) || plan.channels < 1) throw new RangeError("The plan's channel count must be a whole number above 0.");
615
- for (const clip of plan.clips) {
616
- const source = sources.get(clip.source);
617
- if (!source) throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't in the job.`);
618
- assertClip(clip, source.length);
619
- }
620
- return sampleFormat;
621
- }
622
- function createProcessor(environment) {
623
- let startWorker;
624
- let client;
625
- let destroyed = false;
626
- async function ready() {
627
- if (destroyed) throw new Error("The audio processor has been destroyed.");
628
- startWorker ??= await environment.loadWorker();
629
- client ??= createWorkerClient({
630
- createWorker: () => {
631
- if (!startWorker) throw new AudioError("WORKER_START_FAILED", "The audio worker hasn't loaded.");
632
- return startWorker();
633
- },
634
- errorClasses: { AudioError },
635
- packageVersion: environment.version,
636
- ...environment.asset === void 0 ? {} : { workerAsset: environment.asset },
637
- ...environment.idleTimeout === void 0 ? {} : { idleTimeout: environment.idleTimeout }
638
- });
639
- return client;
640
- }
641
- async function render(job, signal, onProgress) {
642
- const { plan, sources } = job;
643
- const sampleFormat = check(job);
644
- throwIfAborted(signal);
645
- const worker = await ready();
646
- const call = signal ? { signal } : {};
647
- const frames = planLength(plan);
648
- const spec = {
649
- sampleRate: plan.sampleRate,
650
- channels: plan.channels,
651
- frames,
652
- sampleFormat
653
- };
654
- const parts = [await worker.call("wavHeader", {
655
- ...spec,
656
- metadata: { ...plan.metadata }
657
- }, call)];
658
- const offsets = clipOffsets(plan);
659
- let first = 0;
660
- for (let start = 0; start < frames; start += EXPORT_BLOCK_FRAMES) {
661
- throwIfAborted(signal);
662
- const length = Math.min(EXPORT_BLOCK_FRAMES, frames - start);
663
- const end = start + length;
664
- const segments = [];
665
- while (first < plan.clips.length) {
666
- const clip = plan.clips[first];
667
- if (!clip || offsets[first] + clipLength(clip) > start) break;
668
- first += 1;
669
- }
670
- for (let index = first; index < plan.clips.length; index += 1) {
671
- const clip = plan.clips[index];
672
- const offset = offsets[index];
673
- if (!clip || offset >= end) break;
674
- const from = Math.max(start, offset);
675
- const to = Math.min(end, offset + clipLength(clip));
676
- const within = from - offset;
677
- const source = sources.get(clip.source);
678
- if (!source) throw new TypeError(`Clip ${clip.key}'s source isn't in the job.`);
679
- const samples = Array.from({ length: source.numberOfChannels }, (_, channel) => source.getChannelData(channel).slice(clip.start + within, clip.start + within + (to - from)));
680
- segments.push({
681
- clip,
682
- within,
683
- at: from - start,
684
- samples,
685
- frames: to - from
686
- });
687
- }
688
- parts.push(await worker.call("renderBlock", {
689
- channels: plan.channels,
690
- frames: length,
691
- sampleFormat,
692
- segments
693
- }, call));
694
- onProgress?.(end / frames);
695
- }
696
- if (dataSize(spec) % 2 === 1) parts.push(/* @__PURE__ */ new Uint8Array(1));
697
- if (frames === 0) onProgress?.(1);
698
- return new Blob(parts, { type: "audio/wav" });
699
- }
700
- return {
701
- async render(job, options = {}) {
702
- try {
703
- return await render(job, options.signal, options.onProgress);
704
- } catch (error) {
705
- if (error instanceof TypeError || error instanceof RangeError) throw error;
706
- throw asAudioError(error, "The recording couldn't be exported.");
707
- }
708
- },
709
- async destroy() {
710
- destroyed = true;
711
- client?.destroy();
712
- }
713
- };
714
- }
715
- // src/core/errors/audio-limits.ts
716
- var audioLimitDefinitions = {
717
- ...coreLimits,
718
- maxFileSize: {
719
- ...coreLimits.maxFileSize,
720
- default: 1e9,
721
- warning: 25e7
722
- },
723
- maxDecodedSize: {
724
- ...coreLimits.maxDecodedSize,
725
- default: 1e9,
726
- warning: 4e8
727
- },
728
- maxDuration: {
729
- code: "DURATION_TOO_LONG",
730
- unit: "milliseconds",
731
- default: 108e5,
732
- warning: 36e5
733
- },
734
- maxChannels: {
735
- code: "TOO_MANY_CHANNELS",
736
- unit: "count",
737
- default: 8
738
- },
739
- maxSampleRate: {
740
- code: "SAMPLE_RATE_TOO_HIGH",
741
- unit: "hertz",
742
- default: 192e3
743
- },
744
- maxSessionSize: {
745
- code: "SESSION_TOO_LARGE",
746
- unit: "bytes",
747
- default: 15e8,
748
- warning: 75e7
749
- },
750
- maxClips: {
751
- code: "TOO_MANY_CLIPS",
752
- unit: "count",
753
- default: 2e3
754
- }
755
- };
756
- var audioLimits = /* @__PURE__ */ defineLimits(audioLimitDefinitions, { errorClass: AudioError });
757
- // src/core/operations/commands.ts
758
- var MAX_METADATA_LENGTH = 1e3;
759
- function longerThan(text, max) {
760
- if (text.length <= max) return false;
761
- let count = 0;
762
- for (const _ of text) {
763
- count += 1;
764
- if (count > max) return true;
765
- }
766
- return false;
767
- }
768
- var CURVES = /* @__PURE__ */ new Set(["linear", "equalPower"]);
769
- var Invalid = class extends Error {
770
- reason;
771
- constructor(reason, message) {
772
- super(message);
773
- this.reason = reason;
774
- }
775
- };
776
- function invalid(reason, message) {
777
- throw new Invalid(reason, message);
778
- }
779
- function isRecord(value) {
780
- return typeof value === "object" && value !== null;
781
- }
782
- function isKey(value) {
783
- return typeof value === "string" && value.length > 0;
784
- }
785
- function isIndex(value, max) {
786
- return Number.isSafeInteger(value) && value >= 0 && value <= max;
787
- }
788
- function fade(value, name) {
789
- if (!isRecord(value)) invalid("malformed-command", `${name} isn't a fade`);
790
- onlyFields(value, FADE_FIELDS, name);
791
- if (typeof value.curve !== "string" || !CURVES.has(value.curve)) invalid("invalid-fade-curve", `${name}'s curve isn't linear or equalPower`);
792
- return {
793
- frames: value.frames,
794
- curve: value.curve
795
- };
796
- }
797
- var COMMAND_FIELDS = {
798
- "audio.insertClips": [
799
- "at",
800
- "clips",
801
- "splitKey"
802
- ],
803
- "audio.removeClips": ["keys"],
804
- "audio.restoreClips": ["entries"],
805
- "audio.replaceClips": [
806
- "index",
807
- "count",
808
- "clips"
809
- ],
810
- "audio.updateClips": ["clips"],
811
- "audio.deleteRange": [
812
- "start",
813
- "end",
814
- "newKey"
815
- ],
816
- "audio.trimClip": [
817
- "key",
818
- "start",
819
- "end"
820
- ],
821
- "audio.splitClip": [
822
- "key",
823
- "at",
824
- "newKey"
825
- ],
826
- "audio.moveClips": ["keys", "to"],
827
- "audio.reorderClips": ["order"],
828
- "audio.setGain": ["keys", "gainDb"],
829
- "audio.setFade": [
830
- "key",
831
- "edge",
832
- "frames",
833
- "curve"
834
- ],
835
- "audio.setMetadata": ["field", "value"]
836
- };
837
- var CLIP_FIELDS = [
838
- "key",
839
- "source",
840
- "start",
841
- "end",
842
- "gainDb",
843
- "fadeIn",
844
- "fadeOut"
845
- ];
846
- var FADE_FIELDS = ["frames", "curve"];
847
- var ENTRY_FIELDS = ["index", "clip"];
848
- function onlyFields(value, allowed, what) {
849
- for (const [field, content] of Object.entries(value)) if (content !== void 0 && !allowed.includes(field)) invalid("malformed-command", `${what} has no field ${field}`);
850
- }
851
- function optionalKey(value, name) {
852
- if (value !== void 0 && !isKey(value)) invalid("malformed-command", `${name} must be a non-empty string`);
853
- return value;
854
- }
855
- function checkClip(value, sourceFrames) {
856
- if (!isRecord(value) || !isKey(value.key) || !isKey(value.source)) invalid("malformed-command", "a clip needs a key and a source");
857
- onlyFields(value, CLIP_FIELDS, "a clip");
858
- const clip = {
859
- key: value.key,
860
- source: value.source,
861
- start: value.start,
862
- end: value.end,
863
- gainDb: value.gainDb,
864
- fadeIn: fade(value.fadeIn, "fadeIn"),
865
- fadeOut: fade(value.fadeOut, "fadeOut")
866
- };
867
- const frames = sourceFrames(clip.source);
868
- if (frames === void 0) invalid("unknown-source", `the session has no source ${clip.source}`);
869
- const problem = clipProblem(clip, frames);
870
- if (problem) invalid(problem, `clip ${clip.key} isn't valid within its source`);
871
- return clip;
872
- }
873
- function checkClips(values, sourceFrames) {
874
- if (!Array.isArray(values)) invalid("malformed-command", "clips must be a list");
875
- return values.map((value) => checkClip(value, sourceFrames));
876
- }
877
- function checkNewKeys(keys, existing) {
878
- const taken = new Set(existing);
879
- const seen = /* @__PURE__ */ new Set();
880
- for (const key of keys) {
881
- if (!isKey(key)) invalid("malformed-command", "a key must be a non-empty string");
882
- if (taken.has(key)) invalid("key-taken", `the key ${key} is taken`);
883
- if (seen.has(key)) invalid("duplicate-key", `the key ${key} appears twice`);
884
- seen.add(key);
885
- }
886
- }
887
- function positions(plan, keys) {
888
- if (!Array.isArray(keys)) invalid("malformed-command", "keys must be a list");
889
- if (keys.length === 0) invalid("no-clips", "it needs at least one clip");
890
- const wanted = new Set(keys);
891
- if (wanted.size !== keys.length) invalid("duplicate-key", "a clip appears twice");
892
- const found = [];
893
- plan.clips.forEach((clip, index) => {
894
- if (wanted.has(clip.key)) found.push(index);
895
- });
896
- if (found.length !== wanted.size) invalid("unknown-clip", "the plan doesn't have every clip");
897
- return found;
898
- }
899
- function position(plan, key) {
900
- return positions(plan, [key])[0];
901
- }
902
- function fitFades(clip) {
903
- const length = clipLength(clip);
904
- const total = clip.fadeIn.frames + clip.fadeOut.frames;
905
- if (total <= length || !(length > 0)) return clip;
906
- return {
907
- ...clip,
908
- fadeIn: {
909
- ...clip.fadeIn,
910
- frames: Math.floor(clip.fadeIn.frames * length / total)
911
- },
912
- fadeOut: {
913
- ...clip.fadeOut,
914
- frames: Math.floor(clip.fadeOut.frames * length / total)
915
- }
916
- };
917
- }
918
- function part(clip, from, to, key) {
919
- const length = clipLength(clip);
920
- return fitFades({
921
- ...clip,
922
- key,
923
- start: clip.start + from,
924
- end: clip.start + to,
925
- fadeIn: from === 0 ? clip.fadeIn : NO_FADE,
926
- fadeOut: to === length ? clip.fadeOut : NO_FADE
927
- });
928
- }
929
- function locate$1(plan, frame) {
930
- if (!isIndex(frame, planLength(plan))) invalid("frame-outside-plan", "the frame is outside the plan");
931
- const found = locate(clipBoundaries(plan), frame);
932
- return found ? {
933
- index: found.index,
934
- offset: found.within
935
- } : {
936
- index: plan.clips.length,
937
- offset: 0
938
- };
939
- }
940
- function withClips(plan, clips) {
941
- return {
942
- ...plan,
943
- clips
944
- };
945
- }
946
- function splice(plan, index, count, clips) {
947
- return withClips(plan, [
948
- ...plan.clips.slice(0, index),
949
- ...clips,
950
- ...plan.clips.slice(index + count)
951
- ]);
952
- }
953
- function updateByKey(plan, clips) {
954
- const byKey = new Map(clips.map((clip) => [clip.key, clip]));
955
- return withClips(plan, plan.clips.map((clip) => byKey.get(clip.key) ?? clip));
956
- }
957
- function apply(plan, command, sourceFrames) {
958
- if (!isRecord(command)) invalid("malformed-command", "a command is an object");
959
- const fields = Object.hasOwn(COMMAND_FIELDS, command.type) ? COMMAND_FIELDS[command.type] : void 0;
960
- if (!fields) invalid("unknown-command", "unknown command");
961
- onlyFields(command, ["type", ...fields], command.type);
962
- switch (command.type) {
963
- case "audio.insertClips": {
964
- const clips = checkClips(command.clips, sourceFrames);
965
- if (clips.length === 0) invalid("no-clips", "it needs at least one clip");
966
- const keys = clips.map((clip) => clip.key);
967
- checkNewKeys(keys, plan.clips.map((clip) => clip.key));
968
- const splitKey = optionalKey(command.splitKey, "splitKey");
969
- const { index, offset } = locate$1(plan, command.at);
970
- if (offset === 0) return {
971
- state: splice(plan, index, 0, clips),
972
- inverse: {
973
- type: "audio.replaceClips",
974
- index,
975
- count: clips.length,
976
- clips: []
977
- }
978
- };
979
- if (splitKey === void 0) invalid("new-key-required", "inserting inside a clip needs a splitKey");
980
- checkNewKeys([splitKey], [...plan.clips.map((clip) => clip.key), ...keys]);
981
- const split = plan.clips[index];
982
- const parts = [
983
- part(split, 0, offset, split.key),
984
- ...clips,
985
- part(split, offset, clipLength(split), splitKey)
986
- ];
987
- return {
988
- state: splice(plan, index, 1, parts),
989
- inverse: {
990
- type: "audio.replaceClips",
991
- index,
992
- count: parts.length,
993
- clips: [split]
994
- }
995
- };
996
- }
997
- case "audio.removeClips": {
998
- const at = positions(plan, command.keys);
999
- const removed = new Set(at);
1000
- return {
1001
- state: withClips(plan, plan.clips.filter((_, index) => !removed.has(index))),
1002
- inverse: {
1003
- type: "audio.restoreClips",
1004
- entries: at.map((index) => ({
1005
- index,
1006
- clip: plan.clips[index]
1007
- }))
1008
- }
1009
- };
1010
- }
1011
- case "audio.restoreClips": {
1012
- if (!Array.isArray(command.entries)) invalid("malformed-command", "entries must be a list");
1013
- if (command.entries.length === 0) invalid("no-clips", "it needs at least one clip");
1014
- const entries = command.entries.map((entry) => {
1015
- if (!isRecord(entry)) invalid("malformed-command", "an entry needs an index and a clip");
1016
- onlyFields(entry, ENTRY_FIELDS, "an entry");
1017
- return {
1018
- index: entry.index,
1019
- clip: checkClip(entry.clip, sourceFrames)
1020
- };
1021
- });
1022
- checkNewKeys(entries.map(({ clip }) => clip.key), plan.clips.map((clip) => clip.key));
1023
- const clips = [...plan.clips];
1024
- let previous = -1;
1025
- for (const { index, clip } of entries) {
1026
- if (!isIndex(index, clips.length) || index <= previous) invalid("invalid-index", `clip ${clip.key} can't be restored at index ${String(index)}`);
1027
- clips.splice(index, 0, clip);
1028
- previous = index;
1029
- }
1030
- return {
1031
- state: withClips(plan, clips),
1032
- inverse: {
1033
- type: "audio.removeClips",
1034
- keys: entries.map(({ clip }) => clip.key)
1035
- }
1036
- };
1037
- }
1038
- case "audio.replaceClips": {
1039
- const { index, count } = command;
1040
- if (!isIndex(index, plan.clips.length) || !isIndex(count, plan.clips.length - index)) invalid("invalid-index", "the run of clips is outside the plan");
1041
- const clips = checkClips(command.clips, sourceFrames);
1042
- if (count === 0 && clips.length === 0) invalid("empty-change", "it changes nothing");
1043
- const removed = plan.clips.slice(index, index + count);
1044
- checkNewKeys(clips.map((clip) => clip.key), [...plan.clips.slice(0, index), ...plan.clips.slice(index + count)].map((clip) => clip.key));
1045
- return {
1046
- state: splice(plan, index, count, clips),
1047
- inverse: {
1048
- type: "audio.replaceClips",
1049
- index,
1050
- count: clips.length,
1051
- clips: removed
1052
- }
1053
- };
1054
- }
1055
- case "audio.updateClips": {
1056
- const clips = checkClips(command.clips, sourceFrames);
1057
- const at = positions(plan, clips.map((clip) => clip.key));
1058
- return {
1059
- state: updateByKey(plan, clips),
1060
- inverse: {
1061
- type: "audio.updateClips",
1062
- clips: at.map((index) => plan.clips[index])
1063
- }
1064
- };
1065
- }
1066
- case "audio.deleteRange": {
1067
- const { start, end } = command;
1068
- const newKey = optionalKey(command.newKey, "newKey");
1069
- if (!isIndex(start, planLength(plan)) || !isIndex(end, planLength(plan))) invalid("frame-outside-plan", "the range must be inside the plan");
1070
- if (end <= start) invalid("empty-range", "the range must be at least one frame long");
1071
- const first = locate$1(plan, start);
1072
- const last = locate$1(plan, end - 1);
1073
- const firstClip = plan.clips[first.index];
1074
- const lastClip = plan.clips[last.index];
1075
- const kept = [];
1076
- if (first.offset > 0) kept.push(part(firstClip, 0, first.offset, firstClip.key));
1077
- if (last.offset + 1 < clipLength(lastClip)) {
1078
- let key = lastClip.key;
1079
- if (first.index === last.index && first.offset > 0) {
1080
- if (newKey === void 0) invalid("new-key-required", "deleting inside a clip needs a newKey");
1081
- checkNewKeys([newKey], plan.clips.map((clip) => clip.key));
1082
- key = newKey;
1083
- }
1084
- kept.push(part(lastClip, last.offset + 1, clipLength(lastClip), key));
1085
- }
1086
- const count = last.index - first.index + 1;
1087
- return {
1088
- state: splice(plan, first.index, count, kept),
1089
- inverse: {
1090
- type: "audio.replaceClips",
1091
- index: first.index,
1092
- count: kept.length,
1093
- clips: plan.clips.slice(first.index, first.index + count)
1094
- }
1095
- };
1096
- }
1097
- case "audio.trimClip": {
1098
- const index = position(plan, command.key);
1099
- const clip = plan.clips[index];
1100
- return {
1101
- state: updateByKey(plan, [checkClip(fitFades({
1102
- ...clip,
1103
- start: command.start,
1104
- end: command.end
1105
- }), sourceFrames)]),
1106
- inverse: {
1107
- type: "audio.updateClips",
1108
- clips: [clip]
1109
- }
1110
- };
1111
- }
1112
- case "audio.splitClip": {
1113
- const index = position(plan, command.key);
1114
- const clip = plan.clips[index];
1115
- const { index: within, offset } = locate$1(plan, command.at);
1116
- if (within !== index || offset === 0) invalid("not-inside-clip", "the frame must be strictly inside the clip");
1117
- checkNewKeys([command.newKey], plan.clips.map((entry) => entry.key));
1118
- return {
1119
- state: splice(plan, index, 1, [part(clip, 0, offset, clip.key), part(clip, offset, clipLength(clip), command.newKey)]),
1120
- inverse: {
1121
- type: "audio.replaceClips",
1122
- index,
1123
- count: 2,
1124
- clips: [clip]
1125
- }
1126
- };
1127
- }
1128
- case "audio.moveClips": {
1129
- const moved = new Set(positions(plan, command.keys));
1130
- const block = plan.clips.filter((_, index) => moved.has(index));
1131
- const rest = plan.clips.filter((_, index) => !moved.has(index));
1132
- if (!isIndex(command.to, rest.length)) invalid("invalid-index", "the clips can't move there");
1133
- return {
1134
- state: withClips(plan, [
1135
- ...rest.slice(0, command.to),
1136
- ...block,
1137
- ...rest.slice(command.to)
1138
- ]),
1139
- inverse: {
1140
- type: "audio.reorderClips",
1141
- order: plan.clips.map((clip) => clip.key)
1142
- }
1143
- };
1144
- }
1145
- case "audio.reorderClips": {
1146
- const { order } = command;
1147
- const byKey = new Map(plan.clips.map((clip) => [clip.key, clip]));
1148
- if (!Array.isArray(order) || order.length !== plan.clips.length || new Set(order).size !== order.length || order.some((key) => !byKey.has(key))) invalid("invalid-order", "the order must list every clip exactly once");
1149
- return {
1150
- state: withClips(plan, order.map((key) => byKey.get(key))),
1151
- inverse: {
1152
- type: "audio.reorderClips",
1153
- order: plan.clips.map((clip) => clip.key)
1154
- }
1155
- };
1156
- }
1157
- case "audio.setGain": {
1158
- const at = positions(plan, command.keys);
1159
- const gainDb = command.gainDb;
1160
- if (typeof gainDb !== "number" || !(gainDb >= -120 && gainDb <= 120)) invalid("gain-out-of-range", `gain must be from ${MIN_GAIN_DB} to 120 dB`);
1161
- const before = at.map((index) => plan.clips[index]);
1162
- return {
1163
- state: updateByKey(plan, before.map((clip) => ({
1164
- ...clip,
1165
- gainDb
1166
- }))),
1167
- inverse: {
1168
- type: "audio.updateClips",
1169
- clips: before
1170
- }
1171
- };
1172
- }
1173
- case "audio.setFade": {
1174
- const clip = plan.clips[position(plan, command.key)];
1175
- const { edge, frames } = command;
1176
- if (edge !== "in" && edge !== "out") invalid("invalid-edge", "the edge must be in or out");
1177
- const next = {
1178
- frames,
1179
- curve: fade({
1180
- frames,
1181
- curve: command.curve
1182
- }, "the fade").curve
1183
- };
1184
- return {
1185
- state: updateByKey(plan, [checkClip(edge === "in" ? {
1186
- ...clip,
1187
- fadeIn: next
1188
- } : {
1189
- ...clip,
1190
- fadeOut: next
1191
- }, sourceFrames)]),
1192
- inverse: {
1193
- type: "audio.updateClips",
1194
- clips: [clip]
1195
- }
1196
- };
1197
- }
1198
- case "audio.setMetadata": {
1199
- const { field, value } = command;
1200
- if (typeof field !== "string" || !Object.hasOwn(EMPTY_METADATA, field)) invalid("unknown-metadata-field", "there's no such metadata field");
1201
- if (typeof value !== "string") invalid("malformed-command", "a metadata value must be text");
1202
- if (longerThan(value, 1e3)) invalid("metadata-too-long", `a metadata value can have at most ${MAX_METADATA_LENGTH} code points`);
1203
- return {
1204
- state: {
1205
- ...plan,
1206
- metadata: {
1207
- ...plan.metadata,
1208
- [field]: value
1209
- }
1210
- },
1211
- inverse: {
1212
- type: "audio.setMetadata",
1213
- field,
1214
- value: plan.metadata[field]
1215
- }
1216
- };
1217
- }
1218
- default: return invalid("unknown-command", "unknown command");
1219
- }
1220
- }
1221
- function createPlanReducer(sourceFrames) {
1222
- return (plan, command) => {
1223
- try {
1224
- return apply(plan, command, sourceFrames);
1225
- } catch (error) {
1226
- if (!(error instanceof Invalid)) throw error;
1227
- const type = isRecord(command) && typeof command.type === "string" ? command.type : "";
1228
- const known = type.startsWith("audio.") && type.length <= 64;
1229
- throw new AudioError("INVALID_COMMAND", `Invalid ${known ? type : "command"}: ${error.message}.`, { details: known ? {
1230
- command: type,
1231
- reason: error.reason
1232
- } : { reason: error.reason } });
1233
- }
1234
- };
1235
- }
1236
- // src/core/format/plan-document.ts
24
+ // src/core/format/document-parts.ts
1237
25
  var AUDIO_PLAN_FORMAT = "hm-audio-plan";
1238
- var AUDIO_PLAN_VERSION = 1;
1239
- var DOCUMENT_FIELDS = [
1240
- "format",
1241
- "version",
1242
- "sampleRate",
1243
- "channels",
1244
- "sources",
1245
- "clips",
1246
- "metadata"
1247
- ];
1248
26
  var SOURCE_FIELDS = ["frames", "asset"];
1249
27
  var ASSET_FIELDS = [
1250
28
  "asset",
@@ -1301,7 +79,17 @@ function readMetadata(value) {
1301
79
  });
1302
80
  return Object.fromEntries(fields);
1303
81
  }
1304
- function read(value) {
82
+ // src/core/format/version-1.ts
83
+ var DOCUMENT_FIELDS$1 = [
84
+ "format",
85
+ "version",
86
+ "sampleRate",
87
+ "channels",
88
+ "sources",
89
+ "clips",
90
+ "metadata"
91
+ ];
92
+ function readVersion1(value) {
1305
93
  if (!isRecord(value) || Array.isArray(value)) malformed("a document is an object");
1306
94
  const { format, version } = value;
1307
95
  if (typeof format !== "string") malformed("format is text");
@@ -1314,13 +102,13 @@ function read(value) {
1314
102
  reason: "unknown-format-version"
1315
103
  } });
1316
104
  if (version !== 1) malformed("version is 1");
1317
- onlyFields(value, DOCUMENT_FIELDS, "a document");
105
+ onlyFields(value, DOCUMENT_FIELDS$1, "a document");
1318
106
  if (!isCount(value.sampleRate, 1)) malformed("sampleRate is a whole number above 0");
1319
107
  if (!isCount(value.channels, 1)) malformed("channels is a whole number above 0");
1320
108
  const sources = readSources(value.sources);
1321
109
  if (!Array.isArray(value.clips)) malformed("clips is a list");
1322
110
  const lookup = (id) => Object.hasOwn(sources, id) ? sources[id]?.frames : void 0;
1323
- const clips = value.clips.map((clip) => checkClip(clip, lookup));
111
+ const clips = value.clips.map((clip) => checkClipBody(clip, lookup));
1324
112
  const keys = /* @__PURE__ */ new Set();
1325
113
  for (const { key } of clips) {
1326
114
  if (keys.has(key)) invalid("duplicate-key", `two clips have the key ${key}`);
@@ -1336,9 +124,9 @@ function read(value) {
1336
124
  sources
1337
125
  };
1338
126
  }
1339
- function readAudioPlanDocument(value) {
127
+ function readPlanDocumentV1(value) {
1340
128
  try {
1341
- return read(value);
129
+ return readVersion1(value);
1342
130
  } catch (error) {
1343
131
  if (!(error instanceof Invalid)) throw error;
1344
132
  const reason = error.reason === "malformed-command" ? "malformed-document" : error.reason;
@@ -1348,562 +136,313 @@ function readAudioPlanDocument(value) {
1348
136
  } });
1349
137
  }
1350
138
  }
1351
- function toAudioPlanDocument(plan, sources) {
1352
- for (const clip of plan.clips) if (!Object.hasOwn(sources, clip.source)) throw new TypeError(`The sources don't include ${clip.source}, which clip ${clip.key} uses.`);
139
+ function trackKeyFor(clips) {
140
+ const taken = new Set(clips.map((clip) => clip.key));
141
+ let number = 1;
142
+ while (taken.has(`t${number}`)) number += 1;
143
+ return `t${number}`;
144
+ }
145
+ function migratePlan(plan) {
146
+ let at = 0;
147
+ const clips = plan.clips.map((clip) => {
148
+ const placed = {
149
+ key: clip.key,
150
+ at,
151
+ source: clip.source,
152
+ start: clip.start,
153
+ end: clip.end,
154
+ gainDb: clip.gainDb,
155
+ fadeIn: clip.fadeIn,
156
+ fadeOut: clip.fadeOut
157
+ };
158
+ at += clip.end - clip.start;
159
+ return placed;
160
+ });
1353
161
  return {
1354
- format: AUDIO_PLAN_FORMAT,
1355
- version: 1,
1356
162
  sampleRate: plan.sampleRate,
1357
163
  channels: plan.channels,
1358
- sources: Object.fromEntries(Object.entries(sources).map(([id, { frames, asset }]) => [id, asset === void 0 ? { frames } : {
1359
- frames,
1360
- asset: { ...asset }
1361
- }])),
1362
- clips: plan.clips.map(({ key, source, start, end, gainDb, fadeIn, fadeOut }) => ({
1363
- key,
1364
- source,
1365
- start,
1366
- end,
1367
- gainDb,
1368
- fadeIn: {
1369
- frames: fadeIn.frames,
1370
- curve: fadeIn.curve
1371
- },
1372
- fadeOut: {
1373
- frames: fadeOut.frames,
1374
- curve: fadeOut.curve
1375
- }
1376
- })),
1377
- metadata: { ...plan.metadata }
164
+ gainDb: 0,
165
+ tracks: [{
166
+ key: trackKeyFor(plan.clips),
167
+ name: "",
168
+ gainDb: 0,
169
+ muted: false,
170
+ soloed: false,
171
+ clips
172
+ }],
173
+ metadata: plan.metadata
1378
174
  };
1379
175
  }
1380
- // src/core/model/time.ts
1381
- function framesToSeconds(frames, sampleRate) {
1382
- return frames / sampleRate;
1383
- }
1384
- function secondsToFrames(seconds, sampleRate) {
1385
- return Math.round(seconds * sampleRate);
1386
- }
1387
- // src/core/session/connect-output.ts
1388
- function connectOutput(session, output) {
1389
- let plan;
1390
- let held = /* @__PURE__ */ new Set();
1391
- function sync() {
1392
- const snapshot = session.getSnapshot();
1393
- const next = snapshot.plan;
1394
- const ids = new Set(snapshot.sources.map((source) => source.id));
1395
- if (next === plan) {
1396
- held = ids;
1397
- return;
1398
- }
1399
- if ((next === void 0 || plan !== void 0 && !next.clips.some((clip) => held.has(clip.source))) && plan !== void 0) output.stop();
1400
- plan = next;
1401
- held = ids;
1402
- if (!next) return;
1403
- const sources = /* @__PURE__ */ new Map();
1404
- for (const { source } of next.clips) {
1405
- const audio = session.getAudio(source);
1406
- if (audio) sources.set(source, audio);
1407
- }
1408
- output.load(next, sources);
1409
- }
1410
- sync();
1411
- return session.subscribe(sync);
1412
- }
1413
- // src/core/session/session.ts
1414
- var BYTES_PER_SAMPLE = 4;
1415
- function clipsOf(command) {
1416
- switch (command.type) {
1417
- case "audio.insertClips":
1418
- case "audio.replaceClips":
1419
- case "audio.updateClips": return command.clips;
1420
- case "audio.restoreClips": return command.entries.map((entry) => entry.clip);
1421
- default: return [];
1422
- }
1423
- }
1424
- function coarseSeconds(seconds) {
1425
- return seconds > 0 ? Number(seconds.toPrecision(2)) : 0;
1426
- }
1427
- function keysOf(command) {
1428
- const keys = clipsOf(command).map((clip) => clip.key);
1429
- if ("newKey" in command && typeof command.newKey === "string") keys.push(command.newKey);
1430
- if ("splitKey" in command && typeof command.splitKey === "string") keys.push(command.splitKey);
1431
- return keys;
1432
- }
1433
- function createAudioSession(options) {
1434
- const { engine } = options;
1435
- const policy = audioLimits.resolve(options.filePolicy);
1436
- const history = createHistory();
1437
- const sources = /* @__PURE__ */ new Map();
1438
- const reducer = createPlanReducer((id) => sources.get(id)?.info.frames);
1439
- let plan;
1440
- let status = "empty";
1441
- let error;
1442
- let busy = 0;
1443
- let selection;
1444
- let nextKey = 0;
1445
- let nextSource = 0;
1446
- const loading = /* @__PURE__ */ new Set();
1447
- const cancelLoads = (message) => {
1448
- for (const controller of loading) controller.abort(new AudioError("ABORTED", message));
1449
- };
1450
- let generation = 0;
1451
- const superseded = (since) => since !== generation ? new AudioError("ABORTED", "The recording was closed or replaced.") : void 0;
1452
- const heldBytes = () => {
1453
- let total = 0;
1454
- for (const source of sources.values()) total += source.bytes;
1455
- return total;
176
+ var isWhole = (value) => Number.isSafeInteger(value) && value >= 0;
177
+ function migrateAudioCommand(command, plan) {
178
+ try {
179
+ return migrate(command, plan);
180
+ } catch (error) {
181
+ if (!(error instanceof Invalid)) throw error;
182
+ throw new AudioError("INVALID_COMMAND", `Invalid command: ${error.message}.`, { details: { reason: error.reason } });
183
+ }
184
+ }
185
+ function migrate(value, plan) {
186
+ if (!isRecord(value)) refuse("malformed-command", "a command is an object");
187
+ const track = plan.tracks[0];
188
+ const tracks = [track.key];
189
+ const command = value;
190
+ const ripple = (start, end, newKey) => ({
191
+ type: "audio.deleteRange",
192
+ start,
193
+ end,
194
+ tracks,
195
+ ripple: true,
196
+ ...newKey === void 0 ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }
197
+ });
198
+ const open = (at, frames, newKey) => ({
199
+ type: "audio.insertTime",
200
+ at,
201
+ frames,
202
+ tracks,
203
+ ...newKey === void 0 ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }
204
+ });
205
+ const find = (keys) => {
206
+ if (!Array.isArray(keys)) refuse("malformed-command", "keys must be a list");
207
+ if (keys.length === 0) refuse("no-clips", "it needs at least one clip");
208
+ if (new Set(keys).size !== keys.length) refuse("duplicate-key", "a clip appears twice");
209
+ const found = track.clips.filter((clip) => keys.includes(clip.key));
210
+ if (found.length !== keys.length) refuse("unknown-clip", "the plan doesn't have every clip");
211
+ return found;
1456
212
  };
1457
- function referenced(steps) {
1458
- const ids = new Set(plan?.clips.map((clip) => clip.source));
1459
- for (const { commands, inverses } of steps) for (const command of [...commands, ...inverses]) for (const clip of clipsOf(command)) ids.add(clip.source);
1460
- return ids;
1461
- }
1462
- function collect() {
1463
- const keep = referenced(history.steps);
1464
- for (const id of sources.keys()) if (!keep.has(id)) sources.delete(id);
1465
- }
1466
- function stepsToDrop(extra) {
1467
- const { maximum } = policy.limits.maxSessionSize;
1468
- const order = history.dropOrder;
1469
- for (let count = 0; count <= order.length; count += 1) {
1470
- const kept = new Set(order.slice(count));
1471
- const ids = referenced(history.steps.filter((entry) => kept.has(entry)));
1472
- let total = extra;
1473
- for (const id of ids) total += sources.get(id)?.bytes ?? 0;
1474
- if (total <= maximum) return count;
213
+ const lengthOf = (clip) => clip.end - clip.start;
214
+ switch (command.type) {
215
+ case "audio.insertClips": {
216
+ const { at, clips, splitKey } = command;
217
+ onlyFields(command, [
218
+ "type",
219
+ "at",
220
+ "clips",
221
+ "splitKey"
222
+ ], command.type);
223
+ if (splitKey !== void 0 && !isKey(splitKey)) refuse("malformed-command", "splitKey must be a non-empty string");
224
+ if (!Array.isArray(clips)) refuse("malformed-command", "clips must be a list");
225
+ if (clips.length === 0) refuse("no-clips", "it needs at least one clip");
226
+ let next = isWhole(at) ? at : 0;
227
+ let total = 0;
228
+ const placed = clips.map((clip) => {
229
+ const length = isRecord(clip) && isWhole(clip.start) && isWhole(clip.end) ? Math.max(0, clip.end - clip.start) : 0;
230
+ const positioned = {
231
+ ...clip,
232
+ at: next
233
+ };
234
+ next += length;
235
+ total += length;
236
+ return positioned;
237
+ });
238
+ const insert = {
239
+ type: "audio.insertClips",
240
+ track: track.key,
241
+ clips: placed
242
+ };
243
+ return total > 0 ? [open(at, total, splitKey), insert] : [insert];
1475
244
  }
1476
- }
1477
- function sessionWarnings() {
1478
- const found = [...sources.values()].flatMap((source) => source.warnings);
1479
- const bytes = heldBytes();
1480
- if (bytes > 0 && bytes >= policy.limits.maxSessionSize.warning) found.push({
1481
- type: "limit",
1482
- limit: "maxSessionSize",
1483
- actual: bytes
1484
- });
1485
- const clips = plan?.clips.length ?? 0;
1486
- if (clips > 0 && clips >= policy.limits.maxClips.warning) found.push({
1487
- type: "limit",
1488
- limit: "maxClips",
1489
- actual: clips
1490
- });
1491
- return found;
1492
- }
1493
- function makeSnapshot() {
1494
- return Object.freeze({
1495
- status,
1496
- plan,
1497
- sources: Object.freeze([...sources.values()].map((source) => source.info)),
1498
- canUndo: history.canUndo,
1499
- canRedo: history.canRedo,
1500
- historyTrimmed: history.trimmed,
1501
- busy: busy > 0,
1502
- error,
1503
- warnings: Object.freeze(sessionWarnings()),
1504
- sessionBytes: heldBytes(),
1505
- selection
1506
- });
1507
- }
1508
- const store = createStore(makeSnapshot());
1509
- function changed() {
1510
- if (selection) {
1511
- const end = Math.min(selection.end, plan ? planLength(plan) : 0);
1512
- selection = selection.start < end ? {
1513
- start: selection.start,
245
+ case "audio.removeClips":
246
+ onlyFields(command, ["type", "keys"], command.type);
247
+ return find(command.keys).reverse().map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));
248
+ case "audio.deleteRange":
249
+ onlyFields(command, [
250
+ "type",
251
+ "start",
252
+ "end",
253
+ "newKey"
254
+ ], command.type);
255
+ return [ripple(command.start, command.end, command.newKey)];
256
+ case "audio.trimClip": {
257
+ onlyFields(command, [
258
+ "type",
259
+ "key",
260
+ "start",
261
+ "end"
262
+ ], command.type);
263
+ const { key, start, end } = command;
264
+ const trim = {
265
+ type: "audio.trimClip",
266
+ key,
267
+ start,
1514
268
  end
1515
- } : void 0;
269
+ };
270
+ const clip = track.clips.find((entry) => entry.key === key);
271
+ if (!clip || !isWhole(start) || !isWhole(end) || end <= start) return [trim];
272
+ const earlier = clip.start - start;
273
+ const later = end - clip.end;
274
+ const length = end - start;
275
+ const last = track.clips.at(-1) === clip;
276
+ const before = [];
277
+ const after = [];
278
+ if (earlier > 0) before.push(open(clip.at, earlier));
279
+ if (later > 0 && !last) before.push(open(clip.at + Math.max(earlier, 0) + lengthOf(clip), later));
280
+ if (earlier < 0) after.push(ripple(clip.at, clip.at - earlier));
281
+ if (later < 0 && !last) after.push(ripple(clip.at + length, clip.at + length - later));
282
+ return [
283
+ ...before,
284
+ trim,
285
+ ...after
286
+ ];
1516
287
  }
1517
- store.set(makeSnapshot());
1518
- }
1519
- function emit(event) {
1520
- try {
1521
- options.onEvent?.(event);
1522
- } catch {}
288
+ case "audio.splitClip": {
289
+ onlyFields(command, [
290
+ "type",
291
+ "key",
292
+ "at",
293
+ "newKey"
294
+ ], command.type);
295
+ const { key, at, newKey } = command;
296
+ return [{
297
+ type: "audio.splitClip",
298
+ key,
299
+ at,
300
+ newKey
301
+ }];
302
+ }
303
+ case "audio.moveClips": {
304
+ onlyFields(command, [
305
+ "type",
306
+ "keys",
307
+ "to"
308
+ ], command.type);
309
+ const moved = find(command.keys);
310
+ const rest = track.clips.filter((clip) => !moved.includes(clip));
311
+ const { to } = command;
312
+ if (!isWhole(to) || to > rest.length) refuse("invalid-index", "the clips can't move there");
313
+ const removals = [...moved].reverse().map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));
314
+ let at = rest.slice(0, to).reduce((sum, clip) => sum + lengthOf(clip), 0);
315
+ const from = at;
316
+ const placed = moved.map((clip) => {
317
+ const positioned = {
318
+ ...clip,
319
+ at
320
+ };
321
+ at += lengthOf(clip);
322
+ return positioned;
323
+ });
324
+ return [
325
+ ...removals,
326
+ open(from, at - from),
327
+ {
328
+ type: "audio.insertClips",
329
+ track: track.key,
330
+ clips: placed
331
+ }
332
+ ];
333
+ }
334
+ case "audio.setGain":
335
+ case "audio.setFade":
336
+ case "audio.setMetadata": return [command];
337
+ default: return refuse("unknown-command", "not a version 1 user command");
1523
338
  }
1524
- function facts(source) {
1525
- const { info } = source;
339
+ }
340
+ // src/core/format/plan-document.ts
341
+ var AUDIO_PLAN_VERSION = 2;
342
+ var DOCUMENT_FIELDS = [
343
+ "format",
344
+ "version",
345
+ "sampleRate",
346
+ "channels",
347
+ "gainDb",
348
+ "sources",
349
+ "tracks",
350
+ "metadata"
351
+ ];
352
+ function read(value) {
353
+ if (!isRecord(value) || Array.isArray(value)) malformed("a document is an object");
354
+ const { format, version } = value;
355
+ if (typeof format !== "string") malformed("format is text");
356
+ if (format !== "hm-audio-plan") throw new AudioError("UNSUPPORTED_FORMAT", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, { details: {
357
+ format: AUDIO_PLAN_FORMAT,
358
+ reason: "unknown-format"
359
+ } });
360
+ if (Number.isSafeInteger(version) && version > 2) throw new AudioError("UNSUPPORTED_FORMAT", `This ${AUDIO_PLAN_FORMAT} document is a later version than this release reads.`, { details: {
361
+ format: AUDIO_PLAN_FORMAT,
362
+ reason: "unknown-format-version"
363
+ } });
364
+ if (version === 1) {
365
+ const earlier = readPlanDocumentV1(value);
1526
366
  return {
1527
- durationSeconds: coarseSeconds(framesToSeconds(info.frames, info.sampleRate)),
1528
- sampleRate: info.sampleRate,
1529
- channels: info.channels,
1530
- container: info.container,
1531
- codec: info.codec,
1532
- truncated: source.warnings.some((warning) => warning.type === "truncated")
367
+ plan: migratePlan(earlier.plan),
368
+ sources: earlier.sources
1533
369
  };
1534
370
  }
1535
- async function load(file, signal, onProgress, beforeDecode) {
1536
- if (!(file instanceof Blob)) throw new TypeError("A recording must be a Blob or a File.");
1537
- nextSource += 1;
1538
- const id = `s${nextSource}`;
1539
- const warnings = [];
1540
- const warnAt = (limit, actual) => {
1541
- if (policy.check(limit, actual) === "warning") warnings.push({
1542
- type: "limit",
1543
- limit,
1544
- actual,
1545
- source: id
1546
- });
1547
- };
1548
- if (checkFile(policy, file) === "warning") warnings.push({
1549
- type: "limit",
1550
- limit: "maxFileSize",
1551
- actual: file.size,
1552
- source: id
1553
- });
1554
- const probe = await withProcessingTime(policy, (limited) => engine.probe(file, { signal: limited }), { signal });
1555
- warnAt("maxChannels", probe.channels);
1556
- warnAt("maxSampleRate", probe.sampleRate);
1557
- warnAt("maxDuration", Math.ceil(probe.frameBound * 1e3 / probe.sampleRate));
1558
- warnAt("maxDecodedSize", probe.frameBound * probe.channels * BYTES_PER_SAMPLE);
1559
- beforeDecode(probe);
1560
- const audio = await withProcessingTime(policy, (limited) => engine.decode(file, probe, {
1561
- signal: limited,
1562
- ...onProgress ? { onProgress } : {}
1563
- }), { signal });
1564
- const frames = Math.min(audio.length, probe.frameBound);
1565
- const channels = audio.numberOfChannels;
1566
- if (audio.sampleRate !== probe.sampleRate || channels < 1 || channels > probe.channels) throw new AudioError("INVALID_AUDIO", "The decoder's output doesn't match the probe.", { details: {
1567
- container: probe.container,
1568
- codec: probe.codec
371
+ if (version !== 2) malformed("version is 1 or 2");
372
+ onlyFields(value, DOCUMENT_FIELDS, "a document");
373
+ if (!isCount(value.sampleRate, 1)) malformed("sampleRate is a whole number above 0");
374
+ if (!isCount(value.channels, 1)) malformed("channels is a whole number above 0");
375
+ const { gainDb } = value;
376
+ if (typeof gainDb !== "number" || !(gainDb >= -120 && gainDb <= 120)) refuse("gain-out-of-range", "the master gain must be from -120 to 120 dB");
377
+ const sources = readSources(value.sources);
378
+ if (!Array.isArray(value.tracks)) malformed("tracks is a list");
379
+ if (value.tracks.length === 0) refuse("no-tracks", "a plan has at least one track");
380
+ const lookup = (id) => Object.hasOwn(sources, id) ? sources[id]?.frames : void 0;
381
+ const plan = {
382
+ sampleRate: value.sampleRate,
383
+ channels: value.channels,
384
+ gainDb,
385
+ tracks: value.tracks.map((track) => checkTrack(track, lookup)),
386
+ metadata: readMetadata(value.metadata)
387
+ };
388
+ checkUniqueKeys(plan);
389
+ return {
390
+ plan,
391
+ sources
392
+ };
393
+ }
394
+ function readAudioPlanDocument(value) {
395
+ try {
396
+ return read(value);
397
+ } catch (error) {
398
+ if (!(error instanceof Invalid)) throw error;
399
+ const reason = error.reason === "malformed-command" ? "malformed-document" : error.reason;
400
+ throw new AudioError("INVALID_DOCUMENT", `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`, { details: {
401
+ format: AUDIO_PLAN_FORMAT,
402
+ reason
1569
403
  } });
1570
- if (frames < 1) throw new AudioError("DECODE_FAILED", "The recording decoded to no audio.", { details: { codec: probe.codec } });
1571
- const peaks = await withProcessingTime(policy, (limited) => engine.peaks(audio, { signal: limited }), { signal });
1572
- throwIfAborted(signal);
1573
- if (probe.declaredFrames !== void 0 && probe.declaredFrames > frames) warnings.push({
1574
- type: "truncated",
1575
- source: id,
1576
- frames,
1577
- declaredFrames: probe.declaredFrames
1578
- });
1579
- return {
1580
- info: Object.freeze({
1581
- id,
1582
- sampleRate: audio.sampleRate,
1583
- channels,
1584
- frames,
1585
- container: probe.container,
1586
- codec: probe.codec
1587
- }),
1588
- audio,
1589
- peaks,
1590
- bytes: frames * channels * BYTES_PER_SAMPLE,
1591
- warnings: Object.freeze(warnings)
1592
- };
1593
- }
1594
- async function track(signal, replaces, run) {
1595
- if (replaces) cancelLoads("A newer recording replaced this one.");
1596
- const controller = new AbortController();
1597
- loading.add(controller);
1598
- const combined = signal ? AbortSignal.any([signal, controller.signal]) : controller.signal;
1599
- busy += 1;
1600
- changed();
1601
- try {
1602
- return await run(combined);
1603
- } finally {
1604
- busy -= 1;
1605
- loading.delete(controller);
1606
- changed();
1607
- }
1608
- }
1609
- function applyChecked(current, commands) {
1610
- const result = applyCommands(reducer, current, commands);
1611
- if (result.state.clips.length > current.clips.length) policy.check("maxClips", result.state.clips.length);
1612
- return result;
1613
- }
1614
- function commit(result, commands) {
1615
- plan = result.state;
1616
- history.push({
1617
- commands,
1618
- inverses: result.inverses
1619
- });
1620
- collect();
1621
- }
1622
- function newKey() {
1623
- const used = new Set(plan?.clips.map((clip) => clip.key));
1624
- for (const { commands, inverses } of history.steps) for (const command of [...commands, ...inverses]) for (const key of keysOf(command)) used.add(key);
1625
- let key;
1626
- do {
1627
- nextKey += 1;
1628
- key = `c${nextKey}`;
1629
- } while (used.has(key));
1630
- return key;
1631
404
  }
405
+ }
406
+ function toAudioPlanDocument(plan, sources) {
1632
407
  return {
1633
- getSnapshot: store.getSnapshot,
1634
- subscribe: store.subscribe,
1635
- async open(file, callOptions = {}) {
1636
- generation += 1;
1637
- const started = generation;
1638
- status = "opening";
1639
- error = void 0;
1640
- try {
1641
- const source = await track(callOptions.signal, true, (signal) => load(file, signal, callOptions.onProgress, () => {}));
1642
- const replaced = superseded(started);
1643
- if (replaced) throw replaced;
1644
- policy.check("maxSessionSize", source.bytes);
1645
- sources.clear();
1646
- history.clear();
1647
- sources.set(source.info.id, source);
1648
- plan = {
1649
- sampleRate: source.info.sampleRate,
1650
- channels: source.info.channels,
1651
- clips: [{
1652
- key: newKey(),
1653
- source: source.info.id,
1654
- start: 0,
1655
- end: source.info.frames,
1656
- gainDb: 0,
1657
- fadeIn: NO_FADE,
1658
- fadeOut: NO_FADE
1659
- }],
1660
- metadata: EMPTY_METADATA
408
+ format: AUDIO_PLAN_FORMAT,
409
+ version: 2,
410
+ sampleRate: plan.sampleRate,
411
+ channels: plan.channels,
412
+ gainDb: plan.gainDb,
413
+ sources: Object.fromEntries(Object.entries(sources).map(([id, { frames, asset }]) => [id, asset === void 0 ? { frames } : {
414
+ frames,
415
+ asset: { ...asset }
416
+ }])),
417
+ tracks: plan.tracks.map((track) => ({
418
+ key: track.key,
419
+ name: track.name,
420
+ gainDb: track.gainDb,
421
+ muted: track.muted,
422
+ soloed: track.soloed,
423
+ clips: track.clips.map((clip) => {
424
+ if (!Object.hasOwn(sources, clip.source)) throw new TypeError(`The sources don't include ${clip.source}, which clip ${clip.key} uses.`);
425
+ return {
426
+ key: clip.key,
427
+ at: clip.at,
428
+ source: clip.source,
429
+ start: clip.start,
430
+ end: clip.end,
431
+ gainDb: clip.gainDb,
432
+ fadeIn: {
433
+ frames: clip.fadeIn.frames,
434
+ curve: clip.fadeIn.curve
435
+ },
436
+ fadeOut: {
437
+ frames: clip.fadeOut.frames,
438
+ curve: clip.fadeOut.curve
439
+ }
1661
440
  };
1662
- selection = void 0;
1663
- status = "ready";
1664
- changed();
1665
- emit({
1666
- type: "recording_opened",
1667
- ...facts(source)
1668
- });
1669
- } catch (reason) {
1670
- const failure = asAudioError(reason, "The recording couldn't be opened.");
1671
- if (started !== generation) throw failure;
1672
- status = plan ? "ready" : "error";
1673
- error = failure;
1674
- changed();
1675
- emit({
1676
- type: "failed",
1677
- operation: "open",
1678
- code: failure.code
1679
- });
1680
- throw failure;
1681
- }
1682
- },
1683
- async insert(file, insertOptions = {}) {
1684
- if (!plan || status !== "ready") throw new AudioError("INVALID_COMMAND", "Open a recording before inserting another.", { details: { reason: "no-recording" } });
1685
- const started = generation;
1686
- error = void 0;
1687
- try {
1688
- const source = await track(insertOptions.signal, false, (signal) => {
1689
- policy.check("maxFiles", sources.size + 1);
1690
- return load(file, signal, insertOptions.onProgress, (probe) => {
1691
- const rate = plan?.sampleRate;
1692
- if (probe.sampleRate !== rate) throw new AudioError("UNSUPPORTED_FORMAT", `Recordings at ${probe.sampleRate} Hz can't be inserted into a ${rate} Hz session yet.`, { details: { sampleRate: probe.sampleRate } });
1693
- });
1694
- });
1695
- const replaced = superseded(started);
1696
- if (replaced) throw replaced;
1697
- const current = plan;
1698
- const drop = stepsToDrop(source.bytes);
1699
- if (drop === void 0) throw policy.error("maxSessionSize", heldBytes() + source.bytes);
1700
- const commands = [{
1701
- type: "audio.insertClips",
1702
- at: insertOptions.at ?? planLength(current),
1703
- clips: [{
1704
- key: newKey(),
1705
- source: source.info.id,
1706
- start: 0,
1707
- end: source.info.frames,
1708
- gainDb: 0,
1709
- fadeIn: NO_FADE,
1710
- fadeOut: NO_FADE
1711
- }],
1712
- splitKey: newKey()
1713
- }];
1714
- sources.set(source.info.id, source);
1715
- let result;
1716
- try {
1717
- result = applyChecked(current, commands);
1718
- } catch (reason) {
1719
- sources.delete(source.info.id);
1720
- throw reason;
1721
- }
1722
- history.drop(drop);
1723
- commit(result, commands);
1724
- changed();
1725
- emit({
1726
- type: "recording_inserted",
1727
- ...facts(source)
1728
- });
1729
- } catch (reason) {
1730
- const failure = asAudioError(reason, "The recording couldn't be inserted.");
1731
- if (started !== generation) throw failure;
1732
- error = failure;
1733
- changed();
1734
- emit({
1735
- type: "failed",
1736
- operation: "insert",
1737
- code: failure.code
1738
- });
1739
- throw failure;
1740
- }
1741
- },
1742
- execute(commands) {
1743
- const list = Array.isArray(commands) ? [...commands] : [commands];
1744
- if (list.length === 0) return;
1745
- try {
1746
- if (!plan) throw new AudioError("INVALID_COMMAND", "Open a recording before editing it.", { details: { reason: "no-recording" } });
1747
- let copies;
1748
- try {
1749
- copies = structuredClone(list);
1750
- } catch (reason) {
1751
- throw new AudioError("INVALID_COMMAND", "Commands must be plain data.", {
1752
- cause: reason,
1753
- details: { reason: "not-plain-data" }
1754
- });
1755
- }
1756
- commit(applyChecked(plan, copies), copies);
1757
- } catch (reason) {
1758
- const failure = asAudioError(reason);
1759
- emit({
1760
- type: "failed",
1761
- operation: "command",
1762
- code: failure.code
1763
- });
1764
- throw failure;
1765
- }
1766
- changed();
1767
- emit({
1768
- type: "command",
1769
- commands: list.map((command) => command.type)
1770
- });
1771
- },
1772
- group: (fn) => history.group(fn),
1773
- createKey: newKey,
1774
- undo() {
1775
- const current = plan;
1776
- const entry = current && history.undo();
1777
- if (!current || !entry) return;
1778
- try {
1779
- plan = applyCommands(reducer, current, entry.inverses).state;
1780
- } catch (reason) {
1781
- history.restore("undo");
1782
- throw reason;
1783
- }
1784
- changed();
1785
- emit({ type: "undo" });
1786
- },
1787
- redo() {
1788
- const current = plan;
1789
- const entry = current && history.redo();
1790
- if (!current || !entry) return;
1791
- try {
1792
- plan = applyCommands(reducer, current, entry.commands).state;
1793
- } catch (reason) {
1794
- history.restore("redo");
1795
- throw reason;
1796
- }
1797
- changed();
1798
- emit({ type: "redo" });
1799
- },
1800
- select(range) {
1801
- let next;
1802
- if (range) {
1803
- const { start, end } = range;
1804
- if (!Number.isSafeInteger(start) || !Number.isSafeInteger(end)) throw new RangeError("A selection is a range of whole frames.");
1805
- const length = plan ? planLength(plan) : 0;
1806
- const from = Math.max(0, Math.min(start, end, length));
1807
- const to = Math.min(length, Math.max(start, end, 0));
1808
- next = from < to ? {
1809
- start: from,
1810
- end: to
1811
- } : void 0;
1812
- }
1813
- if (next?.start === selection?.start && next?.end === selection?.end) return;
1814
- selection = next;
1815
- changed();
1816
- },
1817
- getPeaks: (id) => sources.get(id)?.peaks,
1818
- getAudio: (id) => sources.get(id)?.audio,
1819
- async export(exportOptions = {}) {
1820
- const current = plan;
1821
- const format = exportOptions.format ?? { container: "wav" };
1822
- try {
1823
- if (!current) throw new AudioError("INVALID_COMMAND", "Open a recording before exporting it.", { details: { reason: "no-recording" } });
1824
- if (current.clips.length === 0) throw new AudioError("INVALID_COMMAND", "The recording has no clips to export.", { details: { reason: "empty-plan" } });
1825
- const { processor } = options;
1826
- if (!processor) throw new TypeError("Exporting needs a processor in createAudioSession.");
1827
- const used = /* @__PURE__ */ new Map();
1828
- for (const { source } of current.clips) {
1829
- const held = sources.get(source);
1830
- if (held) used.set(source, held.audio);
1831
- }
1832
- busy += 1;
1833
- changed();
1834
- try {
1835
- const output = await withProcessingTime(policy, (signal) => processor.render({
1836
- plan: current,
1837
- sources: used,
1838
- format
1839
- }, {
1840
- signal,
1841
- ...exportOptions.onProgress ? { onProgress: exportOptions.onProgress } : {}
1842
- }), exportOptions.signal ? { signal: exportOptions.signal } : {});
1843
- emit({
1844
- type: "recording_exported",
1845
- durationSeconds: coarseSeconds(framesToSeconds(planLength(current), current.sampleRate)),
1846
- sampleRate: current.sampleRate,
1847
- channels: current.channels,
1848
- sampleFormat: format.sampleFormat ?? "pcm16"
1849
- });
1850
- return output;
1851
- } finally {
1852
- busy -= 1;
1853
- changed();
1854
- }
1855
- } catch (reason) {
1856
- if (reason instanceof TypeError || reason instanceof RangeError) throw reason;
1857
- const failure = exportOptions.signal?.aborted ? abortError(exportOptions.signal) : asAudioError(reason, "The recording couldn't be exported.");
1858
- emit({
1859
- type: "failed",
1860
- operation: "export",
1861
- code: failure.code
1862
- });
1863
- throw failure;
1864
- }
1865
- },
1866
- async close() {
1867
- generation += 1;
1868
- cancelLoads("The recording was closed.");
1869
- const hadRecording = plan !== void 0;
1870
- sources.clear();
1871
- history.clear();
1872
- plan = void 0;
1873
- selection = void 0;
1874
- error = void 0;
1875
- status = "empty";
1876
- changed();
1877
- if (hadRecording) emit({ type: "recording_closed" });
1878
- }
441
+ })
442
+ })),
443
+ metadata: { ...plan.metadata }
1879
444
  };
1880
445
  }
1881
- // src/messages/en.ts
1882
- var audioMessages = /* @__PURE__ */ defineMessages({
1883
- ...sdkCoreMessages,
1884
- "errors.INVALID_AUDIO": "This file isn't valid audio, or it's too damaged to open.",
1885
- "errors.UNSUPPORTED_FORMAT": "This audio format isn't supported. Try converting the file to WAV, then open it again.",
1886
- "errors.DECODE_FAILED": "This browser can't play this kind of audio. Try another browser, or convert the file to WAV.",
1887
- "errors.INVALID_COMMAND": "This edit couldn't be made. Please try again.",
1888
- "errors.INVALID_DOCUMENT": "This project is damaged, or it isn't an audio project.",
1889
- "errors.DURATION_TOO_LONG": "This recording is {actual, duration} long, which is over the {maximum, duration} limit.",
1890
- "errors.TOO_MANY_CHANNELS": "This recording has {actual, number} channels, which is over the {maximum, number}-channel limit.",
1891
- "errors.SAMPLE_RATE_TOO_HIGH": "This recording's sample rate is {actual, number} Hz, which is over the {maximum, number} Hz limit.",
1892
- "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.",
1893
- "errors.TOO_MANY_CLIPS": /* @__PURE__ */ plural("maximum", {
1894
- one: "A recording can have {maximum} clip. Join or delete clips, and try again.",
1895
- other: "A recording can have up to {maximum} clips. Join or delete clips, and try again."
1896
- }),
1897
- "warnings.maxDuration": "This recording is {actual, duration} long, and may be slow to open and edit.",
1898
- "warnings.maxChannels": "This recording has {actual, number} channels, and may be slow to edit.",
1899
- "warnings.maxSampleRate": "This recording's sample rate is {actual, number} Hz, and it may be slow to edit.",
1900
- "warnings.maxSessionSize": "The open recordings use {actual, fileSize} of memory. Clearing the undo history frees memory.",
1901
- "warnings.maxClips": /* @__PURE__ */ plural("actual", {
1902
- one: "This recording has {actual} clip. Many clips may be slow to play and export.",
1903
- other: "This recording has {actual} clips. Many clips may be slow to play and export."
1904
- }),
1905
- "warnings.truncated": "This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds."
1906
- });
1907
- export { AUDIO_PLAN_FORMAT, AUDIO_PLAN_VERSION, AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MIN_GAIN_DB, NO_FADE, audioLimitDefinitions, audioLimits, audioMessages, clipLength, clipOffsets, connectOutput, createAudioEngine, createAudioOutput, createAudioProcessor, createAudioSession, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument };
446
+ export { AUDIO_PLAN_FORMAT, AUDIO_PLAN_VERSION, AudioError, EMPTY_METADATA, MAX_GAIN_DB, MAX_METADATA_LENGTH, MAX_SOURCE_NAME_LENGTH, MAX_TRACK_NAME_LENGTH, MIN_GAIN_DB, NO_FADE, audibleTracks, audioErrorText, audioLimitDefinitions, audioLimits, audioMessages, audioWarningText, clipAt, clipEnd, clipLength, connectOutput, createAudioAdapters, createAudioEngine, createAudioOutput, createAudioProcessor, createAudioSession, dbToGain, formatTimecode, framesToSeconds, gainAt, isAudioError, migrateAudioCommand, migratePlan, mixLength, peakColumns, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument, trackLength, watchPlayhead };
1908
447
 
1909
448
  //# sourceMappingURL=index.js.map