@waveform-playlist/engine 13.6.1 → 14.0.0-next.1

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
@@ -21,6 +21,7 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
21
21
  var index_exports = {};
22
22
  __export(index_exports, {
23
23
  PlaylistEngine: () => PlaylistEngine,
24
+ attachDecodeContext: () => attachDecodeContext,
24
25
  calculateDuration: () => calculateDuration,
25
26
  calculateSplitPoint: () => calculateSplitPoint,
26
27
  calculateViewportBounds: () => calculateViewportBounds,
@@ -29,6 +30,8 @@ __export(index_exports, {
29
30
  clampSeekPosition: () => clampSeekPosition,
30
31
  constrainBoundaryTrim: () => constrainBoundaryTrim,
31
32
  constrainClipDrag: () => constrainClipDrag,
33
+ createArrangement: () => createArrangement,
34
+ defaultLoadSource: () => defaultLoadSource,
32
35
  findClosestZoomIndex: () => findClosestZoomIndex,
33
36
  getVisibleChunkIndices: () => getVisibleChunkIndices,
34
37
  shouldUpdateViewport: () => shouldUpdateViewport,
@@ -95,7 +98,8 @@ function splitClip(clip, splitSample) {
95
98
  color: clip.color,
96
99
  fadeIn: clip.fadeIn,
97
100
  audioBuffer: clip.audioBuffer,
98
- waveformData: clip.waveformData
101
+ waveformData: clip.waveformData,
102
+ src: clip.src
99
103
  });
100
104
  const right = (0, import_core.createClip)({
101
105
  startSample: splitSample,
@@ -108,7 +112,8 @@ function splitClip(clip, splitSample) {
108
112
  color: clip.color,
109
113
  fadeOut: clip.fadeOut,
110
114
  audioBuffer: clip.audioBuffer,
111
- waveformData: clip.waveformData
115
+ waveformData: clip.waveformData,
116
+ src: clip.src
112
117
  });
113
118
  return { left, right };
114
119
  }
@@ -184,15 +189,1525 @@ function clampSeekPosition(time, duration) {
184
189
  return Math.max(0, Math.min(time, duration));
185
190
  }
186
191
 
192
+ // src/arrangement/Arrangement.ts
193
+ var import_core7 = require("@waveform-playlist/core");
194
+
195
+ // src/arrangement/attach.ts
196
+ var ARRANGEMENT_ATTACH_DECODE = /* @__PURE__ */ Symbol.for(
197
+ "@waveform-playlist/engine/arrangement/attach-decode/v1"
198
+ );
199
+ var ARRANGEMENT_ATTACH_TIME_BASE = /* @__PURE__ */ Symbol.for(
200
+ "@waveform-playlist/engine/arrangement/time-base/v1"
201
+ );
202
+ function attachPoints(value) {
203
+ return typeof value === "object" && value !== null ? value : {};
204
+ }
205
+ function isArrangement(value) {
206
+ return typeof attachPoints(value)[ARRANGEMENT_ATTACH_TIME_BASE] === "function";
207
+ }
208
+ function attachDecodeContext(arrangement, getContext) {
209
+ const attach = attachPoints(arrangement)[ARRANGEMENT_ATTACH_DECODE];
210
+ if (typeof attach !== "function") {
211
+ throw new Error(
212
+ "[waveform-playlist] attachDecodeContext: the first argument must be an arrangement made by createArrangement()."
213
+ );
214
+ }
215
+ return attach.call(arrangement, getContext);
216
+ }
217
+ function attachTimeBase(arrangement, timeBase) {
218
+ const attach = arrangement[ARRANGEMENT_ATTACH_TIME_BASE];
219
+ return attach.call(arrangement, timeBase);
220
+ }
221
+
222
+ // src/arrangement/clipEdits.ts
223
+ var import_core2 = require("@waveform-playlist/core");
224
+ function loadedClips(track) {
225
+ return track.clips.filter((clip) => !(0, import_core2.isLoadingClip)(clip));
226
+ }
227
+ function loadedClip(tracks, trackId, clipId) {
228
+ const clip = tracks.find((t) => t.id === trackId)?.clips.find((c) => c.id === clipId);
229
+ return clip && !(0, import_core2.isLoadingClip)(clip) ? clip : void 0;
230
+ }
231
+ function findClip(tracks, trackId, clipId, operation) {
232
+ const track = tracks.find((t) => t.id === trackId);
233
+ if (!track) {
234
+ console.warn(`[waveform-playlist/engine] ${operation}: track "${trackId}" not found`);
235
+ return null;
236
+ }
237
+ const clipIndex = track.clips.findIndex((c) => c.id === clipId);
238
+ if (clipIndex === -1) {
239
+ console.warn(
240
+ `[waveform-playlist/engine] ${operation}: clip "${clipId}" not found in track "${trackId}"`
241
+ );
242
+ return null;
243
+ }
244
+ const clip = track.clips[clipIndex];
245
+ if ((0, import_core2.isLoadingClip)(clip)) {
246
+ console.warn(
247
+ `[waveform-playlist/engine] ${operation}: clip "${clipId}" in track "${trackId}" is still loading and cannot be edited until its audio has loaded`
248
+ );
249
+ return null;
250
+ }
251
+ return { track, clip, clipIndex };
252
+ }
253
+ function withTrackClips(tracks, trackId, clips) {
254
+ return tracks.map((t) => t.id === trackId ? { ...t, clips } : t);
255
+ }
256
+ function clipBounds(tracks, trackId, clipId) {
257
+ const clip = loadedClip(tracks, trackId, clipId);
258
+ if (!clip) return null;
259
+ return {
260
+ offsetSamples: clip.offsetSamples,
261
+ durationSamples: clip.durationSamples,
262
+ startSample: clip.startSample,
263
+ sourceDurationSamples: clip.sourceDurationSamples
264
+ };
265
+ }
266
+ function constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time) {
267
+ const track = tracks.find((t) => t.id === trackId);
268
+ const clip = loadedClip(tracks, trackId, clipId);
269
+ if (!track || !clip) return 0;
270
+ const sortedClips = (0, import_core2.sortClipsByTime)(loadedClips(track));
271
+ const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
272
+ return constrainBoundaryTrim(
273
+ clip,
274
+ deltaSamples,
275
+ boundary,
276
+ sortedClips,
277
+ sortedIndex,
278
+ time.minDuration(clip)
279
+ );
280
+ }
281
+ function moveClip(tracks, trackId, clipId, deltaSamples, time) {
282
+ const found = findClip(tracks, trackId, clipId, "moveClip");
283
+ if (!found) return null;
284
+ const { track, clip, clipIndex } = found;
285
+ const sortedClips = (0, import_core2.sortClipsByTime)(loadedClips(track));
286
+ const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
287
+ const delta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
288
+ if (delta === 0) return null;
289
+ const startSample = Math.floor(clip.startSample + delta);
290
+ const moved = {
291
+ ...clip,
292
+ startSample,
293
+ startTick: clip.startTick !== void 0 ? time.tickAt(startSample) : void 0
294
+ };
295
+ const clips = track.clips.map((c, i) => i === clipIndex ? moved : c);
296
+ return { tracks: withTrackClips(tracks, trackId, clips), delta };
297
+ }
298
+ function trimClip(tracks, trackId, clipId, boundary, deltaSamples, time) {
299
+ const found = findClip(tracks, trackId, clipId, "trimClip");
300
+ if (!found) return null;
301
+ const { track, clip, clipIndex } = found;
302
+ const constrained = constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time);
303
+ if (constrained === 0) return null;
304
+ let trimmed;
305
+ if (boundary === "left") {
306
+ const startSample = clip.startSample + constrained;
307
+ trimmed = {
308
+ ...clip,
309
+ startSample,
310
+ startTick: clip.startTick !== void 0 ? time.tickAt(startSample) : void 0,
311
+ offsetSamples: clip.offsetSamples + constrained,
312
+ durationSamples: clip.durationSamples - constrained
313
+ };
314
+ } else {
315
+ trimmed = { ...clip, durationSamples: clip.durationSamples + constrained };
316
+ }
317
+ const clips = track.clips.map((c, i) => i === clipIndex ? trimmed : c);
318
+ return withTrackClips(tracks, trackId, clips);
319
+ }
320
+ function splitClip2(tracks, trackId, clipId, atSample, time) {
321
+ const found = findClip(tracks, trackId, clipId, "splitClip");
322
+ if (!found) return null;
323
+ const { track, clip, clipIndex } = found;
324
+ const minDuration = time.minDuration(clip);
325
+ if (!canSplitAt(clip, atSample, minDuration)) {
326
+ console.warn(
327
+ `[waveform-playlist/engine] splitClip: cannot split clip "${clipId}" at sample ${atSample} (clip range: ${clip.startSample}\u2013${clip.startSample + clip.durationSamples}, minDuration: ${minDuration})`
328
+ );
329
+ return null;
330
+ }
331
+ const { left, right } = splitClip(clip, atSample);
332
+ const withTick = (half) => clip.startTick !== void 0 ? { ...half, startTick: time.tickAt(half.startSample) } : half;
333
+ const clips = [...track.clips];
334
+ clips.splice(clipIndex, 1, withTick(left), withTick(right));
335
+ return withTrackClips(tracks, trackId, clips);
336
+ }
337
+
338
+ // src/arrangement/devFreeze.ts
339
+ function isDevelopmentBuild() {
340
+ try {
341
+ return process.env.NODE_ENV !== "production";
342
+ } catch {
343
+ return false;
344
+ }
345
+ }
346
+ function freezeTrackInDevelopment(track) {
347
+ if (!isDevelopmentBuild() || Object.isFrozen(track)) return track;
348
+ for (const clip of track.clips) Object.freeze(clip);
349
+ Object.freeze(track.clips);
350
+ return Object.freeze(track);
351
+ }
352
+ function freezeTracksInDevelopment(tracks) {
353
+ if (!isDevelopmentBuild()) return tracks;
354
+ for (const track of tracks) freezeTrackInDevelopment(track);
355
+ return Object.freeze(tracks);
356
+ }
357
+
358
+ // src/arrangement/loadSource.ts
359
+ var USERINFO = /^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/@]*@/i;
360
+ function urlLabel(url) {
361
+ const plain = url.split(/[?#]/)[0];
362
+ const cut = plain.replace(USERINFO, "$1");
363
+ if (cut !== plain) return cut;
364
+ try {
365
+ const parsed = new URL(url, "http://relative.invalid/");
366
+ if (parsed.username !== "" || parsed.password !== "") {
367
+ parsed.username = "";
368
+ parsed.password = "";
369
+ parsed.search = "";
370
+ parsed.hash = "";
371
+ return parsed.href;
372
+ }
373
+ } catch {
374
+ }
375
+ return plain;
376
+ }
377
+ function sourceLabel(src) {
378
+ if (typeof src === "string") {
379
+ if (/^data:/i.test(src)) return "data: URL";
380
+ if (/^blob:/i.test(src)) return "blob: URL";
381
+ return urlLabel(src);
382
+ }
383
+ if (typeof File !== "undefined" && src instanceof File) return src.name;
384
+ return "Blob";
385
+ }
386
+ async function readBytes(src, label2, signal) {
387
+ if (typeof src !== "string") {
388
+ const bytes2 = await src.arrayBuffer();
389
+ signal.throwIfAborted();
390
+ return bytes2;
391
+ }
392
+ let response;
393
+ try {
394
+ response = await fetch(src, { signal });
395
+ } catch (error) {
396
+ signal.throwIfAborted();
397
+ if (error instanceof TypeError) {
398
+ const failure = new Error("Failed to fetch " + label2);
399
+ throw label2 === src ? Object.assign(failure, { cause: error }) : failure;
400
+ }
401
+ throw error;
402
+ }
403
+ signal.throwIfAborted();
404
+ if (!response.ok) {
405
+ throw new Error(`Failed to fetch ${label2}: ${response.status} ${response.statusText}`);
406
+ }
407
+ const bytes = await response.arrayBuffer();
408
+ signal.throwIfAborted();
409
+ return bytes;
410
+ }
411
+ function isUsable(buffer) {
412
+ return !!buffer && buffer.length > 0 && typeof buffer.sampleRate === "number" && buffer.sampleRate > 0;
413
+ }
414
+ var defaultLoadSource = async (src, { signal, audioContext }) => {
415
+ signal.throwIfAborted();
416
+ const label2 = sourceLabel(src);
417
+ const bytes = await readBytes(src, label2, signal);
418
+ let buffer;
419
+ try {
420
+ buffer = await audioContext.decodeAudioData(bytes);
421
+ } catch (error) {
422
+ signal.throwIfAborted();
423
+ if (error instanceof Error) throw error;
424
+ throw new Error("Failed to decode audio: " + label2);
425
+ }
426
+ signal.throwIfAborted();
427
+ if (!isUsable(buffer)) throw new Error("Decoded audio is empty: " + label2);
428
+ return buffer;
429
+ };
430
+
431
+ // src/arrangement/sources.ts
432
+ var import_core4 = require("@waveform-playlist/core");
433
+
434
+ // src/arrangement/resolveLoadingClip.ts
435
+ var import_core3 = require("@waveform-playlist/core");
436
+ var warned = /* @__PURE__ */ new WeakMap();
437
+ function label(loading) {
438
+ return `clip "${loading.id}"`;
439
+ }
440
+ function warnOnce(loading, message) {
441
+ const seen = warned.get(loading) ?? /* @__PURE__ */ new Set();
442
+ warned.set(loading, seen);
443
+ if (seen.has(message)) return;
444
+ seen.add(message);
445
+ console.warn(`[waveform-playlist] ${label(loading)}: ${message}`);
446
+ }
447
+ var isNonNegative = (n) => Number.isFinite(n) && n >= 0;
448
+ function givenDuration(loading) {
449
+ return loading.duration ?? void 0;
450
+ }
451
+ function fieldProblem(loading) {
452
+ if (!isNonNegative(loading.start ?? 0)) {
453
+ return `start must be a finite number of seconds >= 0, got ${String(loading.start)}`;
454
+ }
455
+ if (!isNonNegative(loading.offset ?? 0)) {
456
+ return `offset must be a finite number of seconds >= 0, got ${String(loading.offset)}`;
457
+ }
458
+ const duration = givenDuration(loading);
459
+ if (duration !== void 0 && !(Number.isFinite(duration) && duration > 0)) {
460
+ return `duration must be a positive, finite number of seconds, got ${String(duration)}`;
461
+ }
462
+ return null;
463
+ }
464
+ function fitDuration(loading, offsetSamples, total, rate) {
465
+ if (!(offsetSamples < total)) return { problem: "offset is at or past the end of the audio" };
466
+ const rest = total - offsetSamples;
467
+ const duration = givenDuration(loading);
468
+ const wanted = duration === void 0 ? rest : Math.round(duration * rate);
469
+ if (!(wanted >= 1)) return { problem: "duration is shorter than one sample" };
470
+ if (wanted > rest + 1) {
471
+ warnOnce(loading, "duration runs past the end of the audio and was cut to it");
472
+ }
473
+ return { samples: Math.min(wanted, rest) };
474
+ }
475
+ function convert(loading, buffer) {
476
+ const rate = buffer?.sampleRate;
477
+ if (!(Number.isFinite(rate) && rate > 0 && buffer.length >= 1)) {
478
+ return "the decoded buffer is empty or has no usable sample rate";
479
+ }
480
+ const problem = fieldProblem(loading);
481
+ if (problem) return problem;
482
+ const offsetSamples = Math.round((loading.offset ?? 0) * rate);
483
+ const startSample = Math.round((loading.start ?? 0) * rate);
484
+ if (!Number.isSafeInteger(offsetSamples) || !Number.isSafeInteger(startSample)) {
485
+ return "start or offset is too large";
486
+ }
487
+ const fitted = fitDuration(loading, offsetSamples, buffer.length, rate);
488
+ if ("problem" in fitted) return fitted.problem;
489
+ return {
490
+ ...(0, import_core3.createClip)({
491
+ audioBuffer: buffer,
492
+ startSample,
493
+ offsetSamples,
494
+ durationSamples: fitted.samples,
495
+ gain: loading.gain,
496
+ name: loading.name,
497
+ color: loading.color,
498
+ fadeIn: loading.fadeIn,
499
+ fadeOut: loading.fadeOut,
500
+ waveformData: loading.waveformData,
501
+ src: loading.src
502
+ }),
503
+ id: loading.id
504
+ };
505
+ }
506
+ function resolveLoadingClip(loading, buffer) {
507
+ let converted;
508
+ try {
509
+ converted = convert(loading, buffer);
510
+ } catch (error) {
511
+ converted = error instanceof Error ? error.message : String(error);
512
+ }
513
+ return typeof converted === "string" ? { unusable: `${label(loading)}: ${converted}` } : { clip: converted };
514
+ }
515
+
516
+ // src/arrangement/sources.ts
517
+ var EMPTY_VALUE = {
518
+ sources: /* @__PURE__ */ new Map(),
519
+ pendingCount: 0,
520
+ failedCount: 0,
521
+ isLoading: false
522
+ };
523
+ function deferred() {
524
+ let resolve = () => {
525
+ };
526
+ const promise = new Promise((done) => {
527
+ resolve = done;
528
+ });
529
+ return { promise, resolve };
530
+ }
531
+ function sameMembers(a, b) {
532
+ if (a.size !== b.size) return false;
533
+ for (const member of a) if (!b.has(member)) return false;
534
+ return true;
535
+ }
536
+ var ArrangementSources = class {
537
+ /**
538
+ * @param loadSource how a source becomes an AudioBuffer
539
+ * @param onSettled called when a source settled by itself (a load finished or failed)
540
+ */
541
+ constructor(loadSource, onSettled) {
542
+ this._trackSources = /* @__PURE__ */ new WeakMap();
543
+ /** A loading clip and the buffer it was converted with: the same clip object every time. */
544
+ this._resolved = /* @__PURE__ */ new WeakMap();
545
+ this._wanted = /* @__PURE__ */ new Set();
546
+ /** Per source, the reason a clip of the CURRENT tracks could not be made (found by the last pass). */
547
+ this._unusable = /* @__PURE__ */ new Map();
548
+ this._getContext = null;
549
+ this._attached = deferred();
550
+ /** While `declare` talks to the loader, its notifications are not acted on. */
551
+ this._declaring = false;
552
+ const { source, publish } = (0, import_core4.createValueSource)(EMPTY_VALUE);
553
+ this.value = source;
554
+ this._publish = publish;
555
+ this._loader = (0, import_core4.createSourceLoader)({
556
+ load: async (src, signal) => {
557
+ let getContext = this._getContext;
558
+ while (!getContext) {
559
+ await this._attached.promise;
560
+ getContext = this._getContext;
561
+ }
562
+ signal.throwIfAborted();
563
+ const audioContext = await getContext();
564
+ signal.throwIfAborted();
565
+ return loadSource(src, { signal, audioContext });
566
+ }
567
+ });
568
+ this._loader.subscribe(() => {
569
+ if (!this._declaring) onSettled();
570
+ });
571
+ }
572
+ /**
573
+ * Give the loader a context to decode with; loads that were waiting start.
574
+ * Returns the function that takes it away again: loads in flight are
575
+ * aborted, loaded sources are kept, and the next attach starts the aborted
576
+ * ones again.
577
+ */
578
+ attachDecodeContext(getContext) {
579
+ if (this._getContext) {
580
+ console.warn(
581
+ "[waveform-playlist] An arrangement decodes with one audio context at a time: a context was attached while another still is. Detach the first (dispose its engine) before attaching another."
582
+ );
583
+ }
584
+ this._getContext = getContext;
585
+ this._attached.resolve();
586
+ this._loader.setWanted(this._wanted);
587
+ return () => {
588
+ if (this._getContext !== getContext) return;
589
+ this._getContext = null;
590
+ this._attached = deferred();
591
+ this._loader.suspend();
592
+ };
593
+ }
594
+ /** Start a source whose load failed again. Does nothing for any other source. */
595
+ retry(src) {
596
+ this._loader.retry(src);
597
+ }
598
+ /**
599
+ * Tell the loader what `states` name. The loader is touched only when the
600
+ * set of wanted sources changed or a clip brought the audio of a source
601
+ * that is not loaded yet.
602
+ */
603
+ declare(states) {
604
+ const wanted = /* @__PURE__ */ new Set();
605
+ const carried = /* @__PURE__ */ new Map();
606
+ for (const tracks of states) {
607
+ for (const track of tracks) {
608
+ const named = this._sourcesOf(track);
609
+ for (const clip of named.loading) wanted.add(clip.src);
610
+ for (const [src, buffer] of named.carried) if (!carried.has(src)) carried.set(src, buffer);
611
+ }
612
+ }
613
+ for (const src of carried.keys()) wanted.add(src);
614
+ this._declaring = true;
615
+ try {
616
+ for (const [src, buffer] of carried) this._loader.provide(src, buffer);
617
+ if (!sameMembers(wanted, this._wanted)) {
618
+ this._wanted = wanted;
619
+ this._loader.setWanted(wanted);
620
+ }
621
+ } finally {
622
+ this._declaring = false;
623
+ }
624
+ }
625
+ /**
626
+ * One pass over every state: two functions that replace, in a tracks
627
+ * array, every loading clip whose source is loaded with its loaded clip.
628
+ * They remember each track they have seen, so states that shared a track
629
+ * object go on sharing one, and they return the same array when nothing in
630
+ * it changed. Call `current` with the current tracks FIRST, then `stored`
631
+ * for each stored state, then `finishPass()`.
632
+ *
633
+ * A clip that cannot be made fails its source only while it is in the
634
+ * current tracks: one that only an undo or redo state holds is not
635
+ * something the app can see or mend.
636
+ *
637
+ * @param tickAt the tick of a sample position (undefined without an engine)
638
+ */
639
+ beginPass(tickAt) {
640
+ const loaded = this._loader.getSnapshot();
641
+ const unusable = /* @__PURE__ */ new Map();
642
+ this._unusable = unusable;
643
+ const seen = /* @__PURE__ */ new Map();
644
+ let inCurrentTracks = false;
645
+ const switched = (clip) => {
646
+ const state = loaded.get(clip.src);
647
+ if (state?.status !== "loaded") return clip;
648
+ const result = this._resolve(clip, state.value, tickAt);
649
+ if ("clip" in result) return result.clip;
650
+ if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, result.unusable);
651
+ return clip;
652
+ };
653
+ const mapTrack = (track) => {
654
+ const known = seen.get(track);
655
+ if (known) return known;
656
+ let next = track;
657
+ if (this._sourcesOf(track).loading.length > 0) {
658
+ const clips = track.clips.map((clip) => (0, import_core4.isLoadingClip)(clip) ? switched(clip) : clip);
659
+ if (clips.some((clip, i) => clip !== track.clips[i])) next = { ...track, clips };
660
+ }
661
+ seen.set(track, next);
662
+ return next;
663
+ };
664
+ const apply = (tracks) => {
665
+ const next = tracks.map(mapTrack);
666
+ return next.some((track, i) => track !== tracks[i]) ? next : tracks;
667
+ };
668
+ return {
669
+ current: (tracks) => {
670
+ inCurrentTracks = true;
671
+ try {
672
+ return apply(tracks);
673
+ } finally {
674
+ inCurrentTracks = false;
675
+ }
676
+ },
677
+ stored: (tracks) => apply(tracks)
678
+ };
679
+ }
680
+ /** After a pass over every state: publish `value` if a status changed. */
681
+ finishPass() {
682
+ const next = this._currentValue();
683
+ const previous = this.value.getSnapshot();
684
+ if (!sameValue(previous, next)) this._publish(next);
685
+ }
686
+ _resolve(clip, buffer, tickAt) {
687
+ const memo = this._resolved.get(clip);
688
+ if (memo && memo.buffer === buffer) return memo.result;
689
+ let result = resolveLoadingClip(clip, buffer);
690
+ if ("clip" in result) {
691
+ result = { clip: { ...result.clip, startTick: tickAt(result.clip.startSample) } };
692
+ }
693
+ this._resolved.set(clip, { buffer, result });
694
+ return result;
695
+ }
696
+ _sourcesOf(track) {
697
+ const known = this._trackSources.get(track);
698
+ if (known) return known;
699
+ const loading = [];
700
+ const carried = [];
701
+ for (const clip of track.clips) {
702
+ if ((0, import_core4.isLoadingClip)(clip)) loading.push(clip);
703
+ else if (clip.src !== void 0 && clip.audioBuffer)
704
+ carried.push([clip.src, clip.audioBuffer]);
705
+ }
706
+ const named = { loading, carried };
707
+ this._trackSources.set(track, named);
708
+ return named;
709
+ }
710
+ _failure(src, message) {
711
+ const shown = this.value.getSnapshot().sources.get(src)?.error;
712
+ return shown && shown.message === message ? shown : new Error(message);
713
+ }
714
+ _currentValue() {
715
+ const sources = /* @__PURE__ */ new Map();
716
+ const loaderStates = this._loader.getSnapshot();
717
+ for (const src of this._wanted) {
718
+ const state = loaderStates.get(src) ?? { status: "pending" };
719
+ const reason = this._unusable.get(src);
720
+ if (state.status === "failed") {
721
+ sources.set(src, { status: "failed", error: state.error });
722
+ } else if (state.status === "loaded" && reason !== void 0) {
723
+ sources.set(src, { status: "failed", error: this._failure(src, reason) });
724
+ } else {
725
+ sources.set(src, { status: state.status });
726
+ }
727
+ }
728
+ let pendingCount = 0;
729
+ let failedCount = 0;
730
+ for (const state of sources.values()) {
731
+ if (state.status === "pending") pendingCount++;
732
+ else if (state.status === "failed") failedCount++;
733
+ }
734
+ return { sources, pendingCount, failedCount, isLoading: pendingCount > 0 };
735
+ }
736
+ };
737
+ function sameValue(a, b) {
738
+ if (a.sources.size !== b.sources.size) return false;
739
+ for (const [src, state] of b.sources) {
740
+ const before = a.sources.get(src);
741
+ if (!before || before.status !== state.status || before.error !== state.error) return false;
742
+ }
743
+ return true;
744
+ }
745
+
746
+ // src/arrangement/history.ts
747
+ var EMPTY_HISTORY = { undo: [], redo: [] };
748
+ function pushStep(history, tracks, limit) {
749
+ const undo = [...history.undo, tracks];
750
+ return { undo: undo.length > limit ? undo.slice(undo.length - limit) : undo, redo: [] };
751
+ }
752
+ function undoStep(history, current) {
753
+ if (history.undo.length === 0) return null;
754
+ const tracks = history.undo[history.undo.length - 1];
755
+ return {
756
+ history: { undo: history.undo.slice(0, -1), redo: [...history.redo, current] },
757
+ tracks
758
+ };
759
+ }
760
+ function redoStep(history, current) {
761
+ if (history.redo.length === 0) return null;
762
+ const tracks = history.redo[history.redo.length - 1];
763
+ return {
764
+ history: { undo: [...history.undo, current], redo: history.redo.slice(0, -1) },
765
+ tracks
766
+ };
767
+ }
768
+ function beginBase(tracks) {
769
+ return { tracks, changed: false };
770
+ }
771
+ function withoutTrack(tracks, trackId) {
772
+ return tracks.some((track) => track.id === trackId) ? tracks.filter((track) => track.id !== trackId) : tracks;
773
+ }
774
+ function sameTracks(a, b) {
775
+ return a === b || a.length === b.length && a.every((track, i) => track === b[i]);
776
+ }
777
+ function purgeTrack(history, current, trackId) {
778
+ const nextCurrent = withoutTrack(current, trackId);
779
+ const undo = [];
780
+ for (const step of history.undo) {
781
+ const stripped = withoutTrack(step, trackId);
782
+ if (undo.length === 0 || !sameTracks(undo[undo.length - 1], stripped)) undo.push(stripped);
783
+ }
784
+ while (undo.length > 0 && sameTracks(undo[undo.length - 1], nextCurrent)) undo.pop();
785
+ const redoFromCurrent = [];
786
+ for (let i = history.redo.length - 1; i >= 0; i--) {
787
+ const stripped = withoutTrack(history.redo[i], trackId);
788
+ const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : nextCurrent;
789
+ if (!sameTracks(before, stripped)) redoFromCurrent.push(stripped);
790
+ }
791
+ const redo = redoFromCurrent.reverse();
792
+ const unchanged = undo.length === history.undo.length && redo.length === history.redo.length && undo.every((step, i) => step === history.undo[i]) && redo.every((step, i) => step === history.redo[i]);
793
+ return { history: unchanged ? history : { undo, redo }, current: nextCurrent };
794
+ }
795
+
796
+ // src/arrangement/mixer.ts
797
+ var EMPTY_MIXER = /* @__PURE__ */ new Map();
798
+ var DEFAULT_VOLUME = 1;
799
+ var DEFAULT_PAN = 0;
800
+ function mixerValuesOf(track) {
801
+ return {
802
+ volume: track.volume ?? DEFAULT_VOLUME,
803
+ muted: track.muted ?? false,
804
+ soloed: track.soloed ?? false,
805
+ pan: track.pan ?? DEFAULT_PAN
806
+ };
807
+ }
808
+ function seedMixer(mixer, tracks) {
809
+ let next = null;
810
+ for (const track of tracks) {
811
+ if ((next ?? mixer).has(track.id)) continue;
812
+ if (!next) next = new Map(mixer);
813
+ next.set(track.id, mixerValuesOf(track));
814
+ }
815
+ return next ?? mixer;
816
+ }
817
+ function setMixerValues(mixer, trackId, patch) {
818
+ const entry = mixer.get(trackId);
819
+ if (!entry) return mixer;
820
+ return new Map(mixer).set(trackId, { ...entry, ...patch });
821
+ }
822
+ function carryMixerEntry(mixer, fromId, toId) {
823
+ const entry = mixer.get(fromId);
824
+ if (!entry || mixer.get(toId) === entry) return mixer;
825
+ return new Map(mixer).set(toId, entry);
826
+ }
827
+ function retainMixer(mixer, states) {
828
+ const held = /* @__PURE__ */ new Set();
829
+ for (const tracks of states) {
830
+ for (const track of tracks) held.add(track.id);
831
+ }
832
+ if ([...mixer.keys()].every((id) => held.has(id))) return mixer;
833
+ return new Map([...mixer].filter(([id]) => held.has(id)));
834
+ }
835
+ function withMixerValues(track, values) {
836
+ if (!values || track.volume === values.volume && track.muted === values.muted && track.soloed === values.soloed && track.pan === values.pan) {
837
+ return track;
838
+ }
839
+ return { ...track, ...values };
840
+ }
841
+
842
+ // src/arrangement/ticks.ts
843
+ var import_core5 = require("@waveform-playlist/core");
844
+ function forLoadedClips(change) {
845
+ return (clip) => (0, import_core5.isLoadingClip)(clip) ? clip : change(clip);
846
+ }
847
+ function withClips(track, change) {
848
+ let changed = false;
849
+ const clips = track.clips.map((clip) => {
850
+ const next = change(clip);
851
+ if (next !== clip) changed = true;
852
+ return next;
853
+ });
854
+ return changed ? { ...track, clips } : track;
855
+ }
856
+ function clipMapper(change) {
857
+ const mapped = /* @__PURE__ */ new Map();
858
+ const mapTrack = (track) => {
859
+ const known = mapped.get(track);
860
+ if (known) return known;
861
+ const next = withClips(track, change);
862
+ mapped.set(track, next);
863
+ return next;
864
+ };
865
+ return (tracks) => {
866
+ const next = tracks.map(mapTrack);
867
+ return next.some((track, i) => track !== tracks[i]) ? next : tracks;
868
+ };
869
+ }
870
+ function tickPreparer(timeBase, fromPpqn) {
871
+ return clipMapper(
872
+ forLoadedClips((clip) => {
873
+ if (clip.startTick === void 0) {
874
+ const startTick2 = timeBase.secondsToTicks(clip.startSample / timeBase.sampleRate);
875
+ return { ...clip, startTick: startTick2 };
876
+ }
877
+ if (fromPpqn === null || fromPpqn === timeBase.ppqn) return clip;
878
+ const startTick = rescaleTick(clip.startTick, fromPpqn, timeBase.ppqn);
879
+ return startTick === clip.startTick ? clip : { ...clip, startTick };
880
+ })
881
+ );
882
+ }
883
+ function rescaleTick(tick, fromPpqn, toPpqn) {
884
+ return Math.round(tick * toPpqn / fromPpqn);
885
+ }
886
+
887
+ // src/arrangement/validate.ts
888
+ var import_core6 = require("@waveform-playlist/core");
889
+ function assertClipsOfTrackKind(track) {
890
+ const clips = track.clips.map(
891
+ (clip) => (0, import_core6.isLoadingClip)(clip) ? { id: clip.id, name: clip.name } : clip
892
+ );
893
+ (0, import_core6.assertTrackKind)({ ...track, clips });
894
+ }
895
+ function assertUniqueClipIds(track) {
896
+ const seen = /* @__PURE__ */ new Set();
897
+ for (const clip of track.clips) {
898
+ if (seen.has(clip.id)) {
899
+ throw new Error(
900
+ `[waveform-playlist] Track "${track.id}" has a duplicate clip id "${clip.id}". Clip ids must be unique within a track.`
901
+ );
902
+ }
903
+ seen.add(clip.id);
904
+ }
905
+ }
906
+ function assertUniqueTrackIds(tracks) {
907
+ const seen = /* @__PURE__ */ new Set();
908
+ for (const track of tracks) {
909
+ if (seen.has(track.id)) throw duplicateTrackId(track.id);
910
+ seen.add(track.id);
911
+ }
912
+ }
913
+ function duplicateTrackId(trackId) {
914
+ return new Error(
915
+ `[waveform-playlist] Duplicate track id "${trackId}". Track ids must be unique in an arrangement.`
916
+ );
917
+ }
918
+
919
+ // src/arrangement/Arrangement.ts
920
+ var DEFAULT_MIN_DURATION_SECONDS = 0.1;
921
+ var DEFAULT_UNDO_LIMIT = 100;
922
+ var ArrangementImpl = class {
923
+ constructor(options = {}) {
924
+ this._tracks = [];
925
+ this._tracksVersion = 0;
926
+ this._mixerVersion = 0;
927
+ this._mixer = EMPTY_MIXER;
928
+ this._history = EMPTY_HISTORY;
929
+ this._transaction = null;
930
+ this._subscribers = /* @__PURE__ */ new Set();
931
+ this._listeners = /* @__PURE__ */ new Set();
932
+ this._pending = [];
933
+ this._delivering = false;
934
+ /** How the clip edits convert time: through the attached engine, or not at all. */
935
+ this._clipTime = {
936
+ tickAt: (startSample) => this._tickAt(startSample),
937
+ minDuration: (clip) => this._minDuration(clip)
938
+ };
939
+ this.undoLimit = options.undoLimit ?? DEFAULT_UNDO_LIMIT;
940
+ this._timeBase = options.timeBase ?? null;
941
+ this._tickPpqn = options.timeBase?.ppqn ?? null;
942
+ this._sources = new ArrangementSources(
943
+ options.loadSource ?? defaultLoadSource,
944
+ () => this._onSourceSettled()
945
+ );
946
+ if (options.tracks) this.setTracks(options.tracks);
947
+ }
948
+ // ---------------------------------------------------------------------------
949
+ // Read
950
+ // ---------------------------------------------------------------------------
951
+ /** The tracks. The same array until something changes; never written to. */
952
+ getTracks() {
953
+ return this._tracks;
954
+ }
955
+ /**
956
+ * The current mixer values by track id. The same Map until a value
957
+ * changes, a track with a new id enters or entries are dropped; never
958
+ * written to. A track's own mixer fields in `getTracks()`
959
+ * are the values it entered with, not these.
960
+ */
961
+ getMixer() {
962
+ return this._mixer;
963
+ }
964
+ /**
965
+ * Where each source the clips name is: pending, loaded or failed. The same
966
+ * object until a status changes.
967
+ */
968
+ get sources() {
969
+ return this._sources.value;
970
+ }
971
+ /** Start a source whose LOAD failed again. See `Arrangement.retry`. */
972
+ retry(src) {
973
+ this._sources.retry(src);
974
+ }
975
+ /** The attach point of `attachDecodeContext()` (./attach.ts): a context to decode with. */
976
+ [ARRANGEMENT_ATTACH_DECODE](getContext) {
977
+ return this._sources.attachDecodeContext(getContext);
978
+ }
979
+ /** The attach point an engine uses (./attach.ts): `attachEngine`. */
980
+ [ARRANGEMENT_ATTACH_TIME_BASE](timeBase) {
981
+ return this.attachEngine(timeBase);
982
+ }
983
+ /** Counts structural changes. */
984
+ get tracksVersion() {
985
+ return this._tracksVersion;
986
+ }
987
+ /** Counts mixer changes. */
988
+ get mixerVersion() {
989
+ return this._mixerVersion;
990
+ }
991
+ /** Be told after every change. See `Arrangement.subscribe`. */
992
+ subscribe(listener) {
993
+ const entry = () => listener();
994
+ this._subscribers.add(entry);
995
+ return () => {
996
+ this._subscribers.delete(entry);
997
+ };
998
+ }
999
+ /**
1000
+ * Internal, for the engine: be told WHAT changed, before the subscribers
1001
+ * are. A listener here that throws fails the change's caller (an adapter
1002
+ * that fails must fail the call that caused it). A `'load'` has no caller
1003
+ * (audio arrived by itself): the engine catches its adapter's error for
1004
+ * that change and reports it.
1005
+ */
1006
+ onChange(listener) {
1007
+ this._listeners.add(listener);
1008
+ return () => {
1009
+ this._listeners.delete(listener);
1010
+ };
1011
+ }
1012
+ /**
1013
+ * Internal, for the engine: how to convert time, for as long as the engine
1014
+ * lives. In every state the arrangement holds (the current tracks, the
1015
+ * undo and redo states, an open transaction's base), ticks counted in
1016
+ * another engine's ppqn are converted to this one's and clips that have no
1017
+ * `startTick` yet are given one. Returns the function that detaches;
1018
+ * afterwards clips are given no ticks until the next engine attaches.
1019
+ *
1020
+ * Ticks a clip came with before any engine attached are read in the first
1021
+ * engine's ppqn. A different TEMPO is not converted: a tick is the musical
1022
+ * position, and `startSample` follows it at the next tempo change.
1023
+ */
1024
+ attachEngine(timeBase) {
1025
+ if (this._timeBase) {
1026
+ console.warn(
1027
+ "[waveform-playlist] An arrangement plays through one engine at a time: a second engine was built on an arrangement whose first engine has not been disposed. Dispose the first engine before building another."
1028
+ );
1029
+ }
1030
+ const prepare = tickPreparer(timeBase, this._tickPpqn);
1031
+ const tracks = prepare(this._tracks);
1032
+ const history = {
1033
+ undo: this._history.undo.map(prepare),
1034
+ redo: this._history.redo.map(prepare)
1035
+ };
1036
+ const transaction = this._transaction && {
1037
+ ...this._transaction,
1038
+ tracks: prepare(this._transaction.tracks)
1039
+ };
1040
+ this._timeBase = timeBase;
1041
+ this._tickPpqn = timeBase.ppqn;
1042
+ this._history = history;
1043
+ this._transaction = transaction;
1044
+ if (tracks !== this._tracks) {
1045
+ this._tracks = tracks;
1046
+ this._tracksVersion++;
1047
+ this._emit({ type: "recompute" });
1048
+ }
1049
+ return () => {
1050
+ if (this._timeBase === timeBase) this._timeBase = null;
1051
+ };
1052
+ }
1053
+ // ---------------------------------------------------------------------------
1054
+ // Undo/Redo
1055
+ // ---------------------------------------------------------------------------
1056
+ get canUndo() {
1057
+ return this._history.undo.length > 0;
1058
+ }
1059
+ get canRedo() {
1060
+ return this._history.redo.length > 0;
1061
+ }
1062
+ undo() {
1063
+ this._abortOpenTransaction();
1064
+ const step = undoStep(this._history, this._tracks);
1065
+ if (!step) return;
1066
+ this._history = step.history;
1067
+ this._restoreTracks(step.tracks);
1068
+ }
1069
+ redo() {
1070
+ this._abortOpenTransaction();
1071
+ const step = redoStep(this._history, this._tracks);
1072
+ if (!step) return;
1073
+ this._history = step.history;
1074
+ this._restoreTracks(step.tracks);
1075
+ }
1076
+ clearHistory() {
1077
+ const hadHistory = this.canUndo || this.canRedo;
1078
+ this._history = EMPTY_HISTORY;
1079
+ this._mixer = retainMixer(this._mixer, this._heldStates());
1080
+ if (hadHistory) this._emit({ type: "history" });
1081
+ }
1082
+ beginTransaction() {
1083
+ if (this._transaction) {
1084
+ console.warn(
1085
+ "[waveform-playlist/engine] beginTransaction: already in a transaction, previous snapshot will be overwritten"
1086
+ );
1087
+ }
1088
+ const replaced = this._transaction !== null;
1089
+ this._transaction = beginBase(this._tracks);
1090
+ if (replaced) this._resyncSourcesQuietly();
1091
+ }
1092
+ commitTransaction() {
1093
+ const transaction = this._transaction;
1094
+ if (!transaction) {
1095
+ console.warn("[waveform-playlist/engine] commitTransaction: no active transaction to commit");
1096
+ return;
1097
+ }
1098
+ this._transaction = null;
1099
+ if (transaction.changed && !sameTracks(transaction.tracks, this._tracks)) {
1100
+ this._pushStep(transaction.tracks);
1101
+ this._emit({ type: "history" });
1102
+ }
1103
+ }
1104
+ abortTransaction() {
1105
+ const transaction = this._transaction;
1106
+ if (!transaction) {
1107
+ console.warn("[waveform-playlist/engine] abortTransaction: no active transaction to abort");
1108
+ return;
1109
+ }
1110
+ this._abortOpenTransaction();
1111
+ }
1112
+ // ---------------------------------------------------------------------------
1113
+ // Track Management
1114
+ // ---------------------------------------------------------------------------
1115
+ // A track holds audio clips or MIDI clips, never both (#756); track ids are
1116
+ // unique, and so are clip ids within a track. The three methods that take a
1117
+ // track check it before they change anything, so a throw leaves the tracks,
1118
+ // the undo history, the mixer and every subscriber untouched.
1119
+ setTracks(tracks) {
1120
+ tracks.forEach(assertClipsOfTrackKind);
1121
+ assertUniqueTrackIds(tracks);
1122
+ tracks.forEach(assertUniqueClipIds);
1123
+ this._transaction = null;
1124
+ this._history = EMPTY_HISTORY;
1125
+ const kept = retainMixer(this._mixer, [this._tracks]);
1126
+ this._tracks = tracks.map((track) => this._ingest(track));
1127
+ this._mixer = retainMixer(seedMixer(kept, this._tracks), [this._tracks]);
1128
+ this._tracksVersion++;
1129
+ this._emit({ type: "set" });
1130
+ }
1131
+ addTrack(track) {
1132
+ assertClipsOfTrackKind(track);
1133
+ assertUniqueClipIds(track);
1134
+ if (this._tracks.some((t) => t.id === track.id)) throw duplicateTrackId(track.id);
1135
+ this._pushUndoSnapshot();
1136
+ const enriched = this._ingest(track);
1137
+ this._tracks = [...this._tracks, enriched];
1138
+ this._mixer = seedMixer(this._mixer, [enriched]);
1139
+ this._tracksVersion++;
1140
+ this._emit({ type: "add", trackId: track.id });
1141
+ }
1142
+ /**
1143
+ * Remove a track: an undo step. With `undoable: false` there is no step,
1144
+ * and the track is also taken out of every undo and redo state, so that no
1145
+ * undo or redo brings it back (a dropped file that could not be decoded).
1146
+ */
1147
+ removeTrack(trackId, options) {
1148
+ if (options?.undoable === false) {
1149
+ this._removeTrackEverywhere(trackId);
1150
+ return;
1151
+ }
1152
+ if (!this._tracks.some((t) => t.id === trackId)) return;
1153
+ this._pushUndoSnapshot();
1154
+ this._tracks = this._tracks.filter((t) => t.id !== trackId);
1155
+ this._tracksVersion++;
1156
+ this._emit({ type: "remove", trackId });
1157
+ }
1158
+ /**
1159
+ * Move a track to a new position in the track order. Purely organizational —
1160
+ * track order is not audible.
1161
+ */
1162
+ reorderTrack(trackId, toIndex) {
1163
+ const fromIndex = this._tracks.findIndex((t) => t.id === trackId);
1164
+ if (fromIndex === -1) return;
1165
+ const clamped = Math.max(0, Math.min(toIndex, this._tracks.length - 1));
1166
+ if (clamped === fromIndex) return;
1167
+ this._pushUndoSnapshot();
1168
+ const track = this._tracks[fromIndex];
1169
+ const without = this._tracks.filter((t) => t.id !== trackId);
1170
+ this._tracks = [...without.slice(0, clamped), track, ...without.slice(clamped)];
1171
+ this._tracksVersion++;
1172
+ this._emit({ type: "reorder" });
1173
+ }
1174
+ /**
1175
+ * Replace a track, with a track or with a function of the current one. The
1176
+ * mixer fields of the new track are not read: the mix is in `getMixer()`.
1177
+ * An id no track has changes nothing (a track object is still checked and
1178
+ * may throw; a function is not called for it).
1179
+ *
1180
+ * The track is copied on its way in, and so is each clip, except a clip
1181
+ * object this track already holds (one taken from `getTracks()`): that
1182
+ * one is kept as it is, so states go on sharing it and a listener can see
1183
+ * that it did not change.
1184
+ */
1185
+ updateTrack(trackId, next) {
1186
+ const current = this._tracks.find((t) => t.id === trackId);
1187
+ const byFunction = typeof next === "function";
1188
+ if (byFunction && !current) return;
1189
+ const track = byFunction ? next(current) : next;
1190
+ if (byFunction && track === current) return;
1191
+ assertClipsOfTrackKind(track);
1192
+ assertUniqueClipIds(track);
1193
+ if (track.id !== trackId && this._tracks.some((t) => t.id === track.id)) {
1194
+ throw duplicateTrackId(track.id);
1195
+ }
1196
+ if (!current) return;
1197
+ this._pushUndoSnapshot();
1198
+ const enriched = this._ingest(track, new Set(current.clips));
1199
+ this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
1200
+ this._mixer = seedMixer(carryMixerEntry(this._mixer, trackId, enriched.id), [enriched]);
1201
+ if (enriched.id !== trackId) this._mixer = retainMixer(this._mixer, this._heldStates());
1202
+ this._tracksVersion++;
1203
+ this._emit({ type: "update", trackId, previous: current });
1204
+ }
1205
+ // ---------------------------------------------------------------------------
1206
+ // Clips (the edits themselves are pure functions in ./clipEdits)
1207
+ // ---------------------------------------------------------------------------
1208
+ /** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
1209
+ getClipBounds(trackId, clipId) {
1210
+ return clipBounds(this._tracks, trackId, clipId);
1211
+ }
1212
+ /** Constrain a trim delta using the collision/bounds logic.
1213
+ * Uses the clip's current state and neighboring clips for constraints. */
1214
+ constrainTrimDelta(trackId, clipId, boundary, deltaSamples) {
1215
+ return constrainTrim(this._tracks, trackId, clipId, boundary, deltaSamples, this._clipTime);
1216
+ }
1217
+ /** Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op). */
1218
+ moveClip(trackId, clipId, deltaSamples) {
1219
+ const moved = moveClip(this._tracks, trackId, clipId, deltaSamples, this._clipTime);
1220
+ if (!moved) return 0;
1221
+ this._replaceTrack(trackId, moved.tracks);
1222
+ return moved.delta;
1223
+ }
1224
+ splitClip(trackId, clipId, atSample) {
1225
+ const next = splitClip2(this._tracks, trackId, clipId, atSample, this._clipTime);
1226
+ if (next) this._replaceTrack(trackId, next);
1227
+ }
1228
+ trimClip(trackId, clipId, boundary, deltaSamples) {
1229
+ const next = trimClip(this._tracks, trackId, clipId, boundary, deltaSamples, this._clipTime);
1230
+ if (next) this._replaceTrack(trackId, next);
1231
+ }
1232
+ // ---------------------------------------------------------------------------
1233
+ // Mixer values
1234
+ // ---------------------------------------------------------------------------
1235
+ //
1236
+ // Each replaces the Map and one entry, bumps mixerVersion and announces
1237
+ // the change. NOT structural changes: no track object is replaced,
1238
+ // tracksVersion stays (#501), and they are not undo steps. An id that is
1239
+ // not in the current tracks does nothing.
1240
+ setTrackVolume(trackId, volume) {
1241
+ this._setMixerValues(trackId, { volume });
1242
+ }
1243
+ setTrackMute(trackId, muted) {
1244
+ this._setMixerValues(trackId, { muted });
1245
+ }
1246
+ setTrackSolo(trackId, soloed) {
1247
+ this._setMixerValues(trackId, { soloed });
1248
+ }
1249
+ setTrackPan(trackId, pan) {
1250
+ this._setMixerValues(trackId, { pan });
1251
+ }
1252
+ // ---------------------------------------------------------------------------
1253
+ // Tempo
1254
+ // ---------------------------------------------------------------------------
1255
+ /** Re-derive `startSample` from `startTick` for every clip that has one (after a tempo change). */
1256
+ recomputeStartSamples() {
1257
+ if (!this._timeBase) return;
1258
+ const { ticksToSeconds, sampleRate } = this._timeBase;
1259
+ this._tracks = this._tracks.map(
1260
+ (track) => withClips(
1261
+ track,
1262
+ forLoadedClips((clip) => {
1263
+ if (clip.startTick === void 0) return clip;
1264
+ const startSample = Math.round(ticksToSeconds(clip.startTick) * sampleRate);
1265
+ return startSample === clip.startSample ? clip : { ...clip, startSample };
1266
+ })
1267
+ )
1268
+ );
1269
+ this._tracksVersion++;
1270
+ this._emit({ type: "recompute" });
1271
+ }
1272
+ // ---------------------------------------------------------------------------
1273
+ // Private helpers
1274
+ // ---------------------------------------------------------------------------
1275
+ /** The tracks after an edit of one track: an undo step, the new array, the announcement. */
1276
+ _replaceTrack(trackId, tracks) {
1277
+ const previous = this._tracks.find((t) => t.id === trackId);
1278
+ this._pushUndoSnapshot();
1279
+ this._tracks = tracks;
1280
+ this._tracksVersion++;
1281
+ this._emit({ type: "update", trackId, previous });
1282
+ }
1283
+ /**
1284
+ * The tick of a sample position. Without an engine there is no tempo to
1285
+ * convert with, so there is no tick: a clip that is placed, moved or cut
1286
+ * meanwhile has none, and is given one when the next engine attaches.
1287
+ */
1288
+ _tickAt(startSample) {
1289
+ if (!this._timeBase) return void 0;
1290
+ return this._timeBase.secondsToTicks(startSample / this._timeBase.sampleRate);
1291
+ }
1292
+ /** The shortest a clip may be: a tenth of a second, at the engine's rate or else the clip's own. */
1293
+ _minDuration(clip) {
1294
+ const sampleRate = this._timeBase?.sampleRate ?? clip.sampleRate;
1295
+ return Math.floor(DEFAULT_MIN_DURATION_SECONDS * sampleRate);
1296
+ }
1297
+ /**
1298
+ * A copy of a track on its way in, with a `startTick` on every clip when
1299
+ * an engine is attached (and none added when there is no engine). The track and each clip are copied, so the
1300
+ * arrangement holds no object its caller can still write to; a clip in
1301
+ * `held` is one the arrangement already holds and is kept as it is.
1302
+ */
1303
+ _ingest(track, held) {
1304
+ return {
1305
+ ...track,
1306
+ clips: track.clips.map((clip) => {
1307
+ if (held?.has(clip)) return clip;
1308
+ if ((0, import_core7.isLoadingClip)(clip)) return { ...clip };
1309
+ return { ...clip, startTick: clip.startTick ?? this._tickAt(clip.startSample) };
1310
+ })
1311
+ };
1312
+ }
1313
+ _setMixerValues(trackId, values) {
1314
+ if (!this._tracks.some((t) => t.id === trackId)) return;
1315
+ const next = setMixerValues(this._mixer, trackId, values);
1316
+ if (next === this._mixer) return;
1317
+ this._mixer = next;
1318
+ this._mixerVersion++;
1319
+ this._emit({ type: "mixer", trackId, values });
1320
+ }
1321
+ /** Every tracks array the arrangement can still return to, and the current one. */
1322
+ _heldStates() {
1323
+ return [
1324
+ this._tracks,
1325
+ ...this._history.undo,
1326
+ ...this._history.redo,
1327
+ ...this._transaction ? [this._transaction.tracks] : []
1328
+ ];
1329
+ }
1330
+ /** `removeTrack` with `undoable: false`: out of the current tracks and out of every stored state. */
1331
+ _removeTrackEverywhere(trackId) {
1332
+ const wasThere = this._tracks.some((t) => t.id === trackId);
1333
+ const purged = purgeTrack(this._history, this._tracks, trackId);
1334
+ const historyChanged = purged.history !== this._history;
1335
+ this._history = purged.history;
1336
+ if (this._transaction) {
1337
+ this._transaction = {
1338
+ ...this._transaction,
1339
+ tracks: withoutTrack(this._transaction.tracks, trackId)
1340
+ };
1341
+ }
1342
+ this._tracks = purged.current;
1343
+ this._mixer = retainMixer(this._mixer, this._heldStates());
1344
+ if (wasThere) {
1345
+ this._tracksVersion++;
1346
+ this._emit({ type: "remove", trackId });
1347
+ } else if (historyChanged) {
1348
+ this._emit({ type: "history" });
1349
+ } else {
1350
+ this._resyncSourcesQuietly();
1351
+ }
1352
+ }
1353
+ /** The state before a change: an undo step, or the mark that an open transaction changed. */
1354
+ _pushUndoSnapshot() {
1355
+ if (this._transaction) {
1356
+ if (!this._transaction.changed) {
1357
+ this._transaction = { ...this._transaction, changed: true };
1358
+ }
1359
+ return;
1360
+ }
1361
+ this._pushStep(this._tracks);
1362
+ }
1363
+ /** Add an undo step. The history may let go of states with it (the redo stack, a step past the limit). */
1364
+ _pushStep(tracks) {
1365
+ const letsGo = this._history.redo.length > 0 || this._history.undo.length >= this.undoLimit;
1366
+ this._history = pushStep(this._history, tracks, this.undoLimit);
1367
+ if (letsGo) this._mixer = retainMixer(this._mixer, this._heldStates());
1368
+ }
1369
+ _restoreTracks(snapshot) {
1370
+ const previous = this._tracks;
1371
+ this._tracks = snapshot;
1372
+ this._tracksVersion++;
1373
+ this._emit({ type: "restore", previous });
1374
+ }
1375
+ /** Ends an open transaction, restoring the tracks it began from if it changed them. */
1376
+ _abortOpenTransaction() {
1377
+ const transaction = this._transaction;
1378
+ if (!transaction) return;
1379
+ this._transaction = null;
1380
+ if (transaction.changed) {
1381
+ this._restoreTracks(transaction.tracks);
1382
+ }
1383
+ }
1384
+ /** Declare the sources every state names, and switch the clips whose audio is there. */
1385
+ _syncSources() {
1386
+ this._sources.declare(this._heldStates());
1387
+ return this._switchLoaded();
1388
+ }
1389
+ /** The stored states changed with nothing to announce: the sources they name may have. */
1390
+ _resyncSourcesQuietly() {
1391
+ this._syncSources();
1392
+ this._sources.finishPass();
1393
+ }
1394
+ /**
1395
+ * Replace every loading clip whose source is loaded with its loaded clip,
1396
+ * in the current tracks and in every state the arrangement can return to.
1397
+ * The same loading-clip object becomes the same loaded clip everywhere, and
1398
+ * states go on sharing the tracks they shared. Not an undo step. Returns
1399
+ * the current tracks from before, or null when they did not change.
1400
+ */
1401
+ _switchLoaded() {
1402
+ const pass = this._sources.beginPass((startSample) => this._tickAt(startSample));
1403
+ const previous = this._tracks;
1404
+ this._tracks = pass.current(previous);
1405
+ this._history = {
1406
+ undo: this._history.undo.map(pass.stored),
1407
+ redo: this._history.redo.map(pass.stored)
1408
+ };
1409
+ if (this._transaction) {
1410
+ this._transaction = { ...this._transaction, tracks: pass.stored(this._transaction.tracks) };
1411
+ }
1412
+ return this._tracks === previous ? null : previous;
1413
+ }
1414
+ /** A load finished or failed by itself (not inside one of this arrangement's methods). */
1415
+ _onSourceSettled() {
1416
+ const previous = this._switchLoaded();
1417
+ if (previous) {
1418
+ this._tracksVersion++;
1419
+ this._emit({ type: "load", previous });
1420
+ } else {
1421
+ this._sources.finishPass();
1422
+ }
1423
+ }
1424
+ /**
1425
+ * Announce a change. Called after the state has changed. When a listener
1426
+ * makes a change of its own, that change waits here until the one being
1427
+ * delivered has reached every listener, so all of them see the changes in
1428
+ * the order they were made.
1429
+ *
1430
+ * A listener that throws does not stop the delivery; the first error is
1431
+ * thrown to the caller once everyone has been told (the engine's listener
1432
+ * throws when its adapter does, and the caller of the engine method has
1433
+ * always received that error).
1434
+ */
1435
+ _emit(change) {
1436
+ const switched = change.type === "mixer" ? null : this._syncSources();
1437
+ freezeTracksInDevelopment(this._tracks);
1438
+ if (change.type === "remove" || change.type === "restore") {
1439
+ this._mixer = retainMixer(this._mixer, this._heldStates());
1440
+ }
1441
+ const at = {
1442
+ tracksVersion: this._tracksVersion,
1443
+ mixerVersion: this._mixerVersion
1444
+ };
1445
+ if (switched && (change.type === "add" || change.type === "update")) at.switched = switched;
1446
+ this._pending.push({ change, at });
1447
+ if (this._delivering) return;
1448
+ this._delivering = true;
1449
+ let failed = false;
1450
+ let firstError;
1451
+ try {
1452
+ for (let next = this._pending.shift(); next; next = this._pending.shift()) {
1453
+ for (const listener of [...this._listeners]) {
1454
+ try {
1455
+ listener(next.change, next.at);
1456
+ } catch (error) {
1457
+ if (!failed) {
1458
+ failed = true;
1459
+ firstError = error;
1460
+ }
1461
+ }
1462
+ }
1463
+ for (const subscriber of [...this._subscribers]) {
1464
+ try {
1465
+ subscriber();
1466
+ } catch (error) {
1467
+ console.warn("[waveform-playlist] Error in an arrangement subscriber:", error);
1468
+ }
1469
+ }
1470
+ }
1471
+ } finally {
1472
+ this._delivering = false;
1473
+ }
1474
+ this._sources.finishPass();
1475
+ if (failed) throw firstError;
1476
+ }
1477
+ };
1478
+
1479
+ // src/arrangement/index.ts
1480
+ function createArrangement(options = {}) {
1481
+ return new ArrangementImpl(options);
1482
+ }
1483
+
1484
+ // src/adapterSync.ts
1485
+ var import_core8 = require("@waveform-playlist/core");
1486
+ var AdapterSync = class {
1487
+ constructor(_arrangement, _adapter) {
1488
+ this._arrangement = _arrangement;
1489
+ this._adapter = _adapter;
1490
+ /**
1491
+ * The `tracksVersion` of each change made with `skipAdapter`. A change is
1492
+ * delivered later than it is made when it comes from inside a listener, so
1493
+ * the mark travels with the change's version, not with the call.
1494
+ */
1495
+ this._skipAt = /* @__PURE__ */ new Set();
1496
+ /**
1497
+ * The arrangement's `tracksVersion` when the adapter was last sent every
1498
+ * track. A change that is delivered later than it was made (from inside a
1499
+ * listener) may already be in what the adapter was sent.
1500
+ */
1501
+ this._syncedTracksVersion = -1;
1502
+ /**
1503
+ * An adapter call for a track change threw, so what the adapter holds is
1504
+ * not known: the next track change sends it every track.
1505
+ */
1506
+ this._needsAllTracks = false;
1507
+ this._projection = null;
1508
+ this._withMixMemo = /* @__PURE__ */ new WeakMap();
1509
+ /** Per track object of the arrangement that holds a loading clip: the track without them. */
1510
+ this._loadedMemo = /* @__PURE__ */ new WeakMap();
1511
+ }
1512
+ /**
1513
+ * The arrangement's tracks, each without its loading clips and with the
1514
+ * current mixer values in its fields: what every adapter track call and
1515
+ * `getState().tracks` use. The same
1516
+ * array until the tracks or the mix change, and the same track object
1517
+ * while neither that track nor its mix changed.
1518
+ */
1519
+ tracks() {
1520
+ const { tracksVersion, mixerVersion } = this._arrangement;
1521
+ const cached = this._projection;
1522
+ if (cached && cached.tracksVersion === tracksVersion && cached.mixerVersion === mixerVersion) {
1523
+ return cached.tracks;
1524
+ }
1525
+ const tracks = freezeTracksInDevelopment(
1526
+ this._arrangement.getTracks().map((track) => this._project(track))
1527
+ );
1528
+ this._projection = { tracksVersion, mixerVersion, tracks };
1529
+ return tracks;
1530
+ }
1531
+ /** When an engine attaches: send the tracks that are there. With none, the adapter is in step as it is. */
1532
+ sendInitialTracks() {
1533
+ if (this._arrangement.getTracks().length > 0) {
1534
+ this.sendAllTracks();
1535
+ } else {
1536
+ this._syncedTracksVersion = this._arrangement.tracksVersion;
1537
+ }
1538
+ }
1539
+ /** Send the adapter every track, and remember up to which change that covers. */
1540
+ sendAllTracks() {
1541
+ const version = this._arrangement.tracksVersion;
1542
+ this._adapter?.setTracks(this.tracks());
1543
+ this._syncedTracksVersion = version;
1544
+ }
1545
+ /** Send the arrangement's current track to the adapter. False when there is no such track. */
1546
+ sendTrack(trackId) {
1547
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1548
+ if (!track) return false;
1549
+ if (this._adapter?.updateTrack) {
1550
+ this._adapter.updateTrack(trackId, this._project(track));
1551
+ } else {
1552
+ this.sendAllTracks();
1553
+ }
1554
+ return true;
1555
+ }
1556
+ /** A mixer value changed: the adapter's setter for it. */
1557
+ sendMixerValues(trackId, values) {
1558
+ if (values.volume !== void 0) this._adapter?.setTrackVolume(trackId, values.volume);
1559
+ if (values.muted !== void 0) this._adapter?.setTrackMute(trackId, values.muted);
1560
+ if (values.soloed !== void 0) this._adapter?.setTrackSolo(trackId, values.soloed);
1561
+ if (values.pan !== void 0) this._adapter?.setTrackPan(trackId, values.pan);
1562
+ }
1563
+ /**
1564
+ * The adapter call for a change to the tracks.
1565
+ *
1566
+ * A change made from inside a listener is delivered later than it was
1567
+ * made. If the tracks have changed again by then, what this change did
1568
+ * cannot be told from the current tracks alone: the adapter is sent every
1569
+ * track, once, and the changes still waiting are then already sent.
1570
+ */
1571
+ follow(change, at) {
1572
+ const skipped = change.type === "update" && this._skipAt.delete(at.tracksVersion);
1573
+ if (skipped || at.tracksVersion <= this._syncedTracksVersion) return;
1574
+ const needsAllTracks = this._needsAllTracks;
1575
+ this._needsAllTracks = true;
1576
+ if (needsAllTracks || at.tracksVersion < this._arrangement.tracksVersion) {
1577
+ this.sendAllTracks();
1578
+ } else {
1579
+ this._sendChange(change);
1580
+ if (at.switched && this._syncedTracksVersion < at.tracksVersion) this._restore(at.switched);
1581
+ }
1582
+ this._needsAllTracks = false;
1583
+ }
1584
+ /**
1585
+ * Before a change made with `skipAdapter`: mark the version that change
1586
+ * will have. Returns the mark, or null without `skipAdapter`.
1587
+ */
1588
+ markSkip(skipAdapter) {
1589
+ if (!skipAdapter) return null;
1590
+ const mark = this._arrangement.tracksVersion + 1;
1591
+ this._skipAt.add(mark);
1592
+ return mark;
1593
+ }
1594
+ /** After the call: a call that changed nothing has no change to carry its mark. */
1595
+ unmarkIfUnchanged(mark) {
1596
+ if (mark !== null && this._arrangement.tracksVersion < mark) {
1597
+ this._skipAt.delete(mark);
1598
+ }
1599
+ }
1600
+ /** One change, made just now, as the adapter call that brings it in step. */
1601
+ _sendChange(change) {
1602
+ switch (change.type) {
1603
+ case "set":
1604
+ this.sendAllTracks();
1605
+ break;
1606
+ case "add":
1607
+ this._addTrack(change.trackId);
1608
+ break;
1609
+ case "remove":
1610
+ if (this._adapter?.removeTrack) {
1611
+ this._adapter.removeTrack(change.trackId);
1612
+ } else {
1613
+ this.sendAllTracks();
1614
+ }
1615
+ break;
1616
+ case "update":
1617
+ if (this._playsTheSame(change.previous, change.trackId)) break;
1618
+ if (!this.sendTrack(change.trackId)) this.sendAllTracks();
1619
+ break;
1620
+ case "restore":
1621
+ case "load":
1622
+ this._restore(change.previous);
1623
+ break;
1624
+ case "recompute":
1625
+ for (const track of this._arrangement.getTracks()) {
1626
+ this.sendTrack(track.id);
1627
+ }
1628
+ break;
1629
+ }
1630
+ }
1631
+ _addTrack(trackId) {
1632
+ const track = this._arrangement.getTracks().find((t) => t.id === trackId);
1633
+ if (track && this._adapter?.addTrack) {
1634
+ this._adapter.addTrack(this._project(track));
1635
+ } else {
1636
+ this.sendAllTracks();
1637
+ }
1638
+ }
1639
+ /**
1640
+ * After an undo, a redo or an abort. Use incremental adapter updates when
1641
+ * the same tracks are there before and after — avoids full playout rebuild
1642
+ * that interrupts playback. A track the restore did not touch is the same
1643
+ * object in both states and is skipped; so is a change of order only.
1644
+ */
1645
+ _restore(previous) {
1646
+ const restored = this._arrangement.getTracks();
1647
+ const oldById = new Map(previous.map((t) => [t.id, t]));
1648
+ const sameSet = previous.length === restored.length && restored.every((t) => oldById.has(t.id));
1649
+ if (this._adapter && sameSet) {
1650
+ for (const track of restored) {
1651
+ const old = oldById.get(track.id);
1652
+ if (!this._playsTheSame(old, track.id)) this.sendTrack(track.id);
1653
+ }
1654
+ } else {
1655
+ this.sendAllTracks();
1656
+ }
1657
+ }
1658
+ /**
1659
+ * True when the arrangement's current track of that id is, for an adapter,
1660
+ * what `previous` was: the same loaded clip objects in the same order and
1661
+ * the same fields. Only its loading clips differ, and an adapter is not
1662
+ * given those, so there is nothing to send.
1663
+ */
1664
+ _playsTheSame(previous, trackId) {
1665
+ const current = this._arrangement.getTracks().find((t) => t.id === trackId);
1666
+ if (!current) return false;
1667
+ if (current === previous) return true;
1668
+ const before = this._loaded(previous);
1669
+ const now = this._loaded(current);
1670
+ if (before.clips.length !== now.clips.length) return false;
1671
+ if (before.clips.some((clip, i) => clip !== now.clips[i])) return false;
1672
+ const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(now)]);
1673
+ keys.delete("clips");
1674
+ return [...keys].every((key) => Object.is(before[key], now[key]));
1675
+ }
1676
+ /** What an adapter and `getState()` are given for one of the arrangement's tracks. */
1677
+ _project(track) {
1678
+ return this._withMix(this._loaded(track));
1679
+ }
1680
+ /**
1681
+ * The track without the clips that are still loading: an adapter plays
1682
+ * loaded clips only. A track that holds none is the arrangement's own
1683
+ * object (memoized per track object otherwise).
1684
+ */
1685
+ _loaded(track) {
1686
+ const known = this._loadedMemo.get(track);
1687
+ if (known) return known;
1688
+ const clips = track.clips.filter((clip) => !(0, import_core8.isLoadingClip)(clip));
1689
+ const loaded = clips.length === track.clips.length ? track : { ...track, clips };
1690
+ this._loadedMemo.set(track, loaded);
1691
+ return loaded;
1692
+ }
1693
+ /** One track with its current mixer values in its fields (memoized per track object). */
1694
+ _withMix(track) {
1695
+ const values = this._arrangement.getMixer().get(track.id);
1696
+ const memo = this._withMixMemo.get(track);
1697
+ if (memo && memo.values === values) return memo.merged;
1698
+ const merged = freezeTrackInDevelopment(withMixerValues(track, values));
1699
+ this._withMixMemo.set(track, { values, merged });
1700
+ return merged;
1701
+ }
1702
+ };
1703
+
187
1704
  // src/PlaylistEngine.ts
188
- var import_core2 = require("@waveform-playlist/core");
189
1705
  var DEFAULT_SAMPLE_RATE = 48e3;
190
1706
  var DEFAULT_SAMPLES_PER_PIXEL = 1024;
191
1707
  var DEFAULT_ZOOM_LEVELS = [256, 512, 1024, 2048, 4096, 8192];
192
- var DEFAULT_MIN_DURATION_SECONDS = 0.1;
193
1708
  var PlaylistEngine = class {
194
1709
  constructor(options = {}) {
195
- this._tracks = [];
1710
+ this._detachDecodeContext = null;
196
1711
  this._currentTime = 0;
197
1712
  this._playStartPosition = 0;
198
1713
  this._isPlaying = false;
@@ -203,20 +1718,12 @@ var PlaylistEngine = class {
203
1718
  this._loopStart = 0;
204
1719
  this._loopEnd = 0;
205
1720
  this._isLoopEnabled = false;
206
- this._tracksVersion = 0;
207
- this._mixerVersion = 0;
208
1721
  this._disposed = false;
209
1722
  // eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
210
1723
  this._listeners = /* @__PURE__ */ new Map();
211
- this._undoStack = [];
212
- this._redoStack = [];
213
- this._inTransaction = false;
214
- this._transactionSnapshot = null;
215
- this._transactionMutated = false;
216
1724
  this._sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
217
1725
  this._zoomLevels = [...options.zoomLevels ?? DEFAULT_ZOOM_LEVELS];
218
1726
  this._adapter = options.adapter ?? null;
219
- this.undoLimit = options.undoLimit ?? 100;
220
1727
  this._adapter?.onPlaybackEnded?.(() => {
221
1728
  queueMicrotask(() => {
222
1729
  if (this._isPlaying && !this._disposed) {
@@ -237,81 +1744,79 @@ var PlaylistEngine = class {
237
1744
  this._zoomIndex = zoomIndex;
238
1745
  this._bpm = options.bpm ?? 120;
239
1746
  this._ppqn = options.adapter?.ppqn ?? options.ppqn ?? 960;
1747
+ const timeBase = {
1748
+ sampleRate: this._sampleRate,
1749
+ ppqn: this._ppqn,
1750
+ secondsToTicks: (seconds) => this._secondsToTicks(seconds),
1751
+ ticksToSeconds: (tick) => this._ticksToSeconds(tick)
1752
+ };
1753
+ if (options.arrangement) {
1754
+ this._arrangement = asArrangementImpl(options.arrangement);
1755
+ if (options.undoLimit !== void 0) {
1756
+ console.warn(
1757
+ "[waveform-playlist] PlaylistEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
1758
+ );
1759
+ }
1760
+ } else {
1761
+ this._arrangement = new ArrangementImpl({ undoLimit: options.undoLimit });
1762
+ }
1763
+ this.undoLimit = this._arrangement.undoLimit;
1764
+ this._detachFromArrangement = attachTimeBase(this._arrangement, timeBase);
1765
+ this._adapterSync = new AdapterSync(this._arrangement, this._adapter);
1766
+ this._stopFollowingArrangement = this._arrangement.onChange(
1767
+ (change, at) => this._onArrangementChange(change, at)
1768
+ );
1769
+ try {
1770
+ this._adapterSync.sendInitialTracks();
1771
+ } catch (error) {
1772
+ this._stopFollowingArrangement();
1773
+ this._detachFromArrangement();
1774
+ throw error;
1775
+ }
1776
+ const adapter = this._adapter;
1777
+ if (adapter && options.attachDecodeContext !== false) {
1778
+ this._detachDecodeContext = attachDecodeContext(
1779
+ this._arrangement,
1780
+ async () => adapter.audioContext
1781
+ );
1782
+ }
240
1783
  }
241
1784
  // ---------------------------------------------------------------------------
242
1785
  // Undo/Redo
243
1786
  // ---------------------------------------------------------------------------
244
1787
  get canUndo() {
245
- return this._undoStack.length > 0;
1788
+ return this._arrangement.canUndo;
246
1789
  }
247
1790
  get canRedo() {
248
- return this._redoStack.length > 0;
1791
+ return this._arrangement.canRedo;
249
1792
  }
250
1793
  undo() {
251
- if (this._undoStack.length === 0) return;
252
- const snapshot = this._undoStack.pop();
253
- this._redoStack.push(this._snapshotTracks());
254
- this._restoreTracks(snapshot);
1794
+ this._arrangement.undo();
255
1795
  }
256
1796
  redo() {
257
- if (this._redoStack.length === 0) return;
258
- const snapshot = this._redoStack.pop();
259
- this._undoStack.push(this._snapshotTracks());
260
- this._restoreTracks(snapshot);
1797
+ this._arrangement.redo();
261
1798
  }
262
1799
  clearHistory() {
263
- this._undoStack = [];
264
- this._redoStack = [];
1800
+ this._arrangement.clearHistory();
265
1801
  }
266
1802
  beginTransaction() {
267
- if (this._inTransaction) {
268
- console.warn(
269
- "[waveform-playlist/engine] beginTransaction: already in a transaction, previous snapshot will be overwritten"
270
- );
271
- }
272
- this._transactionSnapshot = this._snapshotTracks();
273
- this._inTransaction = true;
274
- this._transactionMutated = false;
1803
+ this._arrangement.beginTransaction();
275
1804
  }
276
1805
  commitTransaction() {
277
- if (!this._inTransaction || this._transactionSnapshot === null) {
278
- console.warn("[waveform-playlist/engine] commitTransaction: no active transaction to commit");
279
- return;
280
- }
281
- if (this._transactionMutated) {
282
- this._undoStack.push(this._transactionSnapshot);
283
- if (this._undoStack.length > this.undoLimit) {
284
- this._undoStack.shift();
285
- }
286
- this._redoStack = [];
287
- }
288
- this._transactionSnapshot = null;
289
- this._inTransaction = false;
290
- this._transactionMutated = false;
1806
+ this._arrangement.commitTransaction();
291
1807
  }
292
1808
  abortTransaction() {
293
- if (!this._inTransaction || this._transactionSnapshot === null) {
294
- console.warn("[waveform-playlist/engine] abortTransaction: no active transaction to abort");
295
- return;
296
- }
297
- const snapshot = this._transactionSnapshot;
298
- const mutated = this._transactionMutated;
299
- this._transactionSnapshot = null;
300
- this._inTransaction = false;
301
- this._transactionMutated = false;
302
- if (mutated) {
303
- this._restoreTracks(snapshot);
304
- }
1809
+ this._arrangement.abortTransaction();
305
1810
  }
306
1811
  // ---------------------------------------------------------------------------
307
1812
  // State snapshot
308
1813
  // ---------------------------------------------------------------------------
309
1814
  getState() {
310
1815
  return {
311
- tracks: this._tracks.map((t) => ({ ...t, clips: [...t.clips] })),
312
- tracksVersion: this._tracksVersion,
313
- mixerVersion: this._mixerVersion,
314
- duration: calculateDuration(this._tracks),
1816
+ tracks: this._adapterSync.tracks(),
1817
+ tracksVersion: this._arrangement.tracksVersion,
1818
+ mixerVersion: this._arrangement.mixerVersion,
1819
+ duration: calculateDuration(this._adapterSync.tracks()),
315
1820
  currentTime: this._currentTime,
316
1821
  isPlaying: this._isPlaying,
317
1822
  samplesPerPixel: this._zoomLevels[this._zoomIndex],
@@ -335,51 +1840,17 @@ var PlaylistEngine = class {
335
1840
  // ---------------------------------------------------------------------------
336
1841
  // Track Management
337
1842
  // ---------------------------------------------------------------------------
1843
+ // A track holds audio clips or MIDI clips, never both (#756). The three
1844
+ // methods that take a track check it before they change anything, so a
1845
+ // throw leaves the engine, the undo history and the adapter untouched.
338
1846
  setTracks(tracks) {
339
- this.clearHistory();
340
- this._tracks = tracks.map((track) => ({
341
- ...track,
342
- clips: track.clips.map((clip) => ({
343
- ...clip,
344
- startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
345
- }))
346
- }));
347
- this._tracksVersion++;
348
- this._adapter?.setTracks(this._tracks);
349
- this._emitStateChange();
1847
+ this._arrangement.setTracks(tracks);
350
1848
  }
351
1849
  addTrack(track) {
352
- this._pushUndoSnapshot();
353
- const enriched = {
354
- ...track,
355
- clips: track.clips.map((clip) => ({
356
- ...clip,
357
- startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
358
- }))
359
- };
360
- this._tracks = [...this._tracks, enriched];
361
- this._tracksVersion++;
362
- if (this._adapter?.addTrack) {
363
- this._adapter.addTrack(enriched);
364
- } else {
365
- this._adapter?.setTracks(this._tracks);
366
- }
367
- this._emitStateChange();
1850
+ this._arrangement.addTrack(track);
368
1851
  }
369
1852
  removeTrack(trackId) {
370
- if (!this._tracks.some((t) => t.id === trackId)) return;
371
- this._pushUndoSnapshot();
372
- this._tracks = this._tracks.filter((t) => t.id !== trackId);
373
- this._tracksVersion++;
374
- if (this._selectedTrackId === trackId) {
375
- this._selectedTrackId = null;
376
- }
377
- if (this._adapter?.removeTrack) {
378
- this._adapter.removeTrack(trackId);
379
- } else {
380
- this._adapter?.setTracks(this._tracks);
381
- }
382
- this._emitStateChange();
1853
+ this._arrangement.removeTrack(trackId);
383
1854
  }
384
1855
  /**
385
1856
  * Move a track to a new position in the track order. Purely organizational —
@@ -388,55 +1859,18 @@ var PlaylistEngine = class {
388
1859
  * playout and interrupt playback for a visual-only change.
389
1860
  */
390
1861
  reorderTrack(trackId, toIndex) {
391
- const fromIndex = this._tracks.findIndex((t) => t.id === trackId);
392
- if (fromIndex === -1) return;
393
- const clamped = Math.max(0, Math.min(toIndex, this._tracks.length - 1));
394
- if (clamped === fromIndex) return;
395
- this._pushUndoSnapshot();
396
- const track = this._tracks[fromIndex];
397
- const without = this._tracks.filter((t) => t.id !== trackId);
398
- this._tracks = [...without.slice(0, clamped), track, ...without.slice(clamped)];
399
- this._tracksVersion++;
400
- this._emitStateChange();
1862
+ this._arrangement.reorderTrack(trackId, toIndex);
401
1863
  }
402
- /** Update a single track's clips on the adapter (no full rebuild). */
1864
+ /**
1865
+ * With a track: replace that track (an undo step). Without one: send the
1866
+ * current track to the adapter again (no full rebuild, no change of state).
1867
+ */
403
1868
  updateTrack(trackId, track) {
404
- const resolved = track ?? this._tracks.find((t) => t.id === trackId);
405
- if (!resolved) return;
406
1869
  if (track) {
407
- this._pushUndoSnapshot();
408
- const enriched = {
409
- ...track,
410
- clips: track.clips.map((clip) => ({
411
- ...clip,
412
- startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
413
- }))
414
- };
415
- this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
416
- this._tracksVersion++;
417
- if (this._adapter?.updateTrack) {
418
- this._adapter.updateTrack(trackId, enriched);
419
- } else {
420
- this._adapter?.setTracks(this._tracks);
421
- }
422
- this._emitStateChange();
1870
+ this._arrangement.updateTrack(trackId, track);
423
1871
  return;
424
1872
  }
425
- if (this._adapter?.updateTrack) {
426
- this._adapter.updateTrack(trackId, resolved);
427
- } else {
428
- this._adapter?.setTracks(this._tracks);
429
- }
430
- }
431
- /** Internal: update adapter after modifying this._tracks in place. */
432
- _updateTrackOnAdapter(trackId) {
433
- const t = this._tracks.find((tr) => tr.id === trackId);
434
- if (!t) return;
435
- if (this._adapter?.updateTrack) {
436
- this._adapter.updateTrack(trackId, t);
437
- } else {
438
- this._adapter?.setTracks(this._tracks);
439
- }
1873
+ if (!this._disposed) this._adapterSync.sendTrack(trackId);
440
1874
  }
441
1875
  selectTrack(trackId) {
442
1876
  if (trackId === this._selectedTrackId) return;
@@ -448,166 +1882,38 @@ var PlaylistEngine = class {
448
1882
  // ---------------------------------------------------------------------------
449
1883
  /** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
450
1884
  getClipBounds(trackId, clipId) {
451
- const track = this._tracks.find((t) => t.id === trackId);
452
- if (!track) return null;
453
- const clip = track.clips.find((c) => c.id === clipId);
454
- if (!clip) return null;
455
- return {
456
- offsetSamples: clip.offsetSamples,
457
- durationSamples: clip.durationSamples,
458
- startSample: clip.startSample,
459
- sourceDurationSamples: clip.sourceDurationSamples
460
- };
1885
+ return this._arrangement.getClipBounds(trackId, clipId);
461
1886
  }
462
1887
  /** Constrain a trim delta using the engine's collision/bounds logic.
463
1888
  * Uses the clip's current state and neighboring clips for constraints. */
464
1889
  constrainTrimDelta(trackId, clipId, boundary, deltaSamples) {
465
- const track = this._tracks.find((t) => t.id === trackId);
466
- if (!track) return 0;
467
- const clipIndex = track.clips.findIndex((c) => c.id === clipId);
468
- if (clipIndex === -1) return 0;
469
- const clip = track.clips[clipIndex];
470
- const sortedClips = (0, import_core2.sortClipsByTime)(track.clips);
471
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
472
- const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
473
- return constrainBoundaryTrim(
474
- clip,
475
- deltaSamples,
476
- boundary,
477
- sortedClips,
478
- sortedIndex,
479
- minDuration
480
- );
1890
+ return this._arrangement.constrainTrimDelta(trackId, clipId, boundary, deltaSamples);
481
1891
  }
482
1892
  // ---------------------------------------------------------------------------
483
- // Clip Editing (delegates to operations/)
1893
+ // Clip Editing (delegates to the arrangement)
484
1894
  // ---------------------------------------------------------------------------
485
- /** Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op). */
1895
+ /**
1896
+ * Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op).
1897
+ * With `skipAdapter` the change is not sent to the adapter (a drag sends the track once, on drop).
1898
+ */
486
1899
  moveClip(trackId, clipId, deltaSamples, skipAdapter = false) {
487
- const track = this._tracks.find((t) => t.id === trackId);
488
- if (!track) {
489
- console.warn(`[waveform-playlist/engine] moveClip: track "${trackId}" not found`);
490
- return 0;
491
- }
492
- const clipIndex = track.clips.findIndex((c) => c.id === clipId);
493
- if (clipIndex === -1) {
494
- console.warn(
495
- `[waveform-playlist/engine] moveClip: clip "${clipId}" not found in track "${trackId}"`
496
- );
497
- return 0;
498
- }
499
- const clip = track.clips[clipIndex];
500
- const sortedClips = (0, import_core2.sortClipsByTime)(track.clips);
501
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
502
- const constrainedDelta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
503
- if (constrainedDelta === 0) return 0;
504
- this._pushUndoSnapshot();
505
- this._tracks = this._tracks.map((t) => {
506
- if (t.id !== trackId) return t;
507
- const newClips = t.clips.map((c, i) => {
508
- if (i !== clipIndex) return c;
509
- const newStartSample = Math.floor(c.startSample + constrainedDelta);
510
- return {
511
- ...c,
512
- startSample: newStartSample,
513
- startTick: c.startTick !== void 0 ? this._secondsToTicks(newStartSample / this._sampleRate) : void 0
514
- };
515
- });
516
- return { ...t, clips: newClips };
517
- });
518
- this._tracksVersion++;
519
- if (!skipAdapter) {
520
- this._updateTrackOnAdapter(trackId);
1900
+ const mark = this._adapterSync.markSkip(skipAdapter);
1901
+ try {
1902
+ return this._arrangement.moveClip(trackId, clipId, deltaSamples);
1903
+ } finally {
1904
+ this._adapterSync.unmarkIfUnchanged(mark);
521
1905
  }
522
- this._emitStateChange();
523
- return constrainedDelta;
524
1906
  }
525
1907
  splitClip(trackId, clipId, atSample) {
526
- const track = this._tracks.find((t) => t.id === trackId);
527
- if (!track) {
528
- console.warn(`[waveform-playlist/engine] splitClip: track "${trackId}" not found`);
529
- return;
530
- }
531
- const clipIndex = track.clips.findIndex((c) => c.id === clipId);
532
- if (clipIndex === -1) {
533
- console.warn(
534
- `[waveform-playlist/engine] splitClip: clip "${clipId}" not found in track "${trackId}"`
535
- );
536
- return;
537
- }
538
- const clip = track.clips[clipIndex];
539
- const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
540
- if (!canSplitAt(clip, atSample, minDuration)) {
541
- console.warn(
542
- `[waveform-playlist/engine] splitClip: cannot split clip "${clipId}" at sample ${atSample} (clip range: ${clip.startSample}\u2013${clip.startSample + clip.durationSamples}, minDuration: ${minDuration})`
543
- );
544
- return;
545
- }
546
- this._pushUndoSnapshot();
547
- const { left, right } = splitClip(clip, atSample);
548
- const enrichedLeft = clip.startTick !== void 0 ? { ...left, startTick: this._secondsToTicks(left.startSample / this._sampleRate) } : left;
549
- const enrichedRight = clip.startTick !== void 0 ? { ...right, startTick: this._secondsToTicks(right.startSample / this._sampleRate) } : right;
550
- this._tracks = this._tracks.map((t) => {
551
- if (t.id !== trackId) return t;
552
- const newClips = [...t.clips];
553
- newClips.splice(clipIndex, 1, enrichedLeft, enrichedRight);
554
- return { ...t, clips: newClips };
555
- });
556
- this._tracksVersion++;
557
- this._updateTrackOnAdapter(trackId);
558
- this._emitStateChange();
1908
+ this._arrangement.splitClip(trackId, clipId, atSample);
559
1909
  }
560
1910
  trimClip(trackId, clipId, boundary, deltaSamples, skipAdapter = false) {
561
- const track = this._tracks.find((t) => t.id === trackId);
562
- if (!track) {
563
- console.warn(`[waveform-playlist/engine] trimClip: track "${trackId}" not found`);
564
- return;
565
- }
566
- const clipIndex = track.clips.findIndex((c) => c.id === clipId);
567
- if (clipIndex === -1) {
568
- console.warn(
569
- `[waveform-playlist/engine] trimClip: clip "${clipId}" not found in track "${trackId}"`
570
- );
571
- return;
572
- }
573
- const clip = track.clips[clipIndex];
574
- const sortedClips = (0, import_core2.sortClipsByTime)(track.clips);
575
- const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
576
- const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
577
- const constrained = constrainBoundaryTrim(
578
- clip,
579
- deltaSamples,
580
- boundary,
581
- sortedClips,
582
- sortedIndex,
583
- minDuration
584
- );
585
- if (constrained === 0) return;
586
- this._pushUndoSnapshot();
587
- this._tracks = this._tracks.map((t) => {
588
- if (t.id !== trackId) return t;
589
- const newClips = t.clips.map((c, i) => {
590
- if (i !== clipIndex) return c;
591
- if (boundary === "left") {
592
- const newStartSample = c.startSample + constrained;
593
- return {
594
- ...c,
595
- startSample: newStartSample,
596
- startTick: c.startTick !== void 0 ? this._secondsToTicks(newStartSample / this._sampleRate) : void 0,
597
- offsetSamples: c.offsetSamples + constrained,
598
- durationSamples: c.durationSamples - constrained
599
- };
600
- } else {
601
- return { ...c, durationSamples: c.durationSamples + constrained };
602
- }
603
- });
604
- return { ...t, clips: newClips };
605
- });
606
- this._tracksVersion++;
607
- if (!skipAdapter) {
608
- this._updateTrackOnAdapter(trackId);
1911
+ const mark = this._adapterSync.markSkip(skipAdapter);
1912
+ try {
1913
+ this._arrangement.trimClip(trackId, clipId, boundary, deltaSamples);
1914
+ } finally {
1915
+ this._adapterSync.unmarkIfUnchanged(mark);
609
1916
  }
610
- this._emitStateChange();
611
1917
  }
612
1918
  // ---------------------------------------------------------------------------
613
1919
  // Playback (delegates to adapter, no-ops without adapter)
@@ -678,11 +1984,11 @@ var PlaylistEngine = class {
678
1984
  return;
679
1985
  }
680
1986
  if (bpm === this._bpm && atTick === void 0) return;
1987
+ if (this._disposed) return;
681
1988
  const accepted = this._adapter?.setTempo?.(bpm, atTick);
682
1989
  if (accepted === false) return;
683
1990
  this._bpm = bpm;
684
- this._recomputeStartSamples();
685
- this._emitStateChange();
1991
+ this._arrangement.recomputeStartSamples();
686
1992
  }
687
1993
  getCurrentTime() {
688
1994
  if (this._adapter) {
@@ -760,45 +2066,36 @@ var PlaylistEngine = class {
760
2066
  this._emitStateChange();
761
2067
  }
762
2068
  // ---------------------------------------------------------------------------
763
- // Per-Track Audio (forwards to adapter, persists into _tracks, emits)
2069
+ // Per-Track Audio (persists into the arrangement, forwards to adapter, emits)
764
2070
  // ---------------------------------------------------------------------------
765
2071
  //
766
- // Each setter forwards to the adapter, mirrors the change into the engine's
767
- // own _tracks (so a later adapter rebuild via setTracks keeps the value),
768
- // and bumps _mixerVersion + emits statechange. These are NOT structural
769
- // changes, so they deliberately do NOT bump _tracksVersion — that would make
2072
+ // Each setter writes the value into the arrangement's mixer part (so a later
2073
+ // adapter rebuild via setTracks keeps the value, and mixerVersion is bumped);
2074
+ // the engine's listener then calls the adapter and emits statechange. For a
2075
+ // track the arrangement does not hold nothing changes, and the adapter is
2076
+ // still called from here (a consumer may target a track that has not been
2077
+ // ingested yet). These are NOT structural
2078
+ // changes, so they deliberately do NOT bump tracksVersion — that would make
770
2079
  // tracksVersion-gated consumers re-run expensive structural work (audio-graph
771
2080
  // rewire, peak regeneration) on every volume/pan drag frame. Consumers that
772
2081
  // cache a track snapshot (e.g. @dawcore/components' <daw-editor>) watch
773
- // _mixerVersion to refresh that cache cheaply, so an unrelated setTracks
2082
+ // mixerVersion to refresh that cache cheaply, so an unrelated setTracks
774
2083
  // rebuild no longer reverts live mixer state (#501).
775
2084
  setTrackVolume(trackId, volume) {
776
- const track = this._tracks.find((t) => t.id === trackId);
777
- if (track) track.volume = volume;
778
- this._adapter?.setTrackVolume(trackId, volume);
779
- this._mixerVersion++;
780
- this._emitStateChange();
2085
+ const changed = this._mixerChanged(() => this._arrangement.setTrackVolume(trackId, volume));
2086
+ if (!changed && !this._disposed) this._adapter?.setTrackVolume(trackId, volume);
781
2087
  }
782
2088
  setTrackMute(trackId, muted) {
783
- const track = this._tracks.find((t) => t.id === trackId);
784
- if (track) track.muted = muted;
785
- this._adapter?.setTrackMute(trackId, muted);
786
- this._mixerVersion++;
787
- this._emitStateChange();
2089
+ const changed = this._mixerChanged(() => this._arrangement.setTrackMute(trackId, muted));
2090
+ if (!changed && !this._disposed) this._adapter?.setTrackMute(trackId, muted);
788
2091
  }
789
2092
  setTrackSolo(trackId, soloed) {
790
- const track = this._tracks.find((t) => t.id === trackId);
791
- if (track) track.soloed = soloed;
792
- this._adapter?.setTrackSolo(trackId, soloed);
793
- this._mixerVersion++;
794
- this._emitStateChange();
2093
+ const changed = this._mixerChanged(() => this._arrangement.setTrackSolo(trackId, soloed));
2094
+ if (!changed && !this._disposed) this._adapter?.setTrackSolo(trackId, soloed);
795
2095
  }
796
2096
  setTrackPan(trackId, pan) {
797
- const track = this._tracks.find((t) => t.id === trackId);
798
- if (track) track.pan = pan;
799
- this._adapter?.setTrackPan(trackId, pan);
800
- this._mixerVersion++;
801
- this._emitStateChange();
2097
+ const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan));
2098
+ if (!changed && !this._disposed) this._adapter?.setTrackPan(trackId, pan);
802
2099
  }
803
2100
  // ---------------------------------------------------------------------------
804
2101
  // Zoom
@@ -839,6 +2136,10 @@ var PlaylistEngine = class {
839
2136
  dispose() {
840
2137
  if (this._disposed) return;
841
2138
  this._disposed = true;
2139
+ this._stopFollowingArrangement();
2140
+ this._detachFromArrangement();
2141
+ this._detachDecodeContext?.();
2142
+ this._detachDecodeContext = null;
842
2143
  this._isPlaying = false;
843
2144
  this._adapter?.onPlaybackEnded?.(null);
844
2145
  try {
@@ -851,34 +2152,61 @@ var PlaylistEngine = class {
851
2152
  // ---------------------------------------------------------------------------
852
2153
  // Private helpers
853
2154
  // ---------------------------------------------------------------------------
854
- _snapshotTracks() {
855
- return this._tracks.map((t) => ({ ...t, clips: t.clips.map((c) => ({ ...c })) }));
2155
+ /** Runs a mixer setter on the arrangement. True when a value changed. */
2156
+ _mixerChanged(change) {
2157
+ const version = this._arrangement.mixerVersion;
2158
+ change();
2159
+ return this._arrangement.mixerVersion !== version;
856
2160
  }
857
- _pushUndoSnapshot() {
858
- if (this._inTransaction) {
859
- this._transactionMutated = true;
860
- return;
2161
+ /**
2162
+ * The arrangement changed: bring the adapter in step, then emit
2163
+ * `statechange`. Every change is one emission. An adapter that throws
2164
+ * stops the emission and fails the arrangement call that is delivering
2165
+ * (for a change made from inside a listener, that is the outer call).
2166
+ */
2167
+ _onArrangementChange(change, at) {
2168
+ switch (change.type) {
2169
+ case "mixer":
2170
+ this._adapterSync.sendMixerValues(change.trackId, change.values);
2171
+ break;
2172
+ case "reorder":
2173
+ // not audible: adapter nodes are keyed by track id
2174
+ case "history":
2175
+ break;
2176
+ default:
2177
+ if (change.type === "remove" || change.type === "restore" || change.type === "update") {
2178
+ this._clearSelectionIfGone();
2179
+ }
2180
+ if (change.type === "load") {
2181
+ this._followLoad(change, at);
2182
+ } else {
2183
+ this._adapterSync.follow(change, at);
2184
+ }
861
2185
  }
862
- this._undoStack.push(this._snapshotTracks());
863
- if (this._undoStack.length > this.undoLimit) {
864
- this._undoStack.shift();
2186
+ this._emitStateChange();
2187
+ }
2188
+ /**
2189
+ * Audio arrived by itself: there is no caller to fail when the adapter
2190
+ * throws. The error is reported, the `statechange` is still emitted (the
2191
+ * tracks did change), and the next track change sends the adapter every
2192
+ * track.
2193
+ */
2194
+ _followLoad(change, at) {
2195
+ try {
2196
+ this._adapterSync.follow(change, at);
2197
+ } catch (error) {
2198
+ console.error(
2199
+ "[waveform-playlist] The playout adapter failed while loaded audio was applied:",
2200
+ error
2201
+ );
865
2202
  }
866
- this._redoStack = [];
867
2203
  }
868
- _restoreTracks(snapshot) {
869
- const oldTracks = this._tracks;
870
- this._tracks = snapshot;
871
- this._tracksVersion++;
872
- if (this._adapter && oldTracks.length === snapshot.length) {
873
- for (let i = 0; i < snapshot.length; i++) {
874
- if (oldTracks[i] !== snapshot[i]) {
875
- this._updateTrackOnAdapter(snapshot[i].id);
876
- }
877
- }
878
- } else {
879
- this._adapter?.setTracks(this._tracks);
2204
+ /** The selected track id names a track; when that track is gone, nothing is selected. */
2205
+ _clearSelectionIfGone() {
2206
+ const selected = this._selectedTrackId;
2207
+ if (selected !== null && !this._arrangement.getTracks().some((t) => t.id === selected)) {
2208
+ this._selectedTrackId = null;
880
2209
  }
881
- this._emitStateChange();
882
2210
  }
883
2211
  _emit(event, ...args) {
884
2212
  const listeners = this._listeners.get(event);
@@ -917,29 +2245,20 @@ var PlaylistEngine = class {
917
2245
  }
918
2246
  return Math.round(seconds * this._ppqn * this._bpm / 60);
919
2247
  }
920
- _recomputeStartSamples() {
921
- this._tracks = this._tracks.map((track) => ({
922
- ...track,
923
- clips: track.clips.map((clip) => {
924
- if (clip.startTick === void 0) return clip;
925
- return {
926
- ...clip,
927
- startSample: Math.round(this._ticksToSeconds(clip.startTick) * this._sampleRate)
928
- };
929
- })
930
- }));
931
- this._tracksVersion++;
932
- for (const track of this._tracks) {
933
- this._updateTrackOnAdapter(track.id);
934
- }
935
- }
936
2248
  _emitStateChange() {
937
2249
  this._emit("statechange", this.getState());
938
2250
  }
939
2251
  };
2252
+ function asArrangementImpl(arrangement) {
2253
+ if (isArrangement(arrangement)) return arrangement;
2254
+ throw new Error(
2255
+ "[waveform-playlist] PlaylistEngine: the `arrangement` option must be an arrangement made by createArrangement()."
2256
+ );
2257
+ }
940
2258
  // Annotate the CommonJS export names for ESM import in node:
941
2259
  0 && (module.exports = {
942
2260
  PlaylistEngine,
2261
+ attachDecodeContext,
943
2262
  calculateDuration,
944
2263
  calculateSplitPoint,
945
2264
  calculateViewportBounds,
@@ -948,6 +2267,8 @@ var PlaylistEngine = class {
948
2267
  clampSeekPosition,
949
2268
  constrainBoundaryTrim,
950
2269
  constrainClipDrag,
2270
+ createArrangement,
2271
+ defaultLoadSource,
951
2272
  findClosestZoomIndex,
952
2273
  getVisibleChunkIndices,
953
2274
  shouldUpdateViewport,