@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/README.md CHANGED
@@ -1,6 +1,6 @@
1
1
  # @waveform-playlist/engine
2
2
 
3
- Framework-agnostic multitrack timeline engine for waveform-playlist — pure clip/track operations plus a stateful `PlaylistEngine` that manages tracks, selection, loop, zoom, and undo/redo, decoupled from any audio backend via a pluggable `PlayoutAdapter`.
3
+ Framework-agnostic multitrack timeline engine for waveform-playlist — pure clip/track operations, an arrangement that owns the tracks, the mix and the undo history, and a stateful `PlaylistEngine` that plays an arrangement and manages selection, loop and zoom, decoupled from any audio backend via a pluggable `PlayoutAdapter`.
4
4
 
5
5
  Used by `@waveform-playlist/browser` (the React provider) and `@dawcore/components` (the Lit web-components layer). Pair it with a `PlayoutAdapter` implementation such as `@waveform-playlist/playout` (Tone.js) or `@dawcore/transport` (native Web Audio) to actually produce sound — the engine itself never touches the audio graph directly.
6
6
 
@@ -8,7 +8,9 @@ Used by `@waveform-playlist/browser` (the React provider) and `@dawcore/componen
8
8
 
9
9
  - **Clip-based timeline model** — tracks hold multiple clips; move, trim, and split with automatic collision constraints
10
10
  - **Sample + tick timeline math** — integer samples for precision, ticks for tempo-independent positioning
11
- - **Undo/redo** — snapshot-based history for all structural mutations, with transaction grouping for drag gestures
11
+ - **The arrangement** — one object owns the tracks, the mix (volume, mute, solo and pan by track id) and the undo history; it needs no engine and outlives the engine that plays it
12
+ - **Loading audio** — a clip may name its audio (`src`: a URL, `Blob` or `File`) instead of carrying it; the arrangement fetches and decodes each source once, reports where each one is (`arrangement.sources`) and replaces the clip with a loaded one when the audio arrives
13
+ - **Undo/redo** — history for the structural changes (tracks and clips), with transaction grouping for drag gestures; an undo never changes the mix
12
14
  - **Selection, loop, and zoom state** — engine owns selection range, loop region, zoom level, and master volume
13
15
  - **`statechange` events** — subscribe once and mirror a single `EngineState` snapshot into any UI framework
14
16
  - **Adapter-pluggable playback** — bring your own `PlayoutAdapter` (Tone.js, native Web Audio, or a custom backend); the engine runs headless without one
@@ -19,21 +21,22 @@ Used by `@waveform-playlist/browser` (the React provider) and `@dawcore/componen
19
21
  npm install @waveform-playlist/engine @waveform-playlist/core
20
22
  ```
21
23
 
22
- `@waveform-playlist/core` is a required peer dependency (`>=7.0.0`) — it provides the `ClipTrack`/`AudioClip` types and clip-construction helpers used below.
24
+ `@waveform-playlist/core` is a required peer dependency (version 13 or later) — it provides the `ClipTrack`/`AudioClip` types and clip-construction helpers used below.
23
25
 
24
26
  ## Quick Start
25
27
 
26
28
  ```typescript
27
29
  import { PlaylistEngine } from '@waveform-playlist/engine';
28
30
  import { createClipFromSeconds, type ClipTrack } from '@waveform-playlist/core';
29
- import { TonePlayout } from '@waveform-playlist/playout'; // any PlayoutAdapter implementation
31
+ import { createToneAdapter } from '@waveform-playlist/playout'; // any PlayoutAdapter implementation
30
32
 
31
- const adapter = new TonePlayout();
33
+ const adapter = createToneAdapter();
32
34
  const engine = new PlaylistEngine({ adapter, sampleRate: 48000 });
33
35
  await engine.init();
34
36
 
35
37
  const track: ClipTrack = {
36
38
  id: 'track-1',
39
+ kind: 'audio', // or 'midi': a track holds one kind of clip, and setTracks throws otherwise
37
40
  name: 'Guitar',
38
41
  clips: [
39
42
  createClipFromSeconds({
@@ -41,13 +44,14 @@ const track: ClipTrack = {
41
44
  startTime: 0,
42
45
  }),
43
46
  ],
47
+ // The mix the track enters with. Afterwards change it with engine.setTrackVolume() etc.
44
48
  muted: false,
45
49
  soloed: false,
46
50
  volume: 1.0,
47
51
  pan: 0,
48
52
  };
49
53
 
50
- engine.setTracks([track]);
54
+ engine.setTracks([track]); // the engine keeps a copy; `track` stays yours
51
55
 
52
56
  // Subscribe once; mirror EngineState into your framework's state
53
57
  engine.on('statechange', (state) => {
@@ -69,21 +73,165 @@ engine.undo();
69
73
  engine.redo();
70
74
  ```
71
75
 
76
+ ## The arrangement
77
+
78
+ An arrangement is the owner of three things: the tracks with their clips, the mix (volume, mute, solo and pan by track id) and the undo history with its transactions. Everything else reads it and changes it by calling its methods. A `PlaylistEngine` plays an arrangement: it follows it by subscription, and for each change it makes the adapter call and emits `statechange`.
79
+
80
+ An engine built without an `arrangement` option makes one of its own, so `new PlaylistEngine({ adapter })` works as in the Quick Start. Make the arrangement yourself when it has to exist before the engine does, or outlive it:
81
+
82
+ ```typescript
83
+ import { createArrangement, PlaylistEngine } from '@waveform-playlist/engine';
84
+
85
+ const arrangement = createArrangement({ tracks: [track], undoLimit: 50 });
86
+
87
+ // No engine is needed to edit
88
+ arrangement.moveClip('track-1', track.clips[0].id, 48000);
89
+ arrangement.setTrackVolume('track-1', 0.5);
90
+
91
+ // Read: nothing returned is a copy
92
+ arrangement.getTracks(); // readonly ArrangementTrack[]; the same array until the tracks change
93
+ arrangement.getMixer().get('track-1'); // { volume: 0.5, muted: false, soloed: false, pan: 0 }
94
+ const unsubscribe = arrangement.subscribe(() => {
95
+ // once per change (tracks, mix or history), after the engine has made its adapter call for it
96
+ });
97
+
98
+ // Play it
99
+ const engine = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
100
+ await engine.init();
101
+
102
+ // The arrangement outlives the engine
103
+ engine.dispose();
104
+ const next = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
105
+ // next has the same tracks, the same mix and the same undo history
106
+ ```
107
+
108
+ A clip's `startTick` is counted in an engine's `ppqn`. When an engine attaches, every clip without a `startTick` gets one from its `startSample`, and when the engine has another `ppqn` than the one before (the Tone.js adapter at 192 after the native transport at 960, or the reverse) every stored tick is converted to the new unit, rounded to the nearest tick. Both happen in the current tracks, in every undo and redo state and in the base of an open transaction. `startSample` is not touched and it is not an undo step. When the current tracks changed, subscribers are told once (`tracksVersion` goes up by one); with the same `ppqn` and a tick on every clip, nothing happens. It is all or nothing: if the engine's tempo map throws while the ticks are worked out, the constructor throws, nothing in the arrangement has changed and it is not attached.
109
+
110
+ A `setTempo` places every clip that has a tick on the tick grid of the engine it is called on, swap or no swap. Going to a coarser `ppqn` rounds: 7 ticks at 960 become 1 at 192, and 5 when an engine at 960 takes over again. After such a swap the next tempo change can therefore place a clip up to half a tick of the coarser engine away from where it was: 0.5 × 60 × sampleRate / (ppqn × bpm) samples, about 62 samples (1.3 ms) at 192 ppqn, 120 bpm and 48 kHz.
111
+
112
+ A different tempo is not converted. A tick is the musical position, so an engine built at another tempo than the one the ticks were made under has clips whose `startSample` and `startTick` disagree until the next `setTempo`, which moves `startSample` to follow the tick. Clips added under the new engine get their ticks at its tempo and keep their place at that `setTempo`, while the older ones move.
113
+
114
+ An arrangement plays through one engine at a time: building a second engine on it while the first has not been disposed logs a warning. Two engines alive on one arrangement is unsupported, in particular with different `ppqn`: the second engine's time base replaces the first's, so ticks the first engine gives later are computed with the second engine's. The engine's own `undoLimit` option is ignored, with a warning, when an arrangement is passed; set it on `createArrangement({ undoLimit })`. The `arrangement` option accepts only an arrangement made by `createArrangement()`. The engine recognises one by a versioned `Symbol.for` key and not by `instanceof`, so an arrangement made by another installed copy of this package (an app and a library that pin different versions) is accepted as long as both copies use the same key version.
115
+
116
+ The engine's track, clip, mixer and history methods call the arrangement's, so a change made through either reaches the adapter and emits `statechange`. The arrangement's `removeTrack` also takes `{ undoable: false }` (no undo step, and the track is taken out of every undo and redo state, so no undo brings it back: for a dropped file that could not be decoded), and its `updateTrack` takes a function of the current track: `arrangement.updateTrack(id, (track) => ({ ...track, name: 'Bass' }))`.
117
+
118
+ ### Loading audio
119
+
120
+ A track of an arrangement is an `ArrangementTrack` (from `@waveform-playlist/core`): its clips are loaded clips (`AudioClip`) or clips whose audio is not loaded yet (`LoadingClip`: a `src` and times in seconds). `isLoadingClip(clip)` tells them apart; narrow with it before reading `startSample`, `durationSamples` or any other sample field of a clip from `arrangement.getTracks()`. `createArrangement({ tracks })`, `getTracks`, `setTracks`, `addTrack` and `updateTrack` of the arrangement use that type. The engine's own `setTracks`, `addTrack` and `updateTrack` still take `ClipTrack` (loaded clips only).
121
+
122
+ ```typescript
123
+ import { createArrangement, PlaylistEngine } from '@waveform-playlist/engine';
124
+ import { audioTrack, isLoadingClip } from '@waveform-playlist/core';
125
+
126
+ const arrangement = createArrangement({
127
+ tracks: [
128
+ audioTrack({ id: 'guitar', src: '/audio/guitar.opus' }), // one LoadingClip
129
+ audioTrack({ id: 'vocals', src: '/audio/vocals.opus', start: 4 }), // seconds
130
+ ],
131
+ });
132
+
133
+ // Nothing is fetched yet: the arrangement has no audio context to decode with.
134
+ arrangement.sources.getSnapshot(); // { sources: Map(2), pendingCount: 2, failedCount: 0, isLoading: true }
135
+
136
+ // An engine with an adapter attaches adapter.audioContext, and the loads start.
137
+ const engine = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
138
+ await engine.init();
139
+
140
+ arrangement.sources.subscribe(({ sources, isLoading, failedCount }) => {
141
+ for (const [src, state] of sources) {
142
+ if (state.status === 'failed') {
143
+ console.error(state.error); // an Error
144
+ arrangement.retry(src); // or leave it: nothing starts a failed source again by itself
145
+ }
146
+ }
147
+ });
148
+
149
+ arrangement.subscribe(() => {
150
+ for (const track of arrangement.getTracks()) {
151
+ for (const clip of track.clips) {
152
+ if (isLoadingClip(clip)) continue; // clip.start, clip.duration, clip.offset: seconds, all optional
153
+ clip.startSample; // an AudioClip
154
+ }
155
+ }
156
+ });
157
+ ```
158
+
159
+ What happens to a loading clip:
160
+
161
+ - **It is held like any clip.** It is copied on its way in, is the same object through every operation on its track, keeps its place among the track's clips and is part of the undo steps. It has no `startTick`.
162
+ - **It cannot be edited.** `moveClip`, `trimClip` and `splitClip` on it log a warning (`… is still loading and cannot be edited until its audio has loaded`) and change nothing; `getClipBounds` returns `null` and `constrainTrimDelta` returns 0. Loaded clips do not collide with it.
163
+ - **It is audio.** A loading clip on a `kind: 'midi'` track is refused: `createArrangement({ tracks })`, `setTracks`, `addTrack` and `updateTrack` throw the error for a track whose clips do not match its kind, and nothing changes.
164
+ - **An engine does not play or report it.** The tracks an adapter is sent and `engine.getState().tracks` are each track without its loading clips, and `getState().duration` counts loaded clips only. A change that leaves a track's loaded clips (the same objects in the same order) and its own fields as they were makes no adapter call for that track; the `statechange` is still emitted. `engine.updateTrack(id)` always sends.
165
+
166
+ Which sources are loaded: every source a loading clip names in the current tracks, in an undo or redo state or in the base of an open transaction. So an undo never fetches a source again, and a source is dropped (its load aborted, its audio let go) when no state names it any more; named again later, it is fetched again. A loaded clip that carries both `src` and `audioBuffer` counts too: its buffer is used for that source and nothing is fetched. A loaded clip with `src` and no `audioBuffer` is not fetched and is not in `sources`: it never gets audio from the arrangement.
167
+
168
+ When a source is loaded, every loading clip that names it becomes an `AudioClip`: seconds become integer samples at the sample rate of the decoded buffer, the clip keeps its `id`, `name`, `color`, `gain`, fades, `waveformData` and `src`, a `duration` that runs past the end of the audio is cut to it (one console warning), and it gets a `startTick` when an engine is attached. This happens in the current tracks and in every undo and redo state, it is not an undo step, and subscribers are told once (`tracksVersion` goes up by one) when the current tracks changed. A clip added later that names a source that is already loaded is a loaded clip by the time the call that added it returns. A clip that comes in carrying `src` and `audioBuffer` for a source other loading clips are waiting for loads those clips inside the same call, with the one notification of that call.
169
+
170
+ If the adapter throws while an engine applies audio that arrived, there is no caller to fail: the engine logs `[waveform-playlist] The playout adapter failed while loaded audio was applied:` with the error, still emits the `statechange`, and sends the adapter every track at the next track change.
171
+
172
+ `arrangement.sources` is a `ValueSource` (`getSnapshot()` and `subscribe(listener)`, the shape `useSyncExternalStore` takes). Its value is `{ sources, pendingCount, failedCount, isLoading }`, where `sources` is a `ReadonlyMap` from each source to `{ status: 'pending' | 'loaded' | 'failed', error? }`. It is the same object until a source is added or dropped or a status changes, and it is published after the subscribers of `arrangement.subscribe` have been told, so a listener of `sources` that sees `loaded` finds the loaded clip in `getTracks()`. The other way round, a listener of `arrangement.subscribe` that finds the loaded clip still reads its source as `pending` in `sources`. The order of the entries of `sources` means nothing.
173
+
174
+ A source is `failed` in two cases:
175
+
176
+ - **Its load failed** (the fetch, the decode, or getting the audio context). No track changes. `arrangement.retry(src)` starts it again; nothing else does.
177
+ - **A clip in the current tracks could not be made from its audio**: an `offset` at or past the end of the audio, or a `start`, `offset` or `duration` that is not a usable number. That clip stays a loading clip, the error's message is `clip "<id>": <reason>`, and other clips of the same source are still loaded. `retry` does nothing here. Only a clip in the current tracks counts: replacing or removing the clip clears the failure at once, also while an undo step still holds it, and an undo that brings the clip back brings the failure back.
178
+
179
+ `createArrangement({ loadSource })` replaces how a source becomes an `AudioBuffer`. The default is the exported `defaultLoadSource`: `fetch` for a string, `arrayBuffer()` for a `Blob` or `File`, then `audioContext.decodeAudioData`, with the abort signal checked after each step.
180
+
181
+ ```typescript
182
+ import { createArrangement, defaultLoadSource, type LoadSource } from '@waveform-playlist/engine';
183
+
184
+ const loadSource: LoadSource = async (src, { signal, audioContext }) => {
185
+ if (typeof src !== 'string') return defaultLoadSource(src, { signal, audioContext });
186
+ const response = await fetch(src, { signal, credentials: 'include' });
187
+ if (!response.ok) throw new Error(`Failed to fetch audio: ${response.status}`);
188
+ return audioContext.decodeAudioData(await response.arrayBuffer());
189
+ };
190
+
191
+ const arrangement = createArrangement({ loadSource });
192
+ ```
193
+
194
+ The messages of `defaultLoadSource`'s own errors (`Failed to fetch <source>: <status> <statusText>`, `Failed to fetch <source>` when `fetch` threw a `TypeError`, `Decoded audio is empty: <source>`) name a URL without its query string, its fragment and a user name or password before the host (a URL the browser's parser finds credentials in is named in its parsed, absolute form; a malformed one the parser refuses loses only its query string and fragment), never echo a `data:` or `blob:` URL, and call a `File` by its name and any other `Blob` "Blob". The browser's `TypeError` is kept in `cause` only when the name in the message is the source unchanged. When anything was left out of the name (a user name or password, a query string, a fragment, a `data:` or `blob:` URL) the error has no `cause`, because the browser's own message can quote the whole URL. An `Error` the browser's decoder rejects with is passed on as it is, so its message is the browser's and does not name the source.
195
+
196
+ Nothing is fetched until the arrangement has an audio context to decode with; until then its sources are `pending`. A `PlaylistEngine` built with an adapter attaches `adapter.audioContext` in its constructor and detaches it in `dispose()`. Without an engine, or with `new PlaylistEngine({ adapter, arrangement, attachDecodeContext: false })`, attach one yourself:
197
+
198
+ ```typescript
199
+ import { attachDecodeContext } from '@waveform-playlist/engine';
200
+
201
+ const detach = attachDecodeContext(arrangement, async () => audioContext); // called for each load
202
+ // later
203
+ detach(); // loads in flight are aborted and stay pending; what is loaded stays; the next attach starts them again
204
+ ```
205
+
206
+ One context at a time: attaching a second while one is attached logs a warning and replaces the first. An engine without an adapter attaches nothing.
207
+
208
+ ### Rules
209
+
210
+ Rules that hold for the engine and the arrangement alike:
211
+
212
+ - **Nothing handed out is a copy.** `arrangement.getTracks()`, `engine.getState().tracks` and the tracks an adapter receives are shared with the undo history. Never write to the array, a track or a clip: copy first (`{ ...track, clips: [...] }`) and pass the copy to `updateTrack`. `arrangement.updateTrack`, given a track object or a function, keeps each clip object the track already holds and copies every other clip, so the clips you did not replace are the same objects afterwards. Outside production builds (`process.env.NODE_ENV` is not `'production'`; a page that loads the module with no bundler, and so has no `process`, counts as production) the tracks array, each track, its `clips` array and each clip are frozen, so a write throws in strict code (every module is strict). What a clip refers to (its `AudioBuffer`, peaks, fades, notes) is not frozen. Tracks are copied on their way in, so the objects you pass stay yours.
213
+ - **A change replaces only what changed.** The tracks array and the changed track and clip objects are new; every other track is the same object as before, so a comparison by identity finds what changed. The exception is `setTracks`, which copies every track it is given: after it no track is the object it was.
214
+ - **The mix is separate from the tracks.** A track's own `volume`, `muted`, `soloed` and `pan` fields are the values it enters with. They seed its mixer entry when its id has none. `setTracks` keeps the mix of an id that is in the tracks it replaces, `updateTrack` keeps the track's mix (also when it gives the track a new id, and then also over an entry the new id still has from a removed track), and `addTrack` of a track whose removal can still be undone finds the mix it had; in those cases the fields are not read. An entry is dropped as soon as no state holds its track any more: not the current tracks, not an undo or redo step, not the base of an open transaction (with `undoLimit: 0` a removed track's entry goes at once). Change the mix with `setTrackVolume`, `setTrackMute`, `setTrackSolo` and `setTrackPan`, which act on a track that is in the current tracks. `engine.getState().tracks` and the tracks an adapter receives carry the current mix in those fields; `arrangement.getTracks()` does not (read `getMixer()`).
215
+ - **Undo, redo and an aborted transaction restore tracks and clips, never the mix.** Undoing a `removeTrack` brings the track back with the mix it had. One exception: undoing or redoing an `updateTrack` that gave a track a new id switches between the old id's mix and the new id's, so a fader moved after the rename is not what the old id has after the undo. A second one: when a track is given the id of a removed track whose removal can still be undone, the renamed track's mix replaces the removed track's, so undoing back past the removal brings that track back with the renamed track's mix.
216
+ - **Ids are unique.** `setTracks`, `addTrack` and `updateTrack` throw an `Error` for a duplicate track id, for two clips with one id on the same track, and for a track whose clips do not match its `kind` (a loading clip is an audio clip), before anything changes.
217
+ - **Without an engine** clips are given no `startTick`, and a clip that came with one loses it when it is moved, trimmed on the left or split. Every clip without a tick, in the current tracks and in every undo and redo state, gets one from its `startSample` when an engine attaches. The shortest a clip may be is 0.1 s at the clip's own sample rate.
218
+
72
219
  ## API
73
220
 
74
221
  ### PlaylistEngine
75
222
 
76
- Key methods (see `src/types.ts` for the full `EngineState` shape):
223
+ Key methods (see `src/types.ts` for the full `EngineState` shape). `PlaylistEngineOptions` takes `adapter`, `arrangement`, `sampleRate`, `samplesPerPixel`, `zoomLevels`, `undoLimit`, `attachDecodeContext`, `bpm` and `ppqn`, all optional:
77
224
 
78
225
  ```typescript
79
226
  class PlaylistEngine {
80
227
  constructor(options?: PlaylistEngineOptions);
81
228
 
82
229
  // Tracks
83
- setTracks(tracks: ClipTrack[]): void;
230
+ setTracks(tracks: readonly ClipTrack[]): void; // replaces every track, clears the undo history
84
231
  addTrack(track: ClipTrack): void;
85
232
  removeTrack(trackId: string): void;
86
- updateTrack(trackId: string, track?: ClipTrack): void;
233
+ updateTrack(trackId: string, track?: ClipTrack): void; // with a track: replace it; without: send the current one to the adapter again
234
+ reorderTrack(trackId: string, toIndex: number): void;
87
235
  selectTrack(trackId: string | null): void;
88
236
 
89
237
  // Clip editing (undoable)
@@ -91,6 +239,7 @@ class PlaylistEngine {
91
239
  trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number, skipAdapter?: boolean): void;
92
240
  splitClip(trackId: string, clipId: string, atSample: number): void;
93
241
  constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
242
+ getClipBounds(trackId: string, clipId: string): ClipBounds | null;
94
243
 
95
244
  // Playback (no-ops without an adapter)
96
245
  init(): Promise<void>;
@@ -115,9 +264,9 @@ class PlaylistEngine {
115
264
  setZoomLevel(samplesPerPixel: number): void;
116
265
  setTempo(bpm: number, atTick?: number): void;
117
266
 
118
- // Undo/redo
119
- undo(): void;
120
- redo(): void;
267
+ // Undo/redo (tracks and clips; never the mix)
268
+ undo(): void; // with a transaction open: aborts it first
269
+ redo(): void; // with a transaction open: aborts it first
121
270
  clearHistory(): void;
122
271
  beginTransaction(): void;
123
272
  commitTransaction(): void;
@@ -134,6 +283,90 @@ class PlaylistEngine {
134
283
  }
135
284
  ```
136
285
 
286
+ ### Arrangement
287
+
288
+ ```typescript
289
+ function createArrangement(options?: CreateArrangementOptions): Arrangement;
290
+
291
+ interface CreateArrangementOptions {
292
+ tracks?: readonly ArrangementTrack[]; // the first tracks; not an undo step
293
+ undoLimit?: number; // default 100
294
+ loadSource?: LoadSource; // default: defaultLoadSource
295
+ }
296
+
297
+ interface Arrangement {
298
+ // read
299
+ getTracks(): readonly ArrangementTrack[];
300
+ getMixer(): ReadonlyMap<string, TrackMixerValues>;
301
+ subscribe(listener: () => void): () => void;
302
+ readonly tracksVersion: number;
303
+ readonly mixerVersion: number;
304
+
305
+ // tracks
306
+ setTracks(tracks: readonly ArrangementTrack[]): void;
307
+ addTrack(track: ArrangementTrack): void;
308
+ removeTrack(trackId: string, options?: RemoveTrackOptions): void;
309
+ updateTrack(
310
+ trackId: string,
311
+ next: ArrangementTrack | ((track: ArrangementTrack) => ArrangementTrack)
312
+ ): void;
313
+ reorderTrack(trackId: string, toIndex: number): void;
314
+
315
+ // clips (a clip that is still loading cannot be edited)
316
+ moveClip(trackId: string, clipId: string, deltaSamples: number): number;
317
+ trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;
318
+ splitClip(trackId: string, clipId: string, atSample: number): void;
319
+ getClipBounds(trackId: string, clipId: string): ClipBounds | null;
320
+ constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
321
+
322
+ // mixer
323
+ setTrackVolume(trackId: string, volume: number): void;
324
+ setTrackMute(trackId: string, muted: boolean): void;
325
+ setTrackSolo(trackId: string, soloed: boolean): void;
326
+ setTrackPan(trackId: string, pan: number): void;
327
+
328
+ // history
329
+ readonly canUndo: boolean;
330
+ readonly canRedo: boolean;
331
+ undo(): void;
332
+ redo(): void;
333
+ clearHistory(): void;
334
+ beginTransaction(): void;
335
+ commitTransaction(): void;
336
+ abortTransaction(): void;
337
+
338
+ // loading
339
+ readonly sources: ValueSource<ArrangementSourcesValue>;
340
+ retry(src: ClipSource): void; // start a source whose load failed again
341
+ }
342
+
343
+ interface ArrangementSourceState {
344
+ status: 'pending' | 'loaded' | 'failed';
345
+ error?: Error; // when failed
346
+ }
347
+
348
+ interface ArrangementSourcesValue {
349
+ sources: ReadonlyMap<ClipSource, ArrangementSourceState>;
350
+ pendingCount: number;
351
+ failedCount: number;
352
+ isLoading: boolean; // true while a source is pending
353
+ }
354
+
355
+ type LoadSource = (
356
+ src: ClipSource,
357
+ context: { signal: AbortSignal; audioContext: BaseAudioContext }
358
+ ) => Promise<AudioBuffer>;
359
+
360
+ const defaultLoadSource: LoadSource;
361
+
362
+ function attachDecodeContext(
363
+ arrangement: Arrangement,
364
+ getContext: () => Promise<BaseAudioContext>
365
+ ): () => void; // returns the function that detaches
366
+ ```
367
+
368
+ `ArrangementTrack`, `LoadingClip`, `ClipSource` (`string | Blob`), `ValueSource` and `isLoadingClip` come from `@waveform-playlist/core`.
369
+
137
370
  ### PlayoutAdapter
138
371
 
139
372
  The interface an audio backend implements to plug into the engine:
@@ -145,7 +378,7 @@ interface PlayoutAdapter {
145
378
  setPpqn?(ppqn: number): void;
146
379
 
147
380
  init(): Promise<void>;
148
- setTracks(tracks: ClipTrack[]): void;
381
+ setTracks(tracks: readonly ClipTrack[]): void; // the engine's own objects: read them, never write to them. Loaded clips only
149
382
  addTrack?(track: ClipTrack): void;
150
383
  removeTrack?(trackId: string): void;
151
384
  updateTrack?(trackId: string, track: ClipTrack): void;