@hussmartinez/audio-sdk 0.4.0 → 0.6.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,4 +1,4 @@
1
- import { SdkError, applyCommands, checkFile, coreLimits, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, locate, plural, resolveAssetsBase, sdkCoreMessages, sequenceOffsets, withProcessingTime } from "@hussmartinez/sdk-core";
1
+ import { SdkError, applyCommands, checkFile, coreLimits, createErrorHelpers, createHistory, createStore, createWorkerClient, defineLimits, defineMessages, isSdkError, plural, resolveAssetsBase, sdkCoreMessages, withProcessingTime } from "@hussmartinez/sdk-core";
2
2
  // src/core/errors/audio-error.ts
3
3
  var AudioError = class extends SdkError {
4
4
  name = "AudioError";
@@ -18,8 +18,8 @@ function audioWorkerSource(assetsUrl) {
18
18
  loadWorker: selfHosted ? async () => () => new Worker(selfHosted, {
19
19
  type: "module",
20
20
  name: "hm-audio"
21
- }) : async () => (await import("./lazy/inline-worker-BB2jwrIT.js")).createInlineWorker,
22
- version: "0.4.0",
21
+ }) : async () => (await import("./lazy/inline-worker-D8bxbE-Q.js")).createInlineWorker,
22
+ version: "0.6.0",
23
23
  ...selfHosted ? { asset: selfHosted } : {}
24
24
  };
25
25
  }
@@ -55,6 +55,27 @@ function combine(values, pick) {
55
55
  }
56
56
  return out;
57
57
  }
58
+ // src/adapters/resample/resample.ts
59
+ var ZERO_CROSSINGS = 16;
60
+ var PASS_BAND = .945;
61
+ var isWhole$1 = (value, least) => Number.isSafeInteger(value) && value >= least;
62
+ function resampledLength(frames, fromRate, toRate) {
63
+ if (!isWhole$1(frames, 0) || !isWhole$1(fromRate, 1) || !isWhole$1(toRate, 1)) throw new RangeError("Frames and rates must be whole numbers, and rates positive.");
64
+ const length = Math.ceil(frames * toRate / fromRate);
65
+ if (!Number.isSafeInteger(length)) throw new RangeError("The resampled length is too large.");
66
+ return length;
67
+ }
68
+ function resampleReach(fromRate, toRate) {
69
+ return Math.ceil(ZERO_CROSSINGS / (Math.min(1, toRate / fromRate) * PASS_BAND));
70
+ }
71
+ function resampleWindow(start, frames, fromRate, toRate, inputFrames) {
72
+ const reach = resampleReach(fromRate, toRate);
73
+ const clip = (frame) => Math.min(inputFrames, Math.max(0, frame));
74
+ return {
75
+ first: clip(Math.floor(start * fromRate / toRate) - reach),
76
+ end: clip(Math.floor((start + frames - 1) * fromRate / toRate) + reach + 1)
77
+ };
78
+ }
58
79
  // src/adapters/web-audio/platform-decode.ts
59
80
  var webAudioDecoder = (bytes, { sampleRate, channels }) => {
60
81
  const Offline = globalThis.OfflineAudioContext;
@@ -186,6 +207,86 @@ function createEngine(environment) {
186
207
  } });
187
208
  return fresh.layout;
188
209
  }
210
+ function bufferFor(numberOfChannels, length, sampleRate, container) {
211
+ try {
212
+ return environment.createBuffer({
213
+ numberOfChannels,
214
+ length,
215
+ sampleRate
216
+ });
217
+ } catch (error) {
218
+ throw new AudioError("UNSUPPORTED_FORMAT", "This browser can't hold audio at this rate.", {
219
+ details: {
220
+ container,
221
+ sampleRate
222
+ },
223
+ cause: error
224
+ });
225
+ }
226
+ }
227
+ async function resample(audio, toRate, container, signal, onProgress) {
228
+ const fromRate = audio.sampleRate;
229
+ const length = resampledLength(audio.length, fromRate, toRate);
230
+ const buffer = bufferFor(audio.numberOfChannels, length, toRate, container);
231
+ const room = BLOCK_FRAMES - 2 * resampleReach(fromRate, toRate);
232
+ const blockFrames = Math.max(1, Math.min(BLOCK_FRAMES, Math.floor(room * toRate / fromRate)));
233
+ main ??= newClient();
234
+ for (let start = 0; start < length; start += blockFrames) {
235
+ const frames = Math.min(blockFrames, length - start);
236
+ const { first, end } = resampleWindow(start, frames, fromRate, toRate, audio.length);
237
+ const channels = Array.from({ length: audio.numberOfChannels }, (_, c) => audio.getChannelData(c).slice(first, end));
238
+ const block = await main.call("resample", {
239
+ channels,
240
+ inputStart: first,
241
+ fromRate,
242
+ toRate,
243
+ start,
244
+ frames
245
+ }, {
246
+ transfer: true,
247
+ ...signal ? { signal } : {}
248
+ });
249
+ for (let c = 0; c < audio.numberOfChannels; c += 1) buffer.copyToChannel(block[c], c, start);
250
+ onProgress?.((start + frames) / length);
251
+ }
252
+ if (length === 0) onProgress?.(1);
253
+ return buffer;
254
+ }
255
+ async function decodeAtOwnRate(file, probe, signal, onProgress) {
256
+ if (probe.codec !== "pcm") {
257
+ const audio = await decodeOnPage(file, compressedProbes.has(probe) ? probe : await reprobe(file, probe, signal), environment.decodePlatform, environment.createBuffer, signal);
258
+ onProgress?.(1);
259
+ return audio;
260
+ }
261
+ const layout = await layoutOf(file, probe, signal);
262
+ const { frames, channels, sampleRate } = layout;
263
+ const buffer = bufferFor(channels, frames, sampleRate, layout.container);
264
+ const buckets = Math.ceil(frames / 256);
265
+ const peaks = {
266
+ min: Array.from({ length: channels }, () => new Float32Array(buckets)),
267
+ max: Array.from({ length: channels }, () => new Float32Array(buckets))
268
+ };
269
+ main ??= newClient();
270
+ for (let start = 0; start < frames; start += BLOCK_FRAMES) {
271
+ const block = await main.call("readBlock", {
272
+ file,
273
+ layout,
274
+ start,
275
+ frames: Math.min(BLOCK_FRAMES, frames - start),
276
+ bucket: 256
277
+ }, signal ? { signal } : {});
278
+ const at = start / 256;
279
+ for (let c = 0; c < channels; c += 1) {
280
+ buffer.copyToChannel(block.channels[c], c, start);
281
+ peaks.min[c]?.set(block.min[c], at);
282
+ peaks.max[c]?.set(block.max[c], at);
283
+ }
284
+ onProgress?.(Math.min(start + BLOCK_FRAMES, frames) / frames);
285
+ }
286
+ if (frames === 0) onProgress?.(1);
287
+ finestPeaks.set(buffer, peaks);
288
+ return buffer;
289
+ }
189
290
  return {
190
291
  probe(file, options = {}) {
191
292
  return run(async () => {
@@ -201,55 +302,12 @@ function createEngine(environment) {
201
302
  decode(file, probe, options = {}) {
202
303
  return run(async () => {
203
304
  throwIfAborted(options.signal);
305
+ const { signal, onProgress, sampleRate = probe.sampleRate } = options;
306
+ if (!Number.isSafeInteger(sampleRate) || sampleRate < 1) throw new RangeError("The sample rate must be a positive whole number of hertz.");
204
307
  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;
308
+ if (sampleRate === probe.sampleRate) return decodeAtOwnRate(file, probe, signal, onProgress);
309
+ const half = (from) => onProgress && ((fraction) => onProgress(from + fraction / 2));
310
+ return resample(await decodeAtOwnRate(file, probe, signal, half(0)), sampleRate, probe.container, signal, half(.5));
253
311
  });
254
312
  },
255
313
  peaks(audio, options = {}) {
@@ -303,30 +361,58 @@ var NO_FADE = Object.freeze({
303
361
  frames: 0,
304
362
  curve: "linear"
305
363
  });
364
+ var MAX_TRACK_NAME_LENGTH = 100;
306
365
  function clipLength(clip) {
307
366
  return clip.end - clip.start;
308
367
  }
368
+ function clipEnd(clip) {
369
+ return clip.at + clipLength(clip);
370
+ }
371
+ function trackLength(track) {
372
+ const last = track.clips.at(-1);
373
+ return last ? clipEnd(last) : 0;
374
+ }
309
375
  function planLength(plan) {
310
- let total = 0;
311
- for (const clip of plan.clips) total += clipLength(clip);
312
- return total;
376
+ let length = 0;
377
+ for (const track of plan.tracks) length = Math.max(length, trackLength(track));
378
+ return length;
313
379
  }
314
- function clipOffsets(plan) {
315
- return clipBoundaries(plan).slice(0, -1);
380
+ function audibleTracks(plan) {
381
+ const solo = plan.tracks.some((track) => track.soloed);
382
+ return plan.tracks.filter((track) => !track.muted && (!solo || track.soloed));
316
383
  }
317
- function clipBoundaries(plan) {
318
- return sequenceOffsets(plan.clips.map(clipLength));
384
+ function orderProblem(clips) {
385
+ for (let i = 1; i < clips.length; i += 1) {
386
+ const before = clips[i - 1];
387
+ const clip = clips[i];
388
+ if (clip.at < before.at) return "clips-out-of-order";
389
+ if (clip.at < clipEnd(before)) return "clips-overlap";
390
+ }
391
+ }
392
+ function clipIndexAt(clips, frame) {
393
+ let low = 0;
394
+ let high = clips.length;
395
+ while (low < high) {
396
+ const middle = low + high >>> 1;
397
+ if (clipEnd(clips[middle]) > frame) high = middle;
398
+ else low = middle + 1;
399
+ }
400
+ return low;
401
+ }
402
+ function clipAt(track, frame) {
403
+ const clip = track.clips[clipIndexAt(track.clips, frame)];
404
+ return clip && clip.at <= frame ? clip : void 0;
319
405
  }
320
406
  var MIN_GAIN_DB = -120;
321
407
  var MAX_GAIN_DB = 120;
322
- var isFrames = (value) => Number.isSafeInteger(value) && value >= 0;
408
+ var isFrames$1 = (value) => Number.isSafeInteger(value) && value >= 0;
323
409
  function clipProblem(clip, sourceFrames) {
324
410
  if (![
325
411
  clip.start,
326
412
  clip.end,
327
413
  clip.fadeIn.frames,
328
414
  clip.fadeOut.frames
329
- ].every(isFrames)) return "invalid-frames";
415
+ ].every(isFrames$1)) return "invalid-frames";
330
416
  if (clip.end <= clip.start) return "clip-too-short";
331
417
  if (clip.end > sourceFrames) return "clip-outside-source";
332
418
  if (typeof clip.gainDb !== "number" || !(clip.gainDb >= -120 && clip.gainDb <= 120)) return "gain-out-of-range";
@@ -400,44 +486,92 @@ function gainEvents(clip, from, sampleRate) {
400
486
  return events;
401
487
  }
402
488
  // src/adapters/web-audio/play-graph.ts
489
+ var GAIN_RAMP = .005;
490
+ function tracksWithClips(plan) {
491
+ const found = /* @__PURE__ */ new Map();
492
+ for (const track of plan.tracks) if (track.clips.length > 0) found.set(track.key, track.clips);
493
+ return found;
494
+ }
495
+ function sameClips(a, b) {
496
+ if (a.sampleRate !== b.sampleRate || a.channels !== b.channels) return false;
497
+ const before = tracksWithClips(a);
498
+ const after = tracksWithClips(b);
499
+ if (before.size !== after.size) return false;
500
+ for (const [key, clips] of before) if (after.get(key) !== clips) return false;
501
+ return true;
502
+ }
503
+ function trackLevels(plan) {
504
+ const audible = new Set(audibleTracks(plan));
505
+ return new Map(plan.tracks.map((track) => [track.key, audible.has(track) ? dbToGain(track.gainDb) : 0]));
506
+ }
403
507
  function schedulePlan(context, destination, plan, buffer, from, at) {
404
508
  const rate = plan.sampleRate;
405
509
  const bus = context.createGain();
510
+ bus.gain.value = dbToGain(plan.gainDb);
406
511
  bus.channelCount = plan.channels;
407
512
  bus.channelCountMode = "explicit";
408
513
  bus.channelInterpretation = "speakers";
409
514
  bus.connect(destination);
410
515
  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
- });
516
+ const tracks = /* @__PURE__ */ new Map();
517
+ const levels = trackLevels(plan);
518
+ let master = dbToGain(plan.gainDb);
519
+ for (const track of plan.tracks) {
520
+ if (track.clips.length === 0) continue;
521
+ const output = context.createGain();
522
+ output.gain.value = levels.get(track.key) ?? 0;
523
+ output.channelCount = plan.channels;
524
+ output.channelCountMode = "explicit";
525
+ output.channelInterpretation = "speakers";
526
+ output.connect(bus);
527
+ tracks.set(track.key, output);
528
+ for (const clip of track.clips) {
529
+ const length = clipLength(clip);
530
+ if (clip.at + length <= from) continue;
531
+ const within = Math.max(0, from - clip.at);
532
+ const when = at + Math.max(0, clip.at - from) / rate;
533
+ const source = context.createBufferSource();
534
+ source.buffer = buffer(clip.source);
535
+ const gain = context.createGain();
536
+ for (const event of gainEvents(clip, within, rate)) if (event.kind === "set") gain.gain.setValueAtTime(event.value, when + event.time);
537
+ else gain.gain.setValueCurveAtTime(event.values, when + event.time, event.duration);
538
+ source.connect(gain).connect(output);
539
+ source.start(when, (clip.start + within) / rate, (length - within) / rate);
540
+ nodes.push({
541
+ source,
542
+ gain
543
+ });
544
+ }
430
545
  }
431
- return { stop() {
432
- for (const { source, gain } of nodes) {
433
- try {
434
- source.stop();
435
- } catch {}
436
- source.disconnect();
437
- gain.disconnect();
546
+ const ramp = (param, from, to, time) => {
547
+ if (from === to) return;
548
+ param.setValueAtTime(from, time);
549
+ param.linearRampToValueAtTime(to, time + GAIN_RAMP);
550
+ };
551
+ return {
552
+ setLevels(next, time) {
553
+ const targets = trackLevels(next);
554
+ for (const [key, output] of tracks) {
555
+ const target = targets.get(key) ?? 0;
556
+ ramp(output.gain, levels.get(key) ?? 0, target, time);
557
+ levels.set(key, target);
558
+ }
559
+ const target = dbToGain(next.gainDb);
560
+ ramp(bus.gain, master, target, time);
561
+ master = target;
562
+ },
563
+ stop() {
564
+ for (const { source, gain } of nodes) {
565
+ try {
566
+ source.stop();
567
+ } catch {}
568
+ source.disconnect();
569
+ gain.disconnect();
570
+ }
571
+ for (const output of tracks.values()) output.disconnect();
572
+ bus.disconnect();
438
573
  }
439
- bus.disconnect();
440
- } };
574
+ };
441
575
  }
442
576
  // src/adapters/audio-output.ts
443
577
  var START_LEAD = .03;
@@ -462,6 +596,7 @@ function createOutput(environment) {
462
596
  const setState = (state) => {
463
597
  if (store.getSnapshot().state !== state) store.set(Object.freeze({ state }));
464
598
  };
599
+ const jumped = () => store.set(Object.freeze({ state: store.getSnapshot().state }));
465
600
  function buffer(id) {
466
601
  const audio = sources.get(id);
467
602
  if (!audio) throw new TypeError(`The plan's source ${id} isn't loaded.`);
@@ -532,12 +667,22 @@ function createOutput(environment) {
532
667
  position,
533
668
  load(next, nextSources) {
534
669
  assertAlive();
670
+ if (playing && context && plan && sameClips(plan, next)) {
671
+ plan = next;
672
+ sources = nextSources;
673
+ playing.scheduled.setLevels(next, context.currentTime);
674
+ return;
675
+ }
535
676
  const wasPlaying = playing !== void 0;
536
677
  unschedule();
537
678
  plan = next;
538
679
  sources = nextSources;
680
+ const before = playhead;
539
681
  playhead = Math.min(playhead, length());
540
- if (!wasPlaying) return;
682
+ if (!wasPlaying) {
683
+ if (playhead !== before) jumped();
684
+ return;
685
+ }
541
686
  if (playhead >= length()) {
542
687
  playhead = length();
543
688
  setState("stopped");
@@ -547,7 +692,10 @@ function createOutput(environment) {
547
692
  assertAlive();
548
693
  if (length() === 0 || playing) return;
549
694
  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" } });
695
+ 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: {
696
+ feature: "audio-output",
697
+ reason: "autoplay-blocked"
698
+ } });
551
699
  if (destroyed || playing || length() === 0) return;
552
700
  if (playhead >= length()) playhead = 0;
553
701
  schedule();
@@ -562,16 +710,20 @@ function createOutput(environment) {
562
710
  stop() {
563
711
  assertAlive();
564
712
  unschedule();
713
+ const before = playhead;
565
714
  playhead = 0;
566
- setState("stopped");
715
+ if (store.getSnapshot().state !== "stopped") setState("stopped");
716
+ else if (before !== 0) jumped();
567
717
  },
568
718
  seek(frame) {
569
719
  assertAlive();
570
720
  const wasPlaying = playing !== void 0;
721
+ const before = position();
571
722
  unschedule();
572
723
  playhead = Math.max(0, Math.min(Math.round(frame), length()));
573
724
  if (wasPlaying && playhead < length()) schedule();
574
- else if (wasPlaying) setState("stopped");
725
+ if (wasPlaying && playhead >= length()) setState("stopped");
726
+ else if (playhead !== before) jumped();
575
727
  },
576
728
  async destroy() {
577
729
  if (destroyed) return;
@@ -583,6 +735,38 @@ function createOutput(environment) {
583
735
  }
584
736
  };
585
737
  }
738
+ // src/core/model/mix.ts
739
+ function mixLength(plan) {
740
+ let length = 0;
741
+ for (const track of audibleTracks(plan)) length = Math.max(length, trackLength(track));
742
+ return length;
743
+ }
744
+ function gatherSegments(plan, sources, start, frames) {
745
+ const end = start + frames;
746
+ const segments = [];
747
+ for (const track of audibleTracks(plan)) {
748
+ const gain = dbToGain(track.gainDb);
749
+ for (let index = clipIndexAt(track.clips, start); index < track.clips.length; index += 1) {
750
+ const clip = track.clips[index];
751
+ if (!clip || clip.at >= end) break;
752
+ const from = Math.max(start, clip.at);
753
+ const to = Math.min(end, clipEnd(clip));
754
+ const within = from - clip.at;
755
+ const source = sources.get(clip.source);
756
+ if (!source) throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't given.`);
757
+ const samples = Array.from({ length: source.numberOfChannels }, (_, channel) => source.getChannelData(channel).slice(clip.start + within, clip.start + within + to - from));
758
+ segments.push({
759
+ clip,
760
+ gain,
761
+ within,
762
+ at: from - start,
763
+ samples,
764
+ frames: to - from
765
+ });
766
+ }
767
+ }
768
+ return segments;
769
+ }
586
770
  // src/adapters/wav/wav-writer.ts
587
771
  var BYTES = {
588
772
  pcm16: 2,
@@ -612,7 +796,7 @@ function check(job) {
612
796
  if (!SAMPLE_FORMATS.has(sampleFormat)) throw new TypeError(`Unknown sample format ${String(sampleFormat)}.`);
613
797
  if (!Number.isSafeInteger(plan.sampleRate) || plan.sampleRate < 1) throw new RangeError("The plan's sample rate must be a whole number above 0.");
614
798
  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) {
799
+ for (const track of plan.tracks) for (const clip of track.clips) {
616
800
  const source = sources.get(clip.source);
617
801
  if (!source) throw new TypeError(`Clip ${clip.key}'s source ${clip.source} isn't in the job.`);
618
802
  assertClip(clip, source.length);
@@ -644,7 +828,8 @@ function createProcessor(environment) {
644
828
  throwIfAborted(signal);
645
829
  const worker = await ready();
646
830
  const call = signal ? { signal } : {};
647
- const frames = planLength(plan);
831
+ const frames = mixLength(plan);
832
+ const gain = dbToGain(plan.gainDb);
648
833
  const spec = {
649
834
  sampleRate: plan.sampleRate,
650
835
  channels: plan.channels,
@@ -655,47 +840,34 @@ function createProcessor(environment) {
655
840
  ...spec,
656
841
  metadata: { ...plan.metadata }
657
842
  }, call)];
658
- const offsets = clipOffsets(plan);
659
- let first = 0;
843
+ let peak = 0;
844
+ let clippedFrames = 0;
660
845
  for (let start = 0; start < frames; start += EXPORT_BLOCK_FRAMES) {
661
846
  throwIfAborted(signal);
662
847
  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", {
848
+ const segments = gatherSegments(plan, sources, start, length);
849
+ const block = await worker.call("renderBlock", {
689
850
  channels: plan.channels,
690
851
  frames: length,
852
+ gain,
691
853
  sampleFormat,
692
854
  segments
693
- }, call));
694
- onProgress?.(end / frames);
855
+ }, {
856
+ ...call,
857
+ transfer: true
858
+ });
859
+ parts.push(block.bytes);
860
+ peak = Math.max(peak, block.peak);
861
+ clippedFrames += block.clipped;
862
+ onProgress?.((start + length) / frames);
695
863
  }
696
864
  if (dataSize(spec) % 2 === 1) parts.push(/* @__PURE__ */ new Uint8Array(1));
697
865
  if (frames === 0) onProgress?.(1);
698
- return new Blob(parts, { type: "audio/wav" });
866
+ return {
867
+ blob: new Blob(parts, { type: "audio/wav" }),
868
+ peakDb: 20 * Math.log10(peak),
869
+ clippedFrames
870
+ };
699
871
  }
700
872
  return {
701
873
  async render(job, options = {}) {
@@ -712,6 +884,28 @@ function createProcessor(environment) {
712
884
  }
713
885
  };
714
886
  }
887
+ // src/adapters/audio-adapters.ts
888
+ function createAudioAdapters(options = {}) {
889
+ const worker = {
890
+ ...options.assetsUrl === void 0 ? {} : { assetsUrl: options.assetsUrl },
891
+ ...options.idleTimeout === void 0 ? {} : { idleTimeout: options.idleTimeout }
892
+ };
893
+ const engine = createAudioEngine(worker);
894
+ const processor = createAudioProcessor(worker);
895
+ const output = createAudioOutput();
896
+ return {
897
+ engine,
898
+ processor,
899
+ output,
900
+ async destroy() {
901
+ await Promise.all([
902
+ engine.destroy(),
903
+ processor.destroy(),
904
+ output.destroy()
905
+ ]);
906
+ }
907
+ };
908
+ }
715
909
  // src/core/errors/audio-limits.ts
716
910
  var audioLimitDefinitions = {
717
911
  ...coreLimits,
@@ -751,10 +945,15 @@ var audioLimitDefinitions = {
751
945
  code: "TOO_MANY_CLIPS",
752
946
  unit: "count",
753
947
  default: 2e3
948
+ },
949
+ maxTracks: {
950
+ code: "TOO_MANY_TRACKS",
951
+ unit: "count",
952
+ default: 16
754
953
  }
755
954
  };
756
955
  var audioLimits = /* @__PURE__ */ defineLimits(audioLimitDefinitions, { errorClass: AudioError });
757
- // src/core/operations/commands.ts
956
+ // src/core/operations/checks.ts
758
957
  var MAX_METADATA_LENGTH = 1e3;
759
958
  function longerThan(text, max) {
760
959
  if (text.length <= max) return false;
@@ -794,46 +993,6 @@ function fade(value, name) {
794
993
  curve: value.curve
795
994
  };
796
995
  }
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
996
  var CLIP_FIELDS = [
838
997
  "key",
839
998
  "source",
@@ -844,15 +1003,10 @@ var CLIP_FIELDS = [
844
1003
  "fadeOut"
845
1004
  ];
846
1005
  var FADE_FIELDS = ["frames", "curve"];
847
- var ENTRY_FIELDS = ["index", "clip"];
848
1006
  function onlyFields(value, allowed, what) {
849
1007
  for (const [field, content] of Object.entries(value)) if (content !== void 0 && !allowed.includes(field)) invalid("malformed-command", `${what} has no field ${field}`);
850
1008
  }
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) {
1009
+ function checkClipBody(value, sourceFrames) {
856
1010
  if (!isRecord(value) || !isKey(value.key) || !isKey(value.source)) invalid("malformed-command", "a clip needs a key and a source");
857
1011
  onlyFields(value, CLIP_FIELDS, "a clip");
858
1012
  const clip = {
@@ -870,35 +1024,6 @@ function checkClip(value, sourceFrames) {
870
1024
  if (problem) invalid(problem, `clip ${clip.key} isn't valid within its source`);
871
1025
  return clip;
872
1026
  }
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
1027
  function fitFades(clip) {
903
1028
  const length = clipLength(clip);
904
1029
  const total = clip.fadeIn.frames + clip.fadeOut.frames;
@@ -915,194 +1040,500 @@ function fitFades(clip) {
915
1040
  }
916
1041
  };
917
1042
  }
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
1043
+ // src/core/format/document-parts.ts
1044
+ var AUDIO_PLAN_FORMAT = "hm-audio-plan";
1045
+ var SOURCE_FIELDS = ["frames", "asset"];
1046
+ var ASSET_FIELDS = [
1047
+ "asset",
1048
+ "mediaType",
1049
+ "size"
1050
+ ];
1051
+ var METADATA_FIELDS = [
1052
+ "title",
1053
+ "artist",
1054
+ "album",
1055
+ "year",
1056
+ "comment"
1057
+ ];
1058
+ var ASSET_ID = /^sha256:[0-9a-f]{64}$/;
1059
+ var MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;
1060
+ function malformed(message) {
1061
+ return invalid("malformed-command", message);
1062
+ }
1063
+ var isCount = (value, min) => Number.isSafeInteger(value) && value >= min;
1064
+ function readAsset(value) {
1065
+ if (!isRecord(value)) malformed("an asset is an object");
1066
+ onlyFields(value, ASSET_FIELDS, "an asset");
1067
+ const { asset, mediaType, size } = value;
1068
+ if (typeof asset !== "string" || !ASSET_ID.test(asset)) malformed("an asset id is sha256:<hex>");
1069
+ if (typeof mediaType !== "string" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) malformed("a media type is type/subtype, in lowercase");
1070
+ if (!isCount(size, 0)) malformed("an asset's size is a whole number of bytes");
1071
+ return {
1072
+ asset,
1073
+ mediaType,
1074
+ size
1075
+ };
1076
+ }
1077
+ function readSources(value) {
1078
+ if (!isRecord(value) || Array.isArray(value)) malformed("sources is an object");
1079
+ return Object.fromEntries(Object.entries(value).map(([id, source]) => {
1080
+ if (!isKey(id)) malformed("a source id is a non-empty string");
1081
+ if (!isRecord(source)) malformed("a source is an object");
1082
+ onlyFields(source, SOURCE_FIELDS, "a source");
1083
+ if (!isCount(source.frames, 1)) malformed("a source's frames are a whole number above 0");
1084
+ return [id, source.asset === void 0 ? { frames: source.frames } : {
1085
+ frames: source.frames,
1086
+ asset: readAsset(source.asset)
1087
+ }];
1088
+ }));
1089
+ }
1090
+ function readMetadata(value) {
1091
+ if (!isRecord(value)) malformed("metadata is an object");
1092
+ onlyFields(value, METADATA_FIELDS, "metadata");
1093
+ const fields = METADATA_FIELDS.map((field) => {
1094
+ const text = value[field];
1095
+ if (typeof text !== "string") malformed(`metadata.${field} is text`);
1096
+ if (longerThan(text, 1e3)) invalid("metadata-too-long", `metadata.${field} is over ${MAX_METADATA_LENGTH} code points`);
1097
+ return [field, text];
927
1098
  });
1099
+ return Object.fromEntries(fields);
1100
+ }
1101
+ // src/core/operations/commands.ts
1102
+ function refuse(reason, message) {
1103
+ throw new Invalid(reason, message);
1104
+ }
1105
+ var COMMAND_FIELDS = {
1106
+ "audio.insertClips": ["track", "clips"],
1107
+ "audio.removeClips": ["keys"],
1108
+ "audio.trimClip": [
1109
+ "key",
1110
+ "start",
1111
+ "end"
1112
+ ],
1113
+ "audio.splitClip": [
1114
+ "key",
1115
+ "at",
1116
+ "newKey"
1117
+ ],
1118
+ "audio.moveClips": [
1119
+ "keys",
1120
+ "by",
1121
+ "track"
1122
+ ],
1123
+ "audio.setGain": ["keys", "gainDb"],
1124
+ "audio.setFade": [
1125
+ "key",
1126
+ "edge",
1127
+ "frames",
1128
+ "curve"
1129
+ ],
1130
+ "audio.deleteRange": [
1131
+ "start",
1132
+ "end",
1133
+ "tracks",
1134
+ "ripple",
1135
+ "newKeys"
1136
+ ],
1137
+ "audio.keepRange": ["start", "end"],
1138
+ "audio.insertTime": [
1139
+ "at",
1140
+ "frames",
1141
+ "tracks",
1142
+ "newKeys"
1143
+ ],
1144
+ "audio.addTrack": [
1145
+ "key",
1146
+ "index",
1147
+ "name"
1148
+ ],
1149
+ "audio.removeTracks": ["keys"],
1150
+ "audio.moveTrack": ["key", "to"],
1151
+ "audio.setTrack": [
1152
+ "key",
1153
+ "name",
1154
+ "gainDb",
1155
+ "muted",
1156
+ "soloed"
1157
+ ],
1158
+ "audio.setMasterGain": ["gainDb"],
1159
+ "audio.setChannels": ["channels"],
1160
+ "audio.setMetadata": ["field", "value"],
1161
+ "audio.restoreClips": ["entries"],
1162
+ "audio.updateClips": ["clips"],
1163
+ "audio.placeClips": ["entries"],
1164
+ "audio.replaceClips": ["edits"],
1165
+ "audio.restoreTracks": ["entries"]
1166
+ };
1167
+ var TRACK_FIELDS = [
1168
+ "key",
1169
+ "name",
1170
+ "gainDb",
1171
+ "muted",
1172
+ "soloed",
1173
+ "clips"
1174
+ ];
1175
+ var isFrames = (value) => Number.isSafeInteger(value) && value >= 0;
1176
+ function checkGain(value) {
1177
+ if (typeof value !== "number" || !(value >= -120 && value <= 120)) refuse("gain-out-of-range", `gain must be from ${MIN_GAIN_DB} to 120 dB`);
1178
+ return value;
1179
+ }
1180
+ function checkName(value) {
1181
+ if (typeof value !== "string") refuse("malformed-command", "a track's name must be text");
1182
+ if (longerThan(value, 100)) refuse("name-too-long", `a track's name can have at most 100 code points`);
1183
+ return value;
928
1184
  }
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
1185
+ function checkFlag(value, name) {
1186
+ if (typeof value !== "boolean") refuse("malformed-command", `${name} must be true or false`);
1187
+ return value;
1188
+ }
1189
+ function checkClip(value, sourceFrames) {
1190
+ if (!isRecord(value)) refuse("malformed-command", "a clip is an object");
1191
+ const clip = checkClipBody({
1192
+ ...value,
1193
+ at: void 0
1194
+ }, sourceFrames);
1195
+ const { at } = value;
1196
+ if (!isFrames(at) || !Number.isSafeInteger(at + (clip.end - clip.start))) refuse("invalid-frames", `clip ${clip.key}'s position isn't a whole number of frames`);
1197
+ return {
1198
+ key: clip.key,
1199
+ at,
1200
+ source: clip.source,
1201
+ start: clip.start,
1202
+ end: clip.end,
1203
+ gainDb: clip.gainDb,
1204
+ fadeIn: clip.fadeIn,
1205
+ fadeOut: clip.fadeOut
938
1206
  };
939
1207
  }
940
- function withClips(plan, clips) {
1208
+ function checkClips(values, sourceFrames) {
1209
+ if (!Array.isArray(values)) refuse("malformed-command", "clips must be a list");
1210
+ return values.map((value) => checkClip(value, sourceFrames));
1211
+ }
1212
+ function checkOrder(clips) {
1213
+ const problem = orderProblem(clips);
1214
+ if (problem === "clips-overlap") refuse(problem, "two clips on a track would overlap");
1215
+ if (problem) refuse(problem, "a track's clips must be in time order");
1216
+ }
1217
+ function sorted(clips) {
1218
+ return [...clips].sort((a, b) => a.at - b.at);
1219
+ }
1220
+ function checkTrack(value, sourceFrames) {
1221
+ if (!isRecord(value) || !isKey(value.key)) refuse("malformed-command", "a track needs a key");
1222
+ onlyFields(value, TRACK_FIELDS, "a track");
1223
+ const clips = checkClips(value.clips, sourceFrames);
1224
+ checkOrder(clips);
941
1225
  return {
942
- ...plan,
1226
+ key: value.key,
1227
+ name: checkName(value.name),
1228
+ gainDb: checkGain(value.gainDb),
1229
+ muted: checkFlag(value.muted, "muted"),
1230
+ soloed: checkFlag(value.soloed, "soloed"),
943
1231
  clips
944
1232
  };
945
1233
  }
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));
1234
+ function keysOf$1(plan) {
1235
+ const keys = /* @__PURE__ */ new Set();
1236
+ for (const track of plan.tracks) {
1237
+ keys.add(track.key);
1238
+ for (const clip of track.clips) keys.add(clip.key);
1239
+ }
1240
+ return keys;
1241
+ }
1242
+ function checkUniqueKeys(plan) {
1243
+ const seen = /* @__PURE__ */ new Set();
1244
+ const once = (key) => {
1245
+ if (seen.has(key)) refuse("duplicate-key", `the key ${key} appears twice`);
1246
+ seen.add(key);
1247
+ };
1248
+ for (const track of plan.tracks) {
1249
+ once(track.key);
1250
+ for (const clip of track.clips) once(clip.key);
1251
+ }
1252
+ }
1253
+ function claim(keys, taken) {
1254
+ const before = new Set(taken);
1255
+ for (const key of keys) {
1256
+ if (!isKey(key)) refuse("malformed-command", "a key must be a non-empty string");
1257
+ if (before.has(key)) refuse("key-taken", `the key ${key} is taken`);
1258
+ if (taken.has(key)) refuse("duplicate-key", `the key ${key} appears twice`);
1259
+ taken.add(key);
1260
+ }
1261
+ }
1262
+ function keyList(value, empty) {
1263
+ if (!Array.isArray(value)) refuse("malformed-command", "keys must be a list");
1264
+ if (value.length === 0) refuse(empty, "it needs at least one");
1265
+ const seen = /* @__PURE__ */ new Set();
1266
+ for (const key of value) {
1267
+ if (!isKey(key)) refuse("malformed-command", "a key must be a non-empty string");
1268
+ if (seen.has(key)) refuse("duplicate-key", `the key ${key} appears twice`);
1269
+ seen.add(key);
1270
+ }
1271
+ return value;
1272
+ }
1273
+ function trackIndex(plan, key) {
1274
+ if (!isKey(key)) refuse("malformed-command", "a track is named by its key");
1275
+ const index = plan.tracks.findIndex((track) => track.key === key);
1276
+ if (index < 0) refuse("unknown-track", `the plan has no track ${key}`);
1277
+ return index;
1278
+ }
1279
+ function trackIndexes(plan, keys) {
1280
+ return keyList(keys, "no-tracks").map((key) => trackIndex(plan, key));
1281
+ }
1282
+ function locateClips(plan, keys) {
1283
+ const wanted = new Set(keyList(keys, "no-clips"));
1284
+ const found = [];
1285
+ plan.tracks.forEach((track, index) => {
1286
+ for (const clip of track.clips) if (wanted.has(clip.key)) found.push({
1287
+ track: index,
1288
+ clip
1289
+ });
1290
+ });
1291
+ if (found.length !== wanted.size) refuse("unknown-clip", "the plan doesn't have every clip");
1292
+ return found;
1293
+ }
1294
+ function locateClip(plan, key) {
1295
+ return locateClips(plan, [key])[0];
1296
+ }
1297
+ function withClips(plan, changes) {
1298
+ if (changes.size === 0) return plan;
1299
+ return {
1300
+ ...plan,
1301
+ tracks: plan.tracks.map((track, index) => {
1302
+ const clips = changes.get(index);
1303
+ return clips ? {
1304
+ ...track,
1305
+ clips
1306
+ } : track;
1307
+ })
1308
+ };
1309
+ }
1310
+ function withUpdated(plan, clips) {
1311
+ const byKey = new Map(clips.map((clip) => [clip.key, clip]));
1312
+ const changes = /* @__PURE__ */ new Map();
1313
+ plan.tracks.forEach((track, index) => {
1314
+ if (track.clips.some((clip) => byKey.has(clip.key))) {
1315
+ const next = track.clips.map((clip) => byKey.get(clip.key) ?? clip);
1316
+ checkOrder(next);
1317
+ changes.set(index, next);
1318
+ }
1319
+ });
1320
+ return withClips(plan, changes);
1321
+ }
1322
+ function cut(clip, from, to, key, at) {
1323
+ return fitFades({
1324
+ ...clip,
1325
+ key,
1326
+ at,
1327
+ start: clip.start + from,
1328
+ end: clip.start + to,
1329
+ fadeIn: from === 0 ? clip.fadeIn : NO_FADE,
1330
+ fadeOut: to === clip.end - clip.start ? clip.fadeOut : NO_FADE
1331
+ });
1332
+ }
1333
+ function shifted(clips, by) {
1334
+ if (by === 0) return [...clips];
1335
+ return clips.map((clip) => {
1336
+ const at = clip.at + by;
1337
+ if (at < 0) refuse("frame-outside-plan", "a clip can't start before the timeline does");
1338
+ if (!Number.isSafeInteger(at + (clip.end - clip.start))) refuse("invalid-frames", "a clip's position isn't a whole number of frames");
1339
+ return {
1340
+ ...clip,
1341
+ at
1342
+ };
1343
+ });
1344
+ }
1345
+ function checkRange(plan, start, end) {
1346
+ const length = planLength(plan);
1347
+ if (!isIndex(start, length) || !isIndex(end, length)) refuse("frame-outside-plan", "the range must be inside the plan");
1348
+ if (end <= start) refuse("empty-range", "the range must be at least one frame long");
1349
+ return [start, end];
1350
+ }
1351
+ function newKeysFor(value, tracks) {
1352
+ const keys = /* @__PURE__ */ new Map();
1353
+ if (value === void 0) return keys;
1354
+ if (!isRecord(value) || Array.isArray(value)) refuse("malformed-command", "newKeys is an object of keys, by track");
1355
+ for (const [track, key] of Object.entries(value)) {
1356
+ if (!isKey(track) || !isKey(key)) refuse("malformed-command", "newKeys is an object of keys, by track");
1357
+ if (!tracks.includes(track)) refuse("unknown-track", `the command doesn't edit track ${track}`);
1358
+ keys.set(track, key);
1359
+ }
1360
+ return keys;
1361
+ }
1362
+ function place(plan, placements) {
1363
+ const arriving = /* @__PURE__ */ new Map();
1364
+ const changes = /* @__PURE__ */ new Map();
1365
+ plan.tracks.forEach((track, index) => {
1366
+ const staying = [];
1367
+ for (const clip of track.clips) {
1368
+ const to = placements.get(clip.key);
1369
+ if (!to) {
1370
+ staying.push(clip);
1371
+ continue;
1372
+ }
1373
+ const moved = shifted([clip], to.at - clip.at);
1374
+ arriving.set(to.track, [...arriving.get(to.track) ?? [], ...moved]);
1375
+ }
1376
+ if (staying.length !== track.clips.length) changes.set(index, staying);
1377
+ });
1378
+ for (const [index, clips] of arriving) {
1379
+ const base = changes.get(index) ?? plan.tracks[index].clips;
1380
+ changes.set(index, sorted([...base, ...clips]));
1381
+ }
1382
+ for (const clips of changes.values()) checkOrder(clips);
1383
+ return withClips(plan, changes);
1384
+ }
1385
+ function timeEdit(plan, edit) {
1386
+ return {
1387
+ state: withClips(plan, edit.changes),
1388
+ inverse: {
1389
+ type: "audio.replaceClips",
1390
+ edits: edit.undo
1391
+ }
1392
+ };
956
1393
  }
957
1394
  function apply(plan, command, sourceFrames) {
958
- if (!isRecord(command)) invalid("malformed-command", "a command is an object");
1395
+ if (!isRecord(command)) refuse("malformed-command", "a command is an object");
959
1396
  const fields = Object.hasOwn(COMMAND_FIELDS, command.type) ? COMMAND_FIELDS[command.type] : void 0;
960
- if (!fields) invalid("unknown-command", "unknown command");
1397
+ if (!fields) refuse("unknown-command", "unknown command");
961
1398
  onlyFields(command, ["type", ...fields], command.type);
962
1399
  switch (command.type) {
963
1400
  case "audio.insertClips": {
1401
+ const index = trackIndex(plan, command.track);
964
1402
  const clips = checkClips(command.clips, sourceFrames);
965
- if (clips.length === 0) invalid("no-clips", "it needs at least one clip");
1403
+ if (clips.length === 0) refuse("no-clips", "it needs at least one clip");
966
1404
  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
- ];
1405
+ claim(keys, keysOf$1(plan));
1406
+ const next = sorted([...plan.tracks[index].clips, ...clips]);
1407
+ checkOrder(next);
987
1408
  return {
988
- state: splice(plan, index, 1, parts),
1409
+ state: withClips(plan, /* @__PURE__ */ new Map([[index, next]])),
989
1410
  inverse: {
990
- type: "audio.replaceClips",
991
- index,
992
- count: parts.length,
993
- clips: [split]
1411
+ type: "audio.removeClips",
1412
+ keys
994
1413
  }
995
1414
  };
996
1415
  }
997
1416
  case "audio.removeClips": {
998
- const at = positions(plan, command.keys);
999
- const removed = new Set(at);
1417
+ const found = locateClips(plan, command.keys);
1418
+ const removed = new Set(found.map(({ clip }) => clip.key));
1419
+ const changes = /* @__PURE__ */ new Map();
1420
+ for (const { track } of found) changes.set(track, plan.tracks[track].clips.filter((clip) => !removed.has(clip.key)));
1000
1421
  return {
1001
- state: withClips(plan, plan.clips.filter((_, index) => !removed.has(index))),
1422
+ state: withClips(plan, changes),
1002
1423
  inverse: {
1003
1424
  type: "audio.restoreClips",
1004
- entries: at.map((index) => ({
1005
- index,
1006
- clip: plan.clips[index]
1425
+ entries: found.map(({ track, clip }) => ({
1426
+ track: plan.tracks[track].key,
1427
+ clip
1007
1428
  }))
1008
1429
  }
1009
1430
  };
1010
1431
  }
1011
1432
  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;
1433
+ if (!Array.isArray(command.entries)) refuse("malformed-command", "entries must be a list");
1434
+ if (command.entries.length === 0) refuse("no-clips", "it needs at least one clip");
1435
+ const arriving = /* @__PURE__ */ new Map();
1436
+ const keys = [];
1437
+ for (const entry of command.entries) {
1438
+ if (!isRecord(entry)) refuse("malformed-command", "an entry needs a track and a clip");
1439
+ onlyFields(entry, ["track", "clip"], "an entry");
1440
+ const index = trackIndex(plan, entry.track);
1441
+ const clip = checkClip(entry.clip, sourceFrames);
1442
+ keys.push(clip.key);
1443
+ arriving.set(index, [...arriving.get(index) ?? [], clip]);
1444
+ }
1445
+ claim(keys, keysOf$1(plan));
1446
+ const changes = /* @__PURE__ */ new Map();
1447
+ for (const [index, clips] of arriving) {
1448
+ const next = sorted([...plan.tracks[index].clips, ...clips]);
1449
+ checkOrder(next);
1450
+ changes.set(index, next);
1029
1451
  }
1030
1452
  return {
1031
- state: withClips(plan, clips),
1453
+ state: withClips(plan, changes),
1032
1454
  inverse: {
1033
1455
  type: "audio.removeClips",
1034
- keys: entries.map(({ clip }) => clip.key)
1456
+ keys
1035
1457
  }
1036
1458
  };
1037
1459
  }
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");
1460
+ case "audio.updateClips": {
1041
1461
  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));
1462
+ const before = locateClips(plan, clips.map((clip) => clip.key)).map(({ clip }) => clip);
1045
1463
  return {
1046
- state: splice(plan, index, count, clips),
1464
+ state: withUpdated(plan, clips),
1047
1465
  inverse: {
1048
- type: "audio.replaceClips",
1049
- index,
1050
- count: clips.length,
1051
- clips: removed
1466
+ type: "audio.updateClips",
1467
+ clips: before
1052
1468
  }
1053
1469
  };
1054
1470
  }
1055
- case "audio.updateClips": {
1056
- const clips = checkClips(command.clips, sourceFrames);
1057
- const at = positions(plan, clips.map((clip) => clip.key));
1471
+ case "audio.placeClips": {
1472
+ if (!Array.isArray(command.entries)) refuse("malformed-command", "entries must be a list");
1473
+ const placements = /* @__PURE__ */ new Map();
1474
+ const keys = [];
1475
+ for (const entry of command.entries) {
1476
+ if (!isRecord(entry)) refuse("malformed-command", "an entry needs a key, a track and a position");
1477
+ onlyFields(entry, [
1478
+ "key",
1479
+ "track",
1480
+ "at"
1481
+ ], "an entry");
1482
+ if (!isFrames(entry.at)) refuse("invalid-frames", "a position is a whole number of frames");
1483
+ keys.push(entry.key);
1484
+ if (isKey(entry.key)) placements.set(entry.key, {
1485
+ track: trackIndex(plan, entry.track),
1486
+ at: entry.at
1487
+ });
1488
+ }
1489
+ const found = locateClips(plan, keys);
1058
1490
  return {
1059
- state: updateByKey(plan, clips),
1491
+ state: place(plan, placements),
1060
1492
  inverse: {
1061
- type: "audio.updateClips",
1062
- clips: at.map((index) => plan.clips[index])
1493
+ type: "audio.placeClips",
1494
+ entries: found.map(({ track, clip }) => ({
1495
+ key: clip.key,
1496
+ track: plan.tracks[track].key,
1497
+ at: clip.at
1498
+ }))
1063
1499
  }
1064
1500
  };
1065
1501
  }
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;
1502
+ case "audio.moveClips": {
1503
+ const { by } = command;
1504
+ if (!Number.isSafeInteger(by)) refuse("malformed-command", "by is a whole number of frames");
1505
+ const found = locateClips(plan, command.keys);
1506
+ const to = command.track === void 0 ? void 0 : trackIndex(plan, command.track);
1087
1507
  return {
1088
- state: splice(plan, first.index, count, kept),
1508
+ state: place(plan, new Map(found.map(({ track, clip }) => [clip.key, {
1509
+ track: to ?? track,
1510
+ at: clip.at + by
1511
+ }]))),
1089
1512
  inverse: {
1090
- type: "audio.replaceClips",
1091
- index: first.index,
1092
- count: kept.length,
1093
- clips: plan.clips.slice(first.index, first.index + count)
1513
+ type: "audio.placeClips",
1514
+ entries: found.map(({ track, clip }) => ({
1515
+ key: clip.key,
1516
+ track: plan.tracks[track].key,
1517
+ at: clip.at
1518
+ }))
1094
1519
  }
1095
1520
  };
1096
1521
  }
1097
1522
  case "audio.trimClip": {
1098
- const index = position(plan, command.key);
1099
- const clip = plan.clips[index];
1523
+ const { track, clip } = locateClip(plan, command.key);
1524
+ const { start, end } = command;
1525
+ const at = isFrames(start) ? clip.at + (start - clip.start) : clip.at;
1526
+ if (at < 0) refuse("frame-outside-plan", "a clip can't start before the timeline does");
1527
+ const trimmed = checkClip(fitFades({
1528
+ ...clip,
1529
+ at,
1530
+ start,
1531
+ end
1532
+ }), sourceFrames);
1533
+ const clips = sorted(plan.tracks[track].clips.map((entry) => entry.key === clip.key ? trimmed : entry));
1534
+ checkOrder(clips);
1100
1535
  return {
1101
- state: updateByKey(plan, [checkClip(fitFades({
1102
- ...clip,
1103
- start: command.start,
1104
- end: command.end
1105
- }), sourceFrames)]),
1536
+ state: withClips(plan, /* @__PURE__ */ new Map([[track, clips]])),
1106
1537
  inverse: {
1107
1538
  type: "audio.updateClips",
1108
1539
  clips: [clip]
@@ -1110,57 +1541,39 @@ function apply(plan, command, sourceFrames) {
1110
1541
  };
1111
1542
  }
1112
1543
  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));
1544
+ const { track, clip } = locateClip(plan, command.key);
1545
+ const { at } = command;
1546
+ if (!isIndex(at, planLength(plan))) refuse("frame-outside-plan", "the frame is outside the plan");
1547
+ if (at <= clip.at || at >= clipEnd(clip)) refuse("not-inside-clip", "the frame must be strictly inside the clip");
1548
+ claim([command.newKey], keysOf$1(plan));
1549
+ const newKey = command.newKey;
1550
+ const length = clip.end - clip.start;
1551
+ const parts = [cut(clip, 0, at - clip.at, clip.key, clip.at), cut(clip, at - clip.at, length, newKey, at)];
1552
+ const clips = plan.tracks[track].clips;
1553
+ const index = clips.indexOf(clip);
1118
1554
  return {
1119
- state: splice(plan, index, 1, [part(clip, 0, offset, clip.key), part(clip, offset, clipLength(clip), command.newKey)]),
1555
+ state: withClips(plan, /* @__PURE__ */ new Map([[track, [
1556
+ ...clips.slice(0, index),
1557
+ ...parts,
1558
+ ...clips.slice(index + 1)
1559
+ ]]])),
1120
1560
  inverse: {
1121
1561
  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)
1562
+ edits: [{
1563
+ track: plan.tracks[track].key,
1564
+ index,
1565
+ count: 2,
1566
+ clips: [clip],
1567
+ shift: 0
1568
+ }]
1154
1569
  }
1155
1570
  };
1156
1571
  }
1157
1572
  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]);
1573
+ const gainDb = checkGain(command.gainDb);
1574
+ const before = locateClips(plan, command.keys).map(({ clip }) => clip);
1162
1575
  return {
1163
- state: updateByKey(plan, before.map((clip) => ({
1576
+ state: withUpdated(plan, before.map((clip) => ({
1164
1577
  ...clip,
1165
1578
  gainDb
1166
1579
  }))),
@@ -1171,9 +1584,9 @@ function apply(plan, command, sourceFrames) {
1171
1584
  };
1172
1585
  }
1173
1586
  case "audio.setFade": {
1174
- const clip = plan.clips[position(plan, command.key)];
1587
+ const { clip } = locateClip(plan, command.key);
1175
1588
  const { edge, frames } = command;
1176
- if (edge !== "in" && edge !== "out") invalid("invalid-edge", "the edge must be in or out");
1589
+ if (edge !== "in" && edge !== "out") refuse("invalid-edge", "the edge must be in or out");
1177
1590
  const next = {
1178
1591
  frames,
1179
1592
  curve: fade({
@@ -1182,7 +1595,7 @@ function apply(plan, command, sourceFrames) {
1182
1595
  }, "the fade").curve
1183
1596
  };
1184
1597
  return {
1185
- state: updateByKey(plan, [checkClip(edge === "in" ? {
1598
+ state: withUpdated(plan, [checkClip(edge === "in" ? {
1186
1599
  ...clip,
1187
1600
  fadeIn: next
1188
1601
  } : {
@@ -1195,11 +1608,320 @@ function apply(plan, command, sourceFrames) {
1195
1608
  }
1196
1609
  };
1197
1610
  }
1611
+ case "audio.deleteRange": {
1612
+ const [start, end] = checkRange(plan, command.start, command.end);
1613
+ const indexes = trackIndexes(plan, command.tracks);
1614
+ const ripple = checkFlag(command.ripple, "ripple");
1615
+ const newKeys = newKeysFor(command.newKeys, command.tracks);
1616
+ const taken = keysOf$1(plan);
1617
+ const edit = {
1618
+ changes: /* @__PURE__ */ new Map(),
1619
+ undo: []
1620
+ };
1621
+ indexes.forEach((index) => {
1622
+ const track = plan.tracks[index];
1623
+ const { clips } = track;
1624
+ const first = clipIndexAt(clips, start);
1625
+ let after = first;
1626
+ while (after < clips.length && clips[after].at < end) after += 1;
1627
+ const kept = [];
1628
+ if (after > first) {
1629
+ const head = clips[first];
1630
+ const tail = clips[after - 1];
1631
+ if (head.at < start) kept.push(cut(head, 0, start - head.at, head.key, head.at));
1632
+ if (clipEnd(tail) > end) {
1633
+ let key = tail.key;
1634
+ if (kept.length > 0 && tail === head) {
1635
+ const newKey = newKeys.get(track.key);
1636
+ if (newKey === void 0) refuse("new-key-required", "deleting inside a clip needs a new key for its track");
1637
+ claim([newKey], taken);
1638
+ key = newKey;
1639
+ }
1640
+ kept.push(cut(tail, end - tail.at, tail.end - tail.start, key, ripple ? start : end));
1641
+ }
1642
+ }
1643
+ const rest = clips.slice(after);
1644
+ const shift = ripple && rest.length > 0 ? start - end : 0;
1645
+ if (after === first && shift === 0) return;
1646
+ edit.changes.set(index, [
1647
+ ...clips.slice(0, first),
1648
+ ...kept,
1649
+ ...shifted(rest, shift)
1650
+ ]);
1651
+ edit.undo.push({
1652
+ track: track.key,
1653
+ index: first,
1654
+ count: kept.length,
1655
+ clips: clips.slice(first, after),
1656
+ shift: shift === 0 ? 0 : -shift
1657
+ });
1658
+ });
1659
+ return timeEdit(plan, edit);
1660
+ }
1661
+ case "audio.keepRange": {
1662
+ const [start, end] = checkRange(plan, command.start, command.end);
1663
+ const edit = {
1664
+ changes: /* @__PURE__ */ new Map(),
1665
+ undo: []
1666
+ };
1667
+ plan.tracks.forEach((track, index) => {
1668
+ const { clips } = track;
1669
+ if (clips.length === 0) return;
1670
+ const kept = [];
1671
+ for (const clip of clips) {
1672
+ const from = Math.max(clip.at, start);
1673
+ const to = Math.min(clipEnd(clip), end);
1674
+ if (to > from) kept.push(cut(clip, from - clip.at, to - clip.at, clip.key, from - start));
1675
+ }
1676
+ edit.changes.set(index, kept);
1677
+ edit.undo.push({
1678
+ track: track.key,
1679
+ index: 0,
1680
+ count: kept.length,
1681
+ clips,
1682
+ shift: 0
1683
+ });
1684
+ });
1685
+ return timeEdit(plan, edit);
1686
+ }
1687
+ case "audio.insertTime": {
1688
+ const { at, frames } = command;
1689
+ if (!isFrames(frames) || frames < 1) refuse("invalid-frames", "the time to insert is a whole number of frames, at least one");
1690
+ if (!isIndex(at, planLength(plan))) refuse("frame-outside-plan", "the frame is outside the plan");
1691
+ const indexes = trackIndexes(plan, command.tracks);
1692
+ const newKeys = newKeysFor(command.newKeys, command.tracks);
1693
+ const taken = keysOf$1(plan);
1694
+ const edit = {
1695
+ changes: /* @__PURE__ */ new Map(),
1696
+ undo: []
1697
+ };
1698
+ indexes.forEach((index) => {
1699
+ const track = plan.tracks[index];
1700
+ const { clips } = track;
1701
+ const first = clipIndexAt(clips, at);
1702
+ const across = clips[first];
1703
+ if (across && across.at < at) {
1704
+ const newKey = newKeys.get(track.key);
1705
+ if (newKey === void 0) refuse("new-key-required", "inserting time inside a clip needs a new key for its track");
1706
+ claim([newKey], taken);
1707
+ const parts = [cut(across, 0, at - across.at, across.key, across.at), ...shifted([cut(across, at - across.at, across.end - across.start, newKey, at)], frames)];
1708
+ edit.changes.set(index, [
1709
+ ...clips.slice(0, first),
1710
+ ...parts,
1711
+ ...shifted(clips.slice(first + 1), frames)
1712
+ ]);
1713
+ edit.undo.push({
1714
+ track: track.key,
1715
+ index: first,
1716
+ count: 2,
1717
+ clips: [across],
1718
+ shift: -frames
1719
+ });
1720
+ return;
1721
+ }
1722
+ const rest = clips.slice(first);
1723
+ if (rest.length === 0) return;
1724
+ edit.changes.set(index, [...clips.slice(0, first), ...shifted(rest, frames)]);
1725
+ edit.undo.push({
1726
+ track: track.key,
1727
+ index: first,
1728
+ count: 0,
1729
+ clips: [],
1730
+ shift: -frames
1731
+ });
1732
+ });
1733
+ return timeEdit(plan, edit);
1734
+ }
1735
+ case "audio.replaceClips": {
1736
+ if (!Array.isArray(command.edits)) refuse("malformed-command", "edits must be a list");
1737
+ const edit = {
1738
+ changes: /* @__PURE__ */ new Map(),
1739
+ undo: []
1740
+ };
1741
+ for (const value of command.edits) {
1742
+ if (!isRecord(value)) refuse("malformed-command", "an edit is an object");
1743
+ onlyFields(value, [
1744
+ "track",
1745
+ "index",
1746
+ "count",
1747
+ "clips",
1748
+ "shift"
1749
+ ], "an edit");
1750
+ const index = trackIndex(plan, value.track);
1751
+ if (edit.changes.has(index)) refuse("duplicate-key", "a track is edited twice");
1752
+ const track = plan.tracks[index];
1753
+ const { index: from, count, shift } = value;
1754
+ if (!isIndex(from, track.clips.length) || !isIndex(count, track.clips.length - from)) refuse("invalid-index", "the run of clips is outside the track");
1755
+ if (!Number.isSafeInteger(shift)) refuse("malformed-command", "shift is a whole number of frames");
1756
+ const clips = checkClips(value.clips, sourceFrames);
1757
+ const next = [
1758
+ ...track.clips.slice(0, from),
1759
+ ...clips,
1760
+ ...shifted(track.clips.slice(from + count), shift)
1761
+ ];
1762
+ checkOrder(next);
1763
+ edit.changes.set(index, next);
1764
+ edit.undo.push({
1765
+ track: track.key,
1766
+ index: from,
1767
+ count: clips.length,
1768
+ clips: track.clips.slice(from, from + count),
1769
+ shift: shift === 0 ? 0 : -shift
1770
+ });
1771
+ }
1772
+ const applied = timeEdit(plan, edit);
1773
+ checkUniqueKeys(applied.state);
1774
+ return applied;
1775
+ }
1776
+ case "audio.addTrack": {
1777
+ const { key, index } = command;
1778
+ const name = command.name === void 0 ? "" : checkName(command.name);
1779
+ claim([key], keysOf$1(plan));
1780
+ if (!isIndex(index, plan.tracks.length)) refuse("invalid-index", "the track can't go there");
1781
+ const track = {
1782
+ key,
1783
+ name,
1784
+ gainDb: 0,
1785
+ muted: false,
1786
+ soloed: false,
1787
+ clips: []
1788
+ };
1789
+ return {
1790
+ state: {
1791
+ ...plan,
1792
+ tracks: [
1793
+ ...plan.tracks.slice(0, index),
1794
+ track,
1795
+ ...plan.tracks.slice(index)
1796
+ ]
1797
+ },
1798
+ inverse: {
1799
+ type: "audio.removeTracks",
1800
+ keys: [track.key]
1801
+ }
1802
+ };
1803
+ }
1804
+ case "audio.removeTracks": {
1805
+ const removed = new Set(trackIndexes(plan, command.keys));
1806
+ if (removed.size === plan.tracks.length) refuse("last-track", "a plan keeps at least one track");
1807
+ return {
1808
+ state: {
1809
+ ...plan,
1810
+ tracks: plan.tracks.filter((_, index) => !removed.has(index))
1811
+ },
1812
+ inverse: {
1813
+ type: "audio.restoreTracks",
1814
+ entries: [...removed].sort((a, b) => a - b).map((index) => ({
1815
+ index,
1816
+ track: plan.tracks[index]
1817
+ }))
1818
+ }
1819
+ };
1820
+ }
1821
+ case "audio.restoreTracks": {
1822
+ if (!Array.isArray(command.entries)) refuse("malformed-command", "entries must be a list");
1823
+ if (command.entries.length === 0) refuse("no-tracks", "it needs at least one track");
1824
+ const tracks = [...plan.tracks];
1825
+ const keys = [];
1826
+ let previous = -1;
1827
+ for (const entry of command.entries) {
1828
+ if (!isRecord(entry)) refuse("malformed-command", "an entry needs an index and a track");
1829
+ onlyFields(entry, ["index", "track"], "an entry");
1830
+ const track = checkTrack(entry.track, sourceFrames);
1831
+ const { index } = entry;
1832
+ if (!isIndex(index, tracks.length) || index <= previous) refuse("invalid-index", `track ${track.key} can't be restored at that index`);
1833
+ tracks.splice(index, 0, track);
1834
+ keys.push(track.key);
1835
+ previous = index;
1836
+ }
1837
+ const state = {
1838
+ ...plan,
1839
+ tracks
1840
+ };
1841
+ checkUniqueKeys(state);
1842
+ return {
1843
+ state,
1844
+ inverse: {
1845
+ type: "audio.removeTracks",
1846
+ keys
1847
+ }
1848
+ };
1849
+ }
1850
+ case "audio.moveTrack": {
1851
+ const from = trackIndex(plan, command.key);
1852
+ const { to } = command;
1853
+ if (!isIndex(to, plan.tracks.length - 1)) refuse("invalid-index", "the track can't go there");
1854
+ const tracks = plan.tracks.filter((_, index) => index !== from);
1855
+ tracks.splice(to, 0, plan.tracks[from]);
1856
+ return {
1857
+ state: {
1858
+ ...plan,
1859
+ tracks
1860
+ },
1861
+ inverse: {
1862
+ type: "audio.moveTrack",
1863
+ key: command.key,
1864
+ to: from
1865
+ }
1866
+ };
1867
+ }
1868
+ case "audio.setTrack": {
1869
+ const { name, gainDb, muted, soloed } = command;
1870
+ const next = {
1871
+ ...name === void 0 ? {} : { name: checkName(name) },
1872
+ ...gainDb === void 0 ? {} : { gainDb: checkGain(gainDb) },
1873
+ ...muted === void 0 ? {} : { muted: checkFlag(muted, "muted") },
1874
+ ...soloed === void 0 ? {} : { soloed: checkFlag(soloed, "soloed") }
1875
+ };
1876
+ const changed = Object.keys(next);
1877
+ if (changed.length === 0) refuse("empty-change", "it sets nothing");
1878
+ const index = trackIndex(plan, command.key);
1879
+ const track = plan.tracks[index];
1880
+ const before = Object.fromEntries(changed.map((field) => [field, track[field]]));
1881
+ return {
1882
+ state: {
1883
+ ...plan,
1884
+ tracks: plan.tracks.map((entry, at) => at === index ? {
1885
+ ...track,
1886
+ ...next
1887
+ } : entry)
1888
+ },
1889
+ inverse: {
1890
+ type: "audio.setTrack",
1891
+ key: track.key,
1892
+ ...before
1893
+ }
1894
+ };
1895
+ }
1896
+ case "audio.setMasterGain": return {
1897
+ state: {
1898
+ ...plan,
1899
+ gainDb: checkGain(command.gainDb)
1900
+ },
1901
+ inverse: {
1902
+ type: "audio.setMasterGain",
1903
+ gainDb: plan.gainDb
1904
+ }
1905
+ };
1906
+ case "audio.setChannels": {
1907
+ const { channels } = command;
1908
+ if (!isFrames(channels) || channels < 1) refuse("malformed-command", "channels is a whole number, at least one");
1909
+ return {
1910
+ state: {
1911
+ ...plan,
1912
+ channels
1913
+ },
1914
+ inverse: {
1915
+ type: "audio.setChannels",
1916
+ channels: plan.channels
1917
+ }
1918
+ };
1919
+ }
1198
1920
  case "audio.setMetadata": {
1199
1921
  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`);
1922
+ if (typeof field !== "string" || !Object.hasOwn(EMPTY_METADATA, field)) refuse("unknown-metadata-field", "there's no such metadata field");
1923
+ if (typeof value !== "string") refuse("malformed-command", "a metadata value must be text");
1924
+ if (longerThan(value, 1e3)) refuse("metadata-too-long", `a metadata value can have at most ${MAX_METADATA_LENGTH} code points`);
1203
1925
  return {
1204
1926
  state: {
1205
1927
  ...plan,
@@ -1215,7 +1937,7 @@ function apply(plan, command, sourceFrames) {
1215
1937
  }
1216
1938
  };
1217
1939
  }
1218
- default: return invalid("unknown-command", "unknown command");
1940
+ default: return refuse("unknown-command", "unknown command");
1219
1941
  }
1220
1942
  }
1221
1943
  function createPlanReducer(sourceFrames) {
@@ -1233,10 +1955,8 @@ function createPlanReducer(sourceFrames) {
1233
1955
  }
1234
1956
  };
1235
1957
  }
1236
- // src/core/format/plan-document.ts
1237
- var AUDIO_PLAN_FORMAT = "hm-audio-plan";
1238
- var AUDIO_PLAN_VERSION = 1;
1239
- var DOCUMENT_FIELDS = [
1958
+ // src/core/format/version-1.ts
1959
+ var DOCUMENT_FIELDS$1 = [
1240
1960
  "format",
1241
1961
  "version",
1242
1962
  "sampleRate",
@@ -1245,63 +1965,7 @@ var DOCUMENT_FIELDS = [
1245
1965
  "clips",
1246
1966
  "metadata"
1247
1967
  ];
1248
- var SOURCE_FIELDS = ["frames", "asset"];
1249
- var ASSET_FIELDS = [
1250
- "asset",
1251
- "mediaType",
1252
- "size"
1253
- ];
1254
- var METADATA_FIELDS = [
1255
- "title",
1256
- "artist",
1257
- "album",
1258
- "year",
1259
- "comment"
1260
- ];
1261
- var ASSET_ID = /^sha256:[0-9a-f]{64}$/;
1262
- var MEDIA_TYPE = /^[a-z0-9][a-z0-9!#$&^_.+-]*\/[a-z0-9][a-z0-9!#$&^_.+-]*$/;
1263
- function malformed(message) {
1264
- return invalid("malformed-command", message);
1265
- }
1266
- var isCount = (value, min) => Number.isSafeInteger(value) && value >= min;
1267
- function readAsset(value) {
1268
- if (!isRecord(value)) malformed("an asset is an object");
1269
- onlyFields(value, ASSET_FIELDS, "an asset");
1270
- const { asset, mediaType, size } = value;
1271
- if (typeof asset !== "string" || !ASSET_ID.test(asset)) malformed("an asset id is sha256:<hex>");
1272
- if (typeof mediaType !== "string" || mediaType.length > 255 || !MEDIA_TYPE.test(mediaType)) malformed("a media type is type/subtype, in lowercase");
1273
- if (!isCount(size, 0)) malformed("an asset's size is a whole number of bytes");
1274
- return {
1275
- asset,
1276
- mediaType,
1277
- size
1278
- };
1279
- }
1280
- function readSources(value) {
1281
- if (!isRecord(value) || Array.isArray(value)) malformed("sources is an object");
1282
- return Object.fromEntries(Object.entries(value).map(([id, source]) => {
1283
- if (!isKey(id)) malformed("a source id is a non-empty string");
1284
- if (!isRecord(source)) malformed("a source is an object");
1285
- onlyFields(source, SOURCE_FIELDS, "a source");
1286
- if (!isCount(source.frames, 1)) malformed("a source's frames are a whole number above 0");
1287
- return [id, source.asset === void 0 ? { frames: source.frames } : {
1288
- frames: source.frames,
1289
- asset: readAsset(source.asset)
1290
- }];
1291
- }));
1292
- }
1293
- function readMetadata(value) {
1294
- if (!isRecord(value)) malformed("metadata is an object");
1295
- onlyFields(value, METADATA_FIELDS, "metadata");
1296
- const fields = METADATA_FIELDS.map((field) => {
1297
- const text = value[field];
1298
- if (typeof text !== "string") malformed(`metadata.${field} is text`);
1299
- if (longerThan(text, 1e3)) invalid("metadata-too-long", `metadata.${field} is over ${MAX_METADATA_LENGTH} code points`);
1300
- return [field, text];
1301
- });
1302
- return Object.fromEntries(fields);
1303
- }
1304
- function read(value) {
1968
+ function readVersion1(value) {
1305
1969
  if (!isRecord(value) || Array.isArray(value)) malformed("a document is an object");
1306
1970
  const { format, version } = value;
1307
1971
  if (typeof format !== "string") malformed("format is text");
@@ -1314,13 +1978,13 @@ function read(value) {
1314
1978
  reason: "unknown-format-version"
1315
1979
  } });
1316
1980
  if (version !== 1) malformed("version is 1");
1317
- onlyFields(value, DOCUMENT_FIELDS, "a document");
1981
+ onlyFields(value, DOCUMENT_FIELDS$1, "a document");
1318
1982
  if (!isCount(value.sampleRate, 1)) malformed("sampleRate is a whole number above 0");
1319
1983
  if (!isCount(value.channels, 1)) malformed("channels is a whole number above 0");
1320
1984
  const sources = readSources(value.sources);
1321
1985
  if (!Array.isArray(value.clips)) malformed("clips is a list");
1322
1986
  const lookup = (id) => Object.hasOwn(sources, id) ? sources[id]?.frames : void 0;
1323
- const clips = value.clips.map((clip) => checkClip(clip, lookup));
1987
+ const clips = value.clips.map((clip) => checkClipBody(clip, lookup));
1324
1988
  const keys = /* @__PURE__ */ new Set();
1325
1989
  for (const { key } of clips) {
1326
1990
  if (keys.has(key)) invalid("duplicate-key", `two clips have the key ${key}`);
@@ -1336,6 +2000,273 @@ function read(value) {
1336
2000
  sources
1337
2001
  };
1338
2002
  }
2003
+ function readPlanDocumentV1(value) {
2004
+ try {
2005
+ return readVersion1(value);
2006
+ } catch (error) {
2007
+ if (!(error instanceof Invalid)) throw error;
2008
+ const reason = error.reason === "malformed-command" ? "malformed-document" : error.reason;
2009
+ throw new AudioError("INVALID_DOCUMENT", `Invalid ${AUDIO_PLAN_FORMAT} document: ${error.message}.`, { details: {
2010
+ format: AUDIO_PLAN_FORMAT,
2011
+ reason
2012
+ } });
2013
+ }
2014
+ }
2015
+ function trackKeyFor(clips) {
2016
+ const taken = new Set(clips.map((clip) => clip.key));
2017
+ let number = 1;
2018
+ while (taken.has(`t${number}`)) number += 1;
2019
+ return `t${number}`;
2020
+ }
2021
+ function migratePlan(plan) {
2022
+ let at = 0;
2023
+ const clips = plan.clips.map((clip) => {
2024
+ const placed = {
2025
+ key: clip.key,
2026
+ at,
2027
+ source: clip.source,
2028
+ start: clip.start,
2029
+ end: clip.end,
2030
+ gainDb: clip.gainDb,
2031
+ fadeIn: clip.fadeIn,
2032
+ fadeOut: clip.fadeOut
2033
+ };
2034
+ at += clip.end - clip.start;
2035
+ return placed;
2036
+ });
2037
+ return {
2038
+ sampleRate: plan.sampleRate,
2039
+ channels: plan.channels,
2040
+ gainDb: 0,
2041
+ tracks: [{
2042
+ key: trackKeyFor(plan.clips),
2043
+ name: "",
2044
+ gainDb: 0,
2045
+ muted: false,
2046
+ soloed: false,
2047
+ clips
2048
+ }],
2049
+ metadata: plan.metadata
2050
+ };
2051
+ }
2052
+ var isWhole = (value) => Number.isSafeInteger(value) && value >= 0;
2053
+ function migrateAudioCommand(command, plan) {
2054
+ try {
2055
+ return migrate(command, plan);
2056
+ } catch (error) {
2057
+ if (!(error instanceof Invalid)) throw error;
2058
+ throw new AudioError("INVALID_COMMAND", `Invalid command: ${error.message}.`, { details: { reason: error.reason } });
2059
+ }
2060
+ }
2061
+ function migrate(value, plan) {
2062
+ if (!isRecord(value)) refuse("malformed-command", "a command is an object");
2063
+ const track = plan.tracks[0];
2064
+ const tracks = [track.key];
2065
+ const command = value;
2066
+ const ripple = (start, end, newKey) => ({
2067
+ type: "audio.deleteRange",
2068
+ start,
2069
+ end,
2070
+ tracks,
2071
+ ripple: true,
2072
+ ...newKey === void 0 ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }
2073
+ });
2074
+ const open = (at, frames, newKey) => ({
2075
+ type: "audio.insertTime",
2076
+ at,
2077
+ frames,
2078
+ tracks,
2079
+ ...newKey === void 0 ? {} : { newKeys: Object.fromEntries([[track.key, newKey]]) }
2080
+ });
2081
+ const find = (keys) => {
2082
+ if (!Array.isArray(keys)) refuse("malformed-command", "keys must be a list");
2083
+ if (keys.length === 0) refuse("no-clips", "it needs at least one clip");
2084
+ if (new Set(keys).size !== keys.length) refuse("duplicate-key", "a clip appears twice");
2085
+ const found = track.clips.filter((clip) => keys.includes(clip.key));
2086
+ if (found.length !== keys.length) refuse("unknown-clip", "the plan doesn't have every clip");
2087
+ return found;
2088
+ };
2089
+ const lengthOf = (clip) => clip.end - clip.start;
2090
+ switch (command.type) {
2091
+ case "audio.insertClips": {
2092
+ const { at, clips, splitKey } = command;
2093
+ onlyFields(command, [
2094
+ "type",
2095
+ "at",
2096
+ "clips",
2097
+ "splitKey"
2098
+ ], command.type);
2099
+ if (splitKey !== void 0 && !isKey(splitKey)) refuse("malformed-command", "splitKey must be a non-empty string");
2100
+ if (!Array.isArray(clips)) refuse("malformed-command", "clips must be a list");
2101
+ if (clips.length === 0) refuse("no-clips", "it needs at least one clip");
2102
+ let next = isWhole(at) ? at : 0;
2103
+ let total = 0;
2104
+ const placed = clips.map((clip) => {
2105
+ const length = isRecord(clip) && isWhole(clip.start) && isWhole(clip.end) ? Math.max(0, clip.end - clip.start) : 0;
2106
+ const positioned = {
2107
+ ...clip,
2108
+ at: next
2109
+ };
2110
+ next += length;
2111
+ total += length;
2112
+ return positioned;
2113
+ });
2114
+ const insert = {
2115
+ type: "audio.insertClips",
2116
+ track: track.key,
2117
+ clips: placed
2118
+ };
2119
+ return total > 0 ? [open(at, total, splitKey), insert] : [insert];
2120
+ }
2121
+ case "audio.removeClips":
2122
+ onlyFields(command, ["type", "keys"], command.type);
2123
+ return find(command.keys).reverse().map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));
2124
+ case "audio.deleteRange":
2125
+ onlyFields(command, [
2126
+ "type",
2127
+ "start",
2128
+ "end",
2129
+ "newKey"
2130
+ ], command.type);
2131
+ return [ripple(command.start, command.end, command.newKey)];
2132
+ case "audio.trimClip": {
2133
+ onlyFields(command, [
2134
+ "type",
2135
+ "key",
2136
+ "start",
2137
+ "end"
2138
+ ], command.type);
2139
+ const { key, start, end } = command;
2140
+ const trim = {
2141
+ type: "audio.trimClip",
2142
+ key,
2143
+ start,
2144
+ end
2145
+ };
2146
+ const clip = track.clips.find((entry) => entry.key === key);
2147
+ if (!clip || !isWhole(start) || !isWhole(end) || end <= start) return [trim];
2148
+ const earlier = clip.start - start;
2149
+ const later = end - clip.end;
2150
+ const length = end - start;
2151
+ const last = track.clips.at(-1) === clip;
2152
+ const before = [];
2153
+ const after = [];
2154
+ if (earlier > 0) before.push(open(clip.at, earlier));
2155
+ if (later > 0 && !last) before.push(open(clip.at + Math.max(earlier, 0) + lengthOf(clip), later));
2156
+ if (earlier < 0) after.push(ripple(clip.at, clip.at - earlier));
2157
+ if (later < 0 && !last) after.push(ripple(clip.at + length, clip.at + length - later));
2158
+ return [
2159
+ ...before,
2160
+ trim,
2161
+ ...after
2162
+ ];
2163
+ }
2164
+ case "audio.splitClip": {
2165
+ onlyFields(command, [
2166
+ "type",
2167
+ "key",
2168
+ "at",
2169
+ "newKey"
2170
+ ], command.type);
2171
+ const { key, at, newKey } = command;
2172
+ return [{
2173
+ type: "audio.splitClip",
2174
+ key,
2175
+ at,
2176
+ newKey
2177
+ }];
2178
+ }
2179
+ case "audio.moveClips": {
2180
+ onlyFields(command, [
2181
+ "type",
2182
+ "keys",
2183
+ "to"
2184
+ ], command.type);
2185
+ const moved = find(command.keys);
2186
+ const rest = track.clips.filter((clip) => !moved.includes(clip));
2187
+ const { to } = command;
2188
+ if (!isWhole(to) || to > rest.length) refuse("invalid-index", "the clips can't move there");
2189
+ const removals = [...moved].reverse().map((clip) => ripple(clip.at, clip.at + lengthOf(clip)));
2190
+ let at = rest.slice(0, to).reduce((sum, clip) => sum + lengthOf(clip), 0);
2191
+ const from = at;
2192
+ const placed = moved.map((clip) => {
2193
+ const positioned = {
2194
+ ...clip,
2195
+ at
2196
+ };
2197
+ at += lengthOf(clip);
2198
+ return positioned;
2199
+ });
2200
+ return [
2201
+ ...removals,
2202
+ open(from, at - from),
2203
+ {
2204
+ type: "audio.insertClips",
2205
+ track: track.key,
2206
+ clips: placed
2207
+ }
2208
+ ];
2209
+ }
2210
+ case "audio.setGain":
2211
+ case "audio.setFade":
2212
+ case "audio.setMetadata": return [command];
2213
+ default: return refuse("unknown-command", "not a version 1 user command");
2214
+ }
2215
+ }
2216
+ // src/core/format/plan-document.ts
2217
+ var AUDIO_PLAN_VERSION = 2;
2218
+ var DOCUMENT_FIELDS = [
2219
+ "format",
2220
+ "version",
2221
+ "sampleRate",
2222
+ "channels",
2223
+ "gainDb",
2224
+ "sources",
2225
+ "tracks",
2226
+ "metadata"
2227
+ ];
2228
+ function read(value) {
2229
+ if (!isRecord(value) || Array.isArray(value)) malformed("a document is an object");
2230
+ const { format, version } = value;
2231
+ if (typeof format !== "string") malformed("format is text");
2232
+ if (format !== "hm-audio-plan") throw new AudioError("UNSUPPORTED_FORMAT", `This isn't an ${AUDIO_PLAN_FORMAT} document.`, { details: {
2233
+ format: AUDIO_PLAN_FORMAT,
2234
+ reason: "unknown-format"
2235
+ } });
2236
+ 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: {
2237
+ format: AUDIO_PLAN_FORMAT,
2238
+ reason: "unknown-format-version"
2239
+ } });
2240
+ if (version === 1) {
2241
+ const earlier = readPlanDocumentV1(value);
2242
+ return {
2243
+ plan: migratePlan(earlier.plan),
2244
+ sources: earlier.sources
2245
+ };
2246
+ }
2247
+ if (version !== 2) malformed("version is 1 or 2");
2248
+ onlyFields(value, DOCUMENT_FIELDS, "a document");
2249
+ if (!isCount(value.sampleRate, 1)) malformed("sampleRate is a whole number above 0");
2250
+ if (!isCount(value.channels, 1)) malformed("channels is a whole number above 0");
2251
+ const { gainDb } = value;
2252
+ if (typeof gainDb !== "number" || !(gainDb >= -120 && gainDb <= 120)) refuse("gain-out-of-range", "the master gain must be from -120 to 120 dB");
2253
+ const sources = readSources(value.sources);
2254
+ if (!Array.isArray(value.tracks)) malformed("tracks is a list");
2255
+ if (value.tracks.length === 0) refuse("no-tracks", "a plan has at least one track");
2256
+ const lookup = (id) => Object.hasOwn(sources, id) ? sources[id]?.frames : void 0;
2257
+ const plan = {
2258
+ sampleRate: value.sampleRate,
2259
+ channels: value.channels,
2260
+ gainDb,
2261
+ tracks: value.tracks.map((track) => checkTrack(track, lookup)),
2262
+ metadata: readMetadata(value.metadata)
2263
+ };
2264
+ checkUniqueKeys(plan);
2265
+ return {
2266
+ plan,
2267
+ sources
2268
+ };
2269
+ }
1339
2270
  function readAudioPlanDocument(value) {
1340
2271
  try {
1341
2272
  return read(value);
@@ -1349,34 +2280,86 @@ function readAudioPlanDocument(value) {
1349
2280
  }
1350
2281
  }
1351
2282
  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.`);
1353
2283
  return {
1354
2284
  format: AUDIO_PLAN_FORMAT,
1355
- version: 1,
2285
+ version: 2,
1356
2286
  sampleRate: plan.sampleRate,
1357
2287
  channels: plan.channels,
2288
+ gainDb: plan.gainDb,
1358
2289
  sources: Object.fromEntries(Object.entries(sources).map(([id, { frames, asset }]) => [id, asset === void 0 ? { frames } : {
1359
2290
  frames,
1360
2291
  asset: { ...asset }
1361
2292
  }])),
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
- }
2293
+ tracks: plan.tracks.map((track) => ({
2294
+ key: track.key,
2295
+ name: track.name,
2296
+ gainDb: track.gainDb,
2297
+ muted: track.muted,
2298
+ soloed: track.soloed,
2299
+ clips: track.clips.map((clip) => {
2300
+ if (!Object.hasOwn(sources, clip.source)) throw new TypeError(`The sources don't include ${clip.source}, which clip ${clip.key} uses.`);
2301
+ return {
2302
+ key: clip.key,
2303
+ at: clip.at,
2304
+ source: clip.source,
2305
+ start: clip.start,
2306
+ end: clip.end,
2307
+ gainDb: clip.gainDb,
2308
+ fadeIn: {
2309
+ frames: clip.fadeIn.frames,
2310
+ curve: clip.fadeIn.curve
2311
+ },
2312
+ fadeOut: {
2313
+ frames: clip.fadeOut.frames,
2314
+ curve: clip.fadeOut.curve
2315
+ }
2316
+ };
2317
+ })
1376
2318
  })),
1377
2319
  metadata: { ...plan.metadata }
1378
2320
  };
1379
2321
  }
2322
+ // src/core/model/peaks.ts
2323
+ function levelFor(peaks, framesPerColumn) {
2324
+ let chosen;
2325
+ for (const level of peaks.levels) if (level.framesPerBucket <= framesPerColumn) chosen = level;
2326
+ return chosen ?? peaks.levels[0];
2327
+ }
2328
+ function peakColumns(peaks, options) {
2329
+ const { from, to, columns } = options;
2330
+ if (!Number.isSafeInteger(from) || !Number.isSafeInteger(to) || from < 0 || to <= from) throw new RangeError("from and to are whole frames, with from at 0 or more and before to.");
2331
+ if (!Number.isSafeInteger(columns) || columns < 1) throw new RangeError("columns is a whole number from 1.");
2332
+ const min = new Float32Array(columns);
2333
+ const max = new Float32Array(columns);
2334
+ const framesPerColumn = (to - from) / columns;
2335
+ const level = levelFor(peaks, framesPerColumn);
2336
+ if (!level) return {
2337
+ min,
2338
+ max
2339
+ };
2340
+ const { framesPerBucket, channels } = level;
2341
+ const buckets = channels[0]?.min.length ?? 0;
2342
+ for (let column = 0; column < columns; column += 1) {
2343
+ const start = from + column * framesPerColumn;
2344
+ const end = from + (column + 1) * framesPerColumn;
2345
+ const first = Math.floor(start / framesPerBucket);
2346
+ const last = Math.min(buckets, Math.max(first + 1, Math.ceil(end / framesPerBucket)));
2347
+ let low = 0;
2348
+ let high = 0;
2349
+ for (const channel of channels) for (let bucket = first; bucket < last; bucket += 1) {
2350
+ low = Math.min(low, channel.min[bucket]);
2351
+ high = Math.max(high, channel.max[bucket]);
2352
+ }
2353
+ min[column] = low;
2354
+ max[column] = high;
2355
+ }
2356
+ return {
2357
+ min,
2358
+ max
2359
+ };
2360
+ }
2361
+ // src/core/model/source.ts
2362
+ var MAX_SOURCE_NAME_LENGTH = 128;
1380
2363
  // src/core/model/time.ts
1381
2364
  function framesToSeconds(frames, sampleRate) {
1382
2365
  return frames / sampleRate;
@@ -1384,14 +2367,70 @@ function framesToSeconds(frames, sampleRate) {
1384
2367
  function secondsToFrames(seconds, sampleRate) {
1385
2368
  return Math.round(seconds * sampleRate);
1386
2369
  }
2370
+ function assertFrames(name, value) {
2371
+ if (!Number.isSafeInteger(value) || value < 0) throw new RangeError(`${name} must be a non-negative whole number of frames, not ${value}.`);
2372
+ }
2373
+ function formatTimecode(frames, sampleRate) {
2374
+ assertFrames("frames", frames);
2375
+ if (!Number.isSafeInteger(sampleRate) || sampleRate < 1) throw new RangeError(`The sample rate must be a positive whole number, not ${sampleRate}.`);
2376
+ const hundredths = Math.floor(frames * 100 / sampleRate);
2377
+ const two = (value) => String(value).padStart(2, "0");
2378
+ const fraction = two(hundredths % 100);
2379
+ const seconds = Math.floor(hundredths / 100) % 60;
2380
+ const minutes = Math.floor(hundredths / 6e3) % 60;
2381
+ const hours = Math.floor(hundredths / 36e4);
2382
+ return hours > 0 ? `${hours}:${two(minutes)}:${two(seconds)}.${fraction}` : `${minutes}:${two(seconds)}.${fraction}`;
2383
+ }
2384
+ // src/core/session/connect-output.ts
2385
+ function connectOutput(session, output) {
2386
+ let plan;
2387
+ let held = /* @__PURE__ */ new Set();
2388
+ function sync() {
2389
+ const snapshot = session.getSnapshot();
2390
+ const next = snapshot.plan;
2391
+ const ids = new Set(snapshot.sources.map((source) => source.id));
2392
+ if (next === plan) {
2393
+ held = ids;
2394
+ return;
2395
+ }
2396
+ const clips = next ? next.tracks.flatMap((track) => track.clips) : [];
2397
+ if ((next === void 0 || plan !== void 0 && !clips.some((clip) => held.has(clip.source))) && plan !== void 0) output.stop();
2398
+ plan = next;
2399
+ held = ids;
2400
+ if (!next) return;
2401
+ const sources = /* @__PURE__ */ new Map();
2402
+ for (const { source } of clips) {
2403
+ const audio = session.getAudio(source);
2404
+ if (audio) sources.set(source, audio);
2405
+ }
2406
+ output.load(next, sources);
2407
+ }
2408
+ sync();
2409
+ return session.subscribe(sync);
2410
+ }
2411
+ // src/core/session/source-name.ts
2412
+ var CONTROL = /\p{Cc}/gu;
2413
+ var BIDI = /[\u061C\u200E\u200F\u202A-\u202E\u2066-\u2069]/gu;
2414
+ var REFUSED = /[<>:"|?*]/gu;
2415
+ function cleanFileName(raw) {
2416
+ if (typeof raw !== "string") return void 0;
2417
+ let name = raw.replace(CONTROL, "").replace(BIDI, "");
2418
+ name = name.slice(Math.max(name.lastIndexOf("/"), name.lastIndexOf("\\")) + 1);
2419
+ name = name.replace(REFUSED, "").normalize("NFC");
2420
+ name = name.replace(/^[\s.]+/u, "").trimEnd();
2421
+ const points = Array.from(name);
2422
+ if (points.length > 128) name = points.slice(0, 128).join("").trimEnd();
2423
+ return name === "" ? void 0 : name;
2424
+ }
1387
2425
  // src/core/session/session.ts
1388
2426
  var BYTES_PER_SAMPLE = 4;
1389
2427
  function clipsOf(command) {
1390
2428
  switch (command.type) {
1391
2429
  case "audio.insertClips":
1392
- case "audio.replaceClips":
1393
2430
  case "audio.updateClips": return command.clips;
1394
2431
  case "audio.restoreClips": return command.entries.map((entry) => entry.clip);
2432
+ case "audio.replaceClips": return command.edits.flatMap((edit) => edit.clips);
2433
+ case "audio.restoreTracks": return command.entries.flatMap((entry) => entry.track.clips);
1395
2434
  default: return [];
1396
2435
  }
1397
2436
  }
@@ -1401,9 +2440,39 @@ function coarseSeconds(seconds) {
1401
2440
  function keysOf(command) {
1402
2441
  const keys = clipsOf(command).map((clip) => clip.key);
1403
2442
  if ("newKey" in command && typeof command.newKey === "string") keys.push(command.newKey);
1404
- if ("splitKey" in command && typeof command.splitKey === "string") keys.push(command.splitKey);
2443
+ if ("newKeys" in command && command.newKeys) keys.push(...Object.values(command.newKeys));
2444
+ if (command.type === "audio.addTrack" && typeof command.key === "string") keys.push(command.key);
2445
+ if (command.type === "audio.restoreTracks") keys.push(...command.entries.map((entry) => entry.track.key));
1405
2446
  return keys;
1406
2447
  }
2448
+ var TIME_EDITS = /* @__PURE__ */ new Set([
2449
+ "audio.deleteRange",
2450
+ "audio.keepRange",
2451
+ "audio.insertTime"
2452
+ ]);
2453
+ function equalData(a, b) {
2454
+ if (Object.is(a, b)) return true;
2455
+ if (typeof a !== "object" || typeof b !== "object" || a === null || b === null) return false;
2456
+ if (Array.isArray(a) !== Array.isArray(b)) return false;
2457
+ const keys = Object.keys(a);
2458
+ if (keys.length !== Object.keys(b).length) return false;
2459
+ return keys.every((key) => Object.hasOwn(b, key) && equalData(a[key], b[key]));
2460
+ }
2461
+ function clipsIn(plan) {
2462
+ return plan ? plan.tracks.flatMap((track) => track.clips) : [];
2463
+ }
2464
+ function wholeClip(key, source, at) {
2465
+ return {
2466
+ key,
2467
+ at,
2468
+ source: source.id,
2469
+ start: 0,
2470
+ end: source.frames,
2471
+ gainDb: 0,
2472
+ fadeIn: NO_FADE,
2473
+ fadeOut: NO_FADE
2474
+ };
2475
+ }
1407
2476
  function createAudioSession(options) {
1408
2477
  const { engine } = options;
1409
2478
  const policy = audioLimits.resolve(options.filePolicy);
@@ -1429,7 +2498,7 @@ function createAudioSession(options) {
1429
2498
  return total;
1430
2499
  };
1431
2500
  function referenced(steps) {
1432
- const ids = new Set(plan?.clips.map((clip) => clip.source));
2501
+ const ids = new Set(clipsIn(plan).map((clip) => clip.source));
1433
2502
  for (const { commands, inverses } of steps) for (const command of [...commands, ...inverses]) for (const clip of clipsOf(command)) ids.add(clip.source);
1434
2503
  return ids;
1435
2504
  }
@@ -1456,12 +2525,18 @@ function createAudioSession(options) {
1456
2525
  limit: "maxSessionSize",
1457
2526
  actual: bytes
1458
2527
  });
1459
- const clips = plan?.clips.length ?? 0;
2528
+ const clips = clipsIn(plan).length;
1460
2529
  if (clips > 0 && clips >= policy.limits.maxClips.warning) found.push({
1461
2530
  type: "limit",
1462
2531
  limit: "maxClips",
1463
2532
  actual: clips
1464
2533
  });
2534
+ const tracks = plan?.tracks.length ?? 0;
2535
+ if (tracks > 0 && tracks >= policy.limits.maxTracks.warning) found.push({
2536
+ type: "limit",
2537
+ limit: "maxTracks",
2538
+ actual: tracks
2539
+ });
1465
2540
  return found;
1466
2541
  }
1467
2542
  function makeSnapshot() {
@@ -1483,10 +2558,13 @@ function createAudioSession(options) {
1483
2558
  function changed() {
1484
2559
  if (selection) {
1485
2560
  const end = Math.min(selection.end, plan ? planLength(plan) : 0);
1486
- selection = selection.start < end ? {
2561
+ const tracks = (plan?.tracks ?? []).map((track) => track.key).filter((key) => selection?.tracks.includes(key));
2562
+ if (selection.start >= end || tracks.length === 0) selection = void 0;
2563
+ else if (end !== selection.end || tracks.length !== selection.tracks.length) selection = Object.freeze({
1487
2564
  start: selection.start,
1488
- end
1489
- } : void 0;
2565
+ end,
2566
+ tracks: Object.freeze(tracks)
2567
+ });
1490
2568
  }
1491
2569
  store.set(makeSnapshot());
1492
2570
  }
@@ -1506,8 +2584,9 @@ function createAudioSession(options) {
1506
2584
  truncated: source.warnings.some((warning) => warning.type === "truncated")
1507
2585
  };
1508
2586
  }
1509
- async function load(file, signal, onProgress, beforeDecode) {
2587
+ async function load(file, signal, onProgress, rate, givenName) {
1510
2588
  if (!(file instanceof Blob)) throw new TypeError("A recording must be a Blob or a File.");
2589
+ const name = cleanFileName(givenName ?? (typeof File === "function" && file instanceof File ? file.name : void 0));
1511
2590
  nextSource += 1;
1512
2591
  const id = `s${nextSource}`;
1513
2592
  const warnings = [];
@@ -1530,14 +2609,18 @@ function createAudioSession(options) {
1530
2609
  warnAt("maxSampleRate", probe.sampleRate);
1531
2610
  warnAt("maxDuration", Math.ceil(probe.frameBound * 1e3 / probe.sampleRate));
1532
2611
  warnAt("maxDecodedSize", probe.frameBound * probe.channels * BYTES_PER_SAMPLE);
1533
- beforeDecode(probe);
2612
+ const sampleRate = rate ?? probe.sampleRate;
2613
+ const converts = sampleRate !== probe.sampleRate;
2614
+ const frameBound = Math.ceil(probe.frameBound * sampleRate / probe.sampleRate);
2615
+ if (converts) warnAt("maxDecodedSize", frameBound * probe.channels * BYTES_PER_SAMPLE);
1534
2616
  const audio = await withProcessingTime(policy, (limited) => engine.decode(file, probe, {
1535
2617
  signal: limited,
1536
- ...onProgress ? { onProgress } : {}
2618
+ ...onProgress ? { onProgress } : {},
2619
+ ...converts ? { sampleRate } : {}
1537
2620
  }), { signal });
1538
- const frames = Math.min(audio.length, probe.frameBound);
2621
+ const frames = Math.min(audio.length, frameBound);
1539
2622
  const channels = audio.numberOfChannels;
1540
- 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: {
2623
+ if (audio.sampleRate !== sampleRate || channels < 1 || channels > probe.channels) throw new AudioError("INVALID_AUDIO", "The decoder's output doesn't match the probe.", { details: {
1541
2624
  container: probe.container,
1542
2625
  codec: probe.codec
1543
2626
  } });
@@ -1557,7 +2640,9 @@ function createAudioSession(options) {
1557
2640
  channels,
1558
2641
  frames,
1559
2642
  container: probe.container,
1560
- codec: probe.codec
2643
+ codec: probe.codec,
2644
+ ...converts ? { resampledFrom: probe.sampleRate } : {},
2645
+ ...name === void 0 ? {} : { name }
1561
2646
  }),
1562
2647
  audio,
1563
2648
  peaks,
@@ -1582,7 +2667,20 @@ function createAudioSession(options) {
1582
2667
  }
1583
2668
  function applyChecked(current, commands) {
1584
2669
  const result = applyCommands(reducer, current, commands);
1585
- if (result.state.clips.length > current.clips.length) policy.check("maxClips", result.state.clips.length);
2670
+ const next = result.state;
2671
+ const clips = clipsIn(next).length;
2672
+ if (clips > clipsIn(current).length) policy.check("maxClips", clips);
2673
+ if (next.tracks.length > current.tracks.length) policy.check("maxTracks", next.tracks.length);
2674
+ const length = planLength(next);
2675
+ if (length > planLength(current)) try {
2676
+ policy.check("maxDuration", Math.ceil(length * 1e3 / next.sampleRate));
2677
+ } catch (error) {
2678
+ if (!isAudioError(error, "DURATION_TOO_LONG")) throw error;
2679
+ throw new AudioError("DURATION_TOO_LONG", "The plan would be longer than maxDuration.", { details: {
2680
+ ...error.details,
2681
+ reason: "plan-too-long"
2682
+ } });
2683
+ }
1586
2684
  return result;
1587
2685
  }
1588
2686
  function commit(result, commands) {
@@ -1593,8 +2691,10 @@ function createAudioSession(options) {
1593
2691
  });
1594
2692
  collect();
1595
2693
  }
1596
- function newKey() {
1597
- const used = new Set(plan?.clips.map((clip) => clip.key));
2694
+ function newKey(also = /* @__PURE__ */ new Set()) {
2695
+ const used = new Set(clipsIn(plan).map((clip) => clip.key));
2696
+ for (const key of also) used.add(key);
2697
+ for (const track of plan?.tracks ?? []) used.add(track.key);
1598
2698
  for (const { commands, inverses } of history.steps) for (const command of [...commands, ...inverses]) for (const key of keysOf(command)) used.add(key);
1599
2699
  let key;
1600
2700
  do {
@@ -1603,6 +2703,40 @@ function createAudioSession(options) {
1603
2703
  } while (used.has(key));
1604
2704
  return key;
1605
2705
  }
2706
+ function fillKeys(commands) {
2707
+ const taken = new Set(commands.flatMap(keysOf));
2708
+ const fresh = () => {
2709
+ const key = newKey(taken);
2710
+ taken.add(key);
2711
+ return key;
2712
+ };
2713
+ commands.forEach((command, index) => {
2714
+ if (command.type === "audio.splitClip" && command.newKey === void 0) commands[index] = {
2715
+ ...command,
2716
+ newKey: fresh()
2717
+ };
2718
+ else if (command.type === "audio.addTrack" && command.key === void 0) commands[index] = {
2719
+ ...command,
2720
+ key: fresh()
2721
+ };
2722
+ else if ((command.type === "audio.deleteRange" || command.type === "audio.insertTime") && Array.isArray(command.tracks)) {
2723
+ const given = command.newKeys ?? {};
2724
+ const missing = command.tracks.filter((track) => typeof track === "string" && !Object.hasOwn(given, track));
2725
+ if (missing.length === 0) return;
2726
+ const newKeys = { ...given };
2727
+ for (const track of missing) Object.defineProperty(newKeys, track, {
2728
+ value: fresh(),
2729
+ enumerable: true,
2730
+ writable: true,
2731
+ configurable: true
2732
+ });
2733
+ commands[index] = {
2734
+ ...command,
2735
+ newKeys
2736
+ };
2737
+ }
2738
+ });
2739
+ }
1606
2740
  return {
1607
2741
  getSnapshot: store.getSnapshot,
1608
2742
  subscribe: store.subscribe,
@@ -1612,25 +2746,27 @@ function createAudioSession(options) {
1612
2746
  status = "opening";
1613
2747
  error = void 0;
1614
2748
  try {
1615
- const source = await track(callOptions.signal, true, (signal) => load(file, signal, callOptions.onProgress, () => {}));
2749
+ const source = await track(callOptions.signal, true, (signal) => load(file, signal, callOptions.onProgress, void 0, callOptions.name));
1616
2750
  const replaced = superseded(started);
1617
2751
  if (replaced) throw replaced;
1618
2752
  policy.check("maxSessionSize", source.bytes);
1619
2753
  sources.clear();
1620
2754
  history.clear();
1621
2755
  sources.set(source.info.id, source);
2756
+ plan = void 0;
2757
+ const first = {
2758
+ key: newKey(),
2759
+ name: "",
2760
+ gainDb: 0,
2761
+ muted: false,
2762
+ soloed: false,
2763
+ clips: [wholeClip(newKey(), source.info, 0)]
2764
+ };
1622
2765
  plan = {
1623
2766
  sampleRate: source.info.sampleRate,
1624
2767
  channels: source.info.channels,
1625
- clips: [{
1626
- key: newKey(),
1627
- source: source.info.id,
1628
- start: 0,
1629
- end: source.info.frames,
1630
- gainDb: 0,
1631
- fadeIn: NO_FADE,
1632
- fadeOut: NO_FADE
1633
- }],
2768
+ gainDb: 0,
2769
+ tracks: [first],
1634
2770
  metadata: EMPTY_METADATA
1635
2771
  };
1636
2772
  selection = void 0;
@@ -1661,30 +2797,33 @@ function createAudioSession(options) {
1661
2797
  try {
1662
2798
  const source = await track(insertOptions.signal, false, (signal) => {
1663
2799
  policy.check("maxFiles", sources.size + 1);
1664
- return load(file, signal, insertOptions.onProgress, (probe) => {
1665
- const rate = plan?.sampleRate;
1666
- 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 } });
1667
- });
2800
+ return load(file, signal, insertOptions.onProgress, plan?.sampleRate, insertOptions.name);
1668
2801
  });
1669
2802
  const replaced = superseded(started);
1670
2803
  if (replaced) throw replaced;
1671
2804
  const current = plan;
1672
2805
  const drop = stepsToDrop(source.bytes);
1673
2806
  if (drop === void 0) throw policy.error("maxSessionSize", heldBytes() + source.bytes);
1674
- const commands = [{
2807
+ const clip = wholeClip(newKey(), source.info, insertOptions.at ?? 0);
2808
+ const commands = [];
2809
+ if (source.info.channels > current.channels) commands.push({
2810
+ type: "audio.setChannels",
2811
+ channels: source.info.channels
2812
+ });
2813
+ let target = insertOptions.track;
2814
+ if (target === void 0) {
2815
+ target = newKey();
2816
+ commands.push({
2817
+ type: "audio.addTrack",
2818
+ key: target,
2819
+ index: current.tracks.length
2820
+ });
2821
+ }
2822
+ commands.push({
1675
2823
  type: "audio.insertClips",
1676
- at: insertOptions.at ?? planLength(current),
1677
- clips: [{
1678
- key: newKey(),
1679
- source: source.info.id,
1680
- start: 0,
1681
- end: source.info.frames,
1682
- gainDb: 0,
1683
- fadeIn: NO_FADE,
1684
- fadeOut: NO_FADE
1685
- }],
1686
- splitKey: newKey()
1687
- }];
2824
+ track: target,
2825
+ clips: [clip]
2826
+ });
1688
2827
  sources.set(source.info.id, source);
1689
2828
  let result;
1690
2829
  try {
@@ -1727,7 +2866,11 @@ function createAudioSession(options) {
1727
2866
  details: { reason: "not-plain-data" }
1728
2867
  });
1729
2868
  }
1730
- commit(applyChecked(plan, copies), copies);
2869
+ fillKeys(copies);
2870
+ const result = applyChecked(plan, copies);
2871
+ if (equalData(result.state, plan)) return;
2872
+ commit(result, copies);
2873
+ if (copies.some((command) => TIME_EDITS.has(command.type))) selection = void 0;
1731
2874
  } catch (reason) {
1732
2875
  const failure = asAudioError(reason);
1733
2876
  emit({
@@ -1779,26 +2922,31 @@ function createAudioSession(options) {
1779
2922
  const length = plan ? planLength(plan) : 0;
1780
2923
  const from = Math.max(0, Math.min(start, end, length));
1781
2924
  const to = Math.min(length, Math.max(start, end, 0));
1782
- next = from < to ? {
2925
+ const tracks = (plan?.tracks ?? []).map((track) => track.key).filter((key) => range.tracks === void 0 || range.tracks.includes(key));
2926
+ if (from < to && tracks.length > 0) next = Object.freeze({
1783
2927
  start: from,
1784
- end: to
1785
- } : void 0;
2928
+ end: to,
2929
+ tracks: Object.freeze(tracks)
2930
+ });
1786
2931
  }
1787
- if (next?.start === selection?.start && next?.end === selection?.end) return;
2932
+ if (next?.start === selection?.start && next?.end === selection?.end && next?.tracks.join("\n") === selection?.tracks.join("\n")) return;
1788
2933
  selection = next;
1789
2934
  changed();
1790
2935
  },
1791
2936
  getPeaks: (id) => sources.get(id)?.peaks,
2937
+ getAudio: (id) => sources.get(id)?.audio,
1792
2938
  async export(exportOptions = {}) {
1793
2939
  const current = plan;
1794
2940
  const format = exportOptions.format ?? { container: "wav" };
1795
2941
  try {
1796
2942
  if (!current) throw new AudioError("INVALID_COMMAND", "Open a recording before exporting it.", { details: { reason: "no-recording" } });
1797
- if (current.clips.length === 0) throw new AudioError("INVALID_COMMAND", "The recording has no clips to export.", { details: { reason: "empty-plan" } });
2943
+ const clips = clipsIn(current);
2944
+ if (clips.length === 0) throw new AudioError("INVALID_COMMAND", "The recording has no clips to export.", { details: { reason: "empty-plan" } });
2945
+ if (mixLength(current) === 0) throw new AudioError("INVALID_COMMAND", "No track with clips is audible.", { details: { reason: "nothing-audible" } });
1798
2946
  const { processor } = options;
1799
2947
  if (!processor) throw new TypeError("Exporting needs a processor in createAudioSession.");
1800
2948
  const used = /* @__PURE__ */ new Map();
1801
- for (const { source } of current.clips) {
2949
+ for (const { source } of clips) {
1802
2950
  const held = sources.get(source);
1803
2951
  if (held) used.set(source, held.audio);
1804
2952
  }
@@ -1815,7 +2963,7 @@ function createAudioSession(options) {
1815
2963
  }), exportOptions.signal ? { signal: exportOptions.signal } : {});
1816
2964
  emit({
1817
2965
  type: "recording_exported",
1818
- durationSeconds: coarseSeconds(framesToSeconds(planLength(current), current.sampleRate)),
2966
+ durationSeconds: coarseSeconds(framesToSeconds(mixLength(current), current.sampleRate)),
1819
2967
  sampleRate: current.sampleRate,
1820
2968
  channels: current.channels,
1821
2969
  sampleFormat: format.sampleFormat ?? "pcm16"
@@ -1851,6 +2999,55 @@ function createAudioSession(options) {
1851
2999
  }
1852
3000
  };
1853
3001
  }
3002
+ // src/core/session/watch-playhead.ts
3003
+ function pageFrames() {
3004
+ const page = globalThis;
3005
+ if (page.requestAnimationFrame && page.cancelAnimationFrame) {
3006
+ const { requestAnimationFrame: request, cancelAnimationFrame: cancel } = page;
3007
+ return {
3008
+ request: (callback) => request(callback),
3009
+ cancel: (handle) => cancel(handle)
3010
+ };
3011
+ }
3012
+ return {
3013
+ request: (callback) => setTimeout(callback, 16),
3014
+ cancel: (handle) => clearTimeout(handle)
3015
+ };
3016
+ }
3017
+ function watchPlayhead(output, listener, frames = pageFrames()) {
3018
+ let last;
3019
+ let pending;
3020
+ let stopped = false;
3021
+ const report = () => {
3022
+ const frame = output.position();
3023
+ if (frame === last) return;
3024
+ last = frame;
3025
+ listener(frame);
3026
+ };
3027
+ const tick = () => {
3028
+ pending = void 0;
3029
+ if (stopped) return;
3030
+ report();
3031
+ if (output.getSnapshot().state === "playing") pending = frames.request(tick);
3032
+ };
3033
+ const changed = () => {
3034
+ if (stopped) return;
3035
+ report();
3036
+ if (output.getSnapshot().state === "playing") pending ??= frames.request(tick);
3037
+ else if (pending !== void 0) {
3038
+ frames.cancel(pending);
3039
+ pending = void 0;
3040
+ }
3041
+ };
3042
+ const unsubscribe = output.subscribe(changed);
3043
+ changed();
3044
+ return () => {
3045
+ stopped = true;
3046
+ unsubscribe();
3047
+ if (pending !== void 0) frames.cancel(pending);
3048
+ pending = void 0;
3049
+ };
3050
+ }
1854
3051
  // src/messages/en.ts
1855
3052
  var audioMessages = /* @__PURE__ */ defineMessages({
1856
3053
  ...sdkCoreMessages,
@@ -1867,6 +3064,10 @@ var audioMessages = /* @__PURE__ */ defineMessages({
1867
3064
  one: "A recording can have {maximum} clip. Join or delete clips, and try again.",
1868
3065
  other: "A recording can have up to {maximum} clips. Join or delete clips, and try again."
1869
3066
  }),
3067
+ "errors.TOO_MANY_TRACKS": /* @__PURE__ */ plural("maximum", {
3068
+ one: "A recording can have {maximum} track. Remove a track, and try again.",
3069
+ other: "A recording can have up to {maximum} tracks. Remove a track, and try again."
3070
+ }),
1870
3071
  "warnings.maxDuration": "This recording is {actual, duration} long, and may be slow to open and edit.",
1871
3072
  "warnings.maxChannels": "This recording has {actual, number} channels, and may be slow to edit.",
1872
3073
  "warnings.maxSampleRate": "This recording's sample rate is {actual, number} Hz, and it may be slow to edit.",
@@ -1875,8 +3076,29 @@ var audioMessages = /* @__PURE__ */ defineMessages({
1875
3076
  one: "This recording has {actual} clip. Many clips may be slow to play and export.",
1876
3077
  other: "This recording has {actual} clips. Many clips may be slow to play and export."
1877
3078
  }),
3079
+ "warnings.maxTracks": /* @__PURE__ */ plural("actual", {
3080
+ one: "This recording has {actual} track. Many tracks may be slow to play and export.",
3081
+ other: "This recording has {actual} tracks. Many tracks may be slow to play and export."
3082
+ }),
3083
+ "errors.UNSUPPORTED_ENVIRONMENT.autoplay-blocked": "The browser didn't let sound start. Press Play to start it.",
3084
+ "errors.DURATION_TOO_LONG.plan-too-long": "This would make the recording {actual, duration} long, which is over the {maximum, duration} limit.",
1878
3085
  "warnings.truncated": "This recording looks incomplete, perhaps from an interrupted recording or download. It opened with the audio it holds."
1879
3086
  });
1880
- 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, createAudioEngine, createAudioOutput, createAudioProcessor, createAudioSession, dbToGain, framesToSeconds, gainAt, isAudioError, planLength, readAudioPlanDocument, secondsToFrames, toAudioPlanDocument };
3087
+ // src/messages/text.ts
3088
+ function audioErrorText(messages, error) {
3089
+ if (isSdkError(error)) {
3090
+ const details = error.details ?? {};
3091
+ if (typeof details.reason === "string") {
3092
+ const key = `errors.${error.code}.${details.reason}`;
3093
+ if (Object.hasOwn(audioMessages, key)) return messages.t(key, details);
3094
+ }
3095
+ }
3096
+ return messages.error(error);
3097
+ }
3098
+ function audioWarningText(messages, warning) {
3099
+ if (warning.type === "truncated") return messages.t("warnings.truncated");
3100
+ return messages.t(`warnings.${warning.limit}`, { actual: warning.actual });
3101
+ }
3102
+ 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 };
1881
3103
 
1882
3104
  //# sourceMappingURL=index.js.map