@waveform-playlist/engine 14.0.0-next.0 → 14.0.0-next.10

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, 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`.
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 `EditorEngine` 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
 
@@ -10,7 +10,7 @@ Used by `@waveform-playlist/browser` (the React provider) and `@dawcore/componen
10
10
  - **Sample + tick timeline math** — integer samples for precision, ticks for tempo-independent positioning
11
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
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
13
+ - **Undo/redo** — one history for the tracks, the clips and the mix: a fader move is an undo step, a whole drag is one step (`createMixerGesture()` from `@waveform-playlist/core`), and transactions group a clip drag
14
14
  - **Selection, loop, and zoom state** — engine owns selection range, loop region, zoom level, and master volume
15
15
  - **`statechange` events** — subscribe once and mirror a single `EngineState` snapshot into any UI framework
16
16
  - **Adapter-pluggable playback** — bring your own `PlayoutAdapter` (Tone.js, native Web Audio, or a custom backend); the engine runs headless without one
@@ -26,12 +26,12 @@ npm install @waveform-playlist/engine @waveform-playlist/core
26
26
  ## Quick Start
27
27
 
28
28
  ```typescript
29
- import { PlaylistEngine } from '@waveform-playlist/engine';
29
+ import { EditorEngine } from '@waveform-playlist/engine';
30
30
  import { createClipFromSeconds, type ClipTrack } from '@waveform-playlist/core';
31
31
  import { createToneAdapter } from '@waveform-playlist/playout'; // any PlayoutAdapter implementation
32
32
 
33
33
  const adapter = createToneAdapter();
34
- const engine = new PlaylistEngine({ adapter, sampleRate: 48000 });
34
+ const engine = new EditorEngine({ adapter, sampleRate: 48000 });
35
35
  await engine.init();
36
36
 
37
37
  const track: ClipTrack = {
@@ -75,12 +75,12 @@ engine.redo();
75
75
 
76
76
  ## The arrangement
77
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`.
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. An `EditorEngine` plays an arrangement: it follows it by subscription, and for each change it makes the adapter call and emits `statechange`.
79
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:
80
+ An engine built without an `arrangement` option makes one of its own, so `new EditorEngine({ adapter })` works as in the Quick Start. Make the arrangement yourself when it has to exist before the engine does, or outlive it:
81
81
 
82
82
  ```typescript
83
- import { createArrangement, PlaylistEngine } from '@waveform-playlist/engine';
83
+ import { createArrangement, EditorEngine } from '@waveform-playlist/engine';
84
84
 
85
85
  const arrangement = createArrangement({ tracks: [track], undoLimit: 50 });
86
86
 
@@ -96,12 +96,12 @@ const unsubscribe = arrangement.subscribe(() => {
96
96
  });
97
97
 
98
98
  // Play it
99
- const engine = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
99
+ const engine = new EditorEngine({ adapter: createToneAdapter(), arrangement });
100
100
  await engine.init();
101
101
 
102
102
  // The arrangement outlives the engine
103
103
  engine.dispose();
104
- const next = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
104
+ const next = new EditorEngine({ adapter: createToneAdapter(), arrangement });
105
105
  // next has the same tracks, the same mix and the same undo history
106
106
  ```
107
107
 
@@ -111,16 +111,43 @@ A `setTempo` places every clip that has a tick on the tick grid of the engine it
111
111
 
112
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
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.
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. The key version changed with the mixer undo steps (`/v2`) and again with `addTrack`'s `index` (`/v3`): an engine and an arrangement from copies on either side of such a change refuse each other.
115
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' }))`.
116
+ The engine's track, clip, mixer, recording 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), `removeClip(trackId, clipId, options?)` removes a clip (an undo step; `{ undoable: false }` takes it out of every state in the same way), and its `updateTrack` takes a function of the current track: `arrangement.updateTrack(id, (track) => ({ ...track, name: 'Bass' }))`.
117
+
118
+ ### Mixer moves are undo steps
119
+
120
+ `setTrackVolume`, `setTrackMute`, `setTrackSolo`, `setTrackPan` and `setTrackPanLaw` (on the arrangement and on the engine) are undo steps: an undo puts the fader back. Their last argument, `options?: MixerChangeOptions`, says how a change goes into the history:
121
+
122
+ - nothing: each call is a step of its own;
123
+ - `{ gesture: id }`: calls with the same id, one after another, are one step (a fader drag from press to release);
124
+ - `{ undoable: false }`: no step. The value is written into every saved state as well, so no undo or redo brings back an older one (automation, a value that is not the user's edit). It wins over `gesture`.
125
+
126
+ A call that changes nothing (the value the track already has, or a track that is not in the current tracks) makes no step and no `statechange`. Inside an open transaction an undoable mixer change is part of it, and an abort takes it back; an `{ undoable: false }` change is written into the transaction's base too, so an abort keeps it. Undo, redo and an abort bring back the mix of the state they return to.
127
+
128
+ `createMixerGesture()` from `@waveform-playlist/core` makes the ids for one control. Use one per slider:
129
+
130
+ ```typescript
131
+ import { createMixerGesture } from '@waveform-playlist/core';
132
+
133
+ const gesture = createMixerGesture();
134
+ const detach = gesture.attach(slider); // ends the gesture on the slider's own events
135
+ slider.addEventListener('input', () => {
136
+ engine.setTrackVolume('track-1', slider.valueAsNumber, { gesture: gesture.id });
137
+ });
138
+ // gesture.end() ends it by hand; detach() removes the listeners
139
+ ```
140
+
141
+ `attach` ends the gesture on the input's `change` (the end of a pointer drag), except while an arrow, Page Up/Down, Home or End key is held: then on that key's `keyup`, so a held key is one step. A `blur` ends it too. Mute and solo buttons need no helper: each click is a step.
142
+
143
+ **The take's mute.** `setTrackRecording(trackId, recording)` (arrangement and engine) marks the track a take is recording onto, and `arrangement.recordingTrackIds` is the set of those ids (`engine.recordingTrackIds` reads the same set, for example to disable that track's mute control). Such a track plays muted for the length of the take: `engine.getState().tracks` and the adapter have it muted, while its mute in `getMixer()` stays as it is and comes back when the take ends. It is not an undo step, and undo, redo, an abort, `setTracks` and `clearHistory` do not change which tracks are recording. It is not a record-arm: it lasts only while a take is recorded.
117
144
 
118
145
  ### Loading audio
119
146
 
120
147
  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
148
 
122
149
  ```typescript
123
- import { createArrangement, PlaylistEngine } from '@waveform-playlist/engine';
150
+ import { createArrangement, EditorEngine } from '@waveform-playlist/engine';
124
151
  import { audioTrack, isLoadingClip } from '@waveform-playlist/core';
125
152
 
126
153
  const arrangement = createArrangement({
@@ -134,7 +161,7 @@ const arrangement = createArrangement({
134
161
  arrangement.sources.getSnapshot(); // { sources: Map(2), pendingCount: 2, failedCount: 0, isLoading: true }
135
162
 
136
163
  // An engine with an adapter attaches adapter.audioContext, and the loads start.
137
- const engine = new PlaylistEngine({ adapter: createToneAdapter(), arrangement });
164
+ const engine = new EditorEngine({ adapter: createToneAdapter(), arrangement });
138
165
  await engine.init();
139
166
 
140
167
  arrangement.sources.subscribe(({ sources, isLoading, failedCount }) => {
@@ -159,9 +186,9 @@ arrangement.subscribe(() => {
159
186
  What happens to a loading clip:
160
187
 
161
188
  - **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.
189
+ - **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. A move or a trim of a loaded clip stops at its span: at its start or its end when its length is known (a `duration`, or `waveformData`); when it is not, the clip holds its start (one sample), which nothing may cover.
163
190
  - **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.
191
+ - **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 other than the view fields (`TRACK_VIEW_FIELDS`) as they were makes no adapter call for that track; the `statechange` is still emitted. `engine.updateTrack(id)` always sends.
165
192
 
166
193
  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
194
 
@@ -174,7 +201,9 @@ If the adapter throws while an engine applies audio that arrived, there is no ca
174
201
  A source is `failed` in two cases:
175
202
 
176
203
  - **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.
204
+ - **A clip in the current tracks could not be made from its audio**: 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.
205
+
206
+ A clip whose `offset` is at or past the end of its audio has nothing of it left: it is removed from every state when the audio arrives, with a console warning, and is not an undo step. Its source is not failed: it stays `loaded` while another clip names it, and leaves `sources` otherwise.
178
207
 
179
208
  `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
209
 
@@ -193,7 +222,7 @@ const arrangement = createArrangement({ loadSource });
193
222
 
194
223
  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
224
 
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:
225
+ Nothing is fetched until the arrangement has an audio context to decode with; until then its sources are `pending`. An `EditorEngine` built with an adapter attaches `adapter.audioContext` in its constructor and detaches it in `dispose()`. Without an engine, or with `new EditorEngine({ adapter, arrangement, attachDecodeContext: false })`, attach one yourself:
197
226
 
198
227
  ```typescript
199
228
  import { attachDecodeContext } from '@waveform-playlist/engine';
@@ -209,26 +238,27 @@ One context at a time: attaching a second while one is attached logs a warning a
209
238
 
210
239
  Rules that hold for the engine and the arrangement alike:
211
240
 
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.
241
+ - **Nothing handed out is a copy.** `arrangement.getTracks()` and `engine.getState().tracks` are shared with the undo history. The tracks an adapter receives are copies without the view fields (core's `TRACK_VIEW_FIELDS`, typed `PlayoutTrack`) that share these clips, frozen the same way. 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
242
  - **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.
243
+ - **The mix is separate from the tracks.** A track's own `volume`, `muted`, `soloed`, `pan` and `panLaw` 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, and `updateTrack` keeps the track's mix (also when it gives the track a new id); in those cases the fields are not read. `addTrack` seeds the entry from the new track's fields, also for the id of a track removed earlier. `getMixer()` holds the entries of the current tracks; each undo and redo state keeps its own. Change the mix with `setTrackVolume`, `setTrackMute`, `setTrackSolo`, `setTrackPan` and `setTrackPanLaw`, 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()`).
244
+ - **The pan law is a mixer value that the first audio decides.** `getMixer().get(id).panLaw` is `'auto'`, `'mono'` or `'stereo'`. A track enters with its own `panLaw` field when that is `'mono'` or `'stereo'`, else with the law of the decoded audio it holds (`'stereo'` if a clip's buffer has two or more channels), else with `'auto'`. A track that is `'auto'` gets the law of the first decoded audio it holds, in the same change that brings the audio: the same undo step for a clip added decoded, no step for a clip that finishes loading (every state the arrangement can return to gets the law of its own tracks; an undo or redo step that this makes equal to the state next to it is dropped, so a finished load can turn `canUndo` or `canRedo` false). From then on the clips do not change it: not a clip of the other kind, not the removal of every clip, not `setTracks` with the same id. The law belongs to the id, like the rest of the mix: an app that reuses a track id for other material gets the law the id had (use a new id, pass through `setTracks([])`, which drops every entry, or set the law). `setTrackPanLaw(id, 'mono' | 'stereo')` changes it and may be called before the track has audio; any other value, `'auto'` included, throws a `TypeError`. A MIDI track stays `'auto'` (it plays with the mono law), and the setter does nothing for it. The law converts no audio: a stereo clip on a `'mono'` track stays stereo. `engine.getState().tracks` and the tracks an adapter receives carry the law in `panLaw` (a track that carries no field and is `'auto'` is sent without one). A change of the law alone is one call of the adapter's optional `setTrackPanLaw`, also when an undo returns a track without audio to `'auto'`; an adapter without the method is sent the track again. Unlike the other four engine setters, `engine.setTrackPanLaw` makes no adapter call when the arrangement changed nothing (a track it does not hold, the law the track already has).
245
+ - **Undo, redo and an aborted transaction restore the tracks, the clips and the mix** of the state they return to. Undoing a `removeTrack` brings the track back with the mix it had, and undoing an `updateTrack` that gave a track a new id brings back the old id with the mix it had then.
246
+ - **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, for a track whose clips do not match its `kind` (a loading clip is an audio clip), and for a track whose clips overlap (clips that touch are accepted; `findClipOverlap(clips)` names the first two that overlap), before anything changes.
217
247
  - **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
248
 
219
249
  ## API
220
250
 
221
- ### PlaylistEngine
251
+ ### EditorEngine
222
252
 
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:
253
+ Key methods (see `src/types.ts` for the full `EngineState` shape). `EditorEngineOptions` takes `adapter`, `arrangement`, `sampleRate`, `samplesPerPixel`, `zoomLevels`, `undoLimit`, `attachDecodeContext`, `bpm` and `ppqn`, all optional:
224
254
 
225
255
  ```typescript
226
- class PlaylistEngine {
227
- constructor(options?: PlaylistEngineOptions);
256
+ class EditorEngine {
257
+ constructor(options?: EditorEngineOptions);
228
258
 
229
259
  // Tracks
230
260
  setTracks(tracks: readonly ClipTrack[]): void; // replaces every track, clears the undo history
231
- addTrack(track: ClipTrack): void;
261
+ addTrack(track: ClipTrack, options?: AddTrackOptions): void; // { index }: where it enters (default: the end)
232
262
  removeTrack(trackId: string): void;
233
263
  updateTrack(trackId: string, track?: ClipTrack): void; // with a track: replace it; without: send the current one to the adapter again
234
264
  reorderTrack(trackId: string, toIndex: number): void;
@@ -255,16 +285,19 @@ class PlaylistEngine {
255
285
  setLoopRegion(start: number, end: number): void;
256
286
  setLoopEnabled(enabled: boolean): void;
257
287
  setMasterVolume(volume: number): void;
258
- setTrackVolume(trackId: string, volume: number): void;
259
- setTrackMute(trackId: string, muted: boolean): void;
260
- setTrackSolo(trackId: string, soloed: boolean): void;
261
- setTrackPan(trackId: string, pan: number): void;
288
+ setTrackVolume(trackId: string, volume: number, options?: MixerChangeOptions): void; // an undo step
289
+ setTrackMute(trackId: string, muted: boolean, options?: MixerChangeOptions): void;
290
+ setTrackSolo(trackId: string, soloed: boolean, options?: MixerChangeOptions): void;
291
+ setTrackPan(trackId: string, pan: number, options?: MixerChangeOptions): void;
292
+ setTrackPanLaw(trackId: string, panLaw: 'mono' | 'stereo', options?: MixerChangeOptions): void;
293
+ setTrackRecording(trackId: string, recording: boolean): void; // plays muted during the take; not an undo step
294
+ readonly recordingTrackIds: ReadonlySet<string>; // the arrangement's set (the same object), read-only
262
295
  zoomIn(): void;
263
296
  zoomOut(): void;
264
297
  setZoomLevel(samplesPerPixel: number): void;
265
298
  setTempo(bpm: number, atTick?: number): void;
266
299
 
267
- // Undo/redo (tracks and clips; never the mix)
300
+ // Undo/redo (tracks, clips and the mix)
268
301
  undo(): void; // with a transaction open: aborts it first
269
302
  redo(): void; // with a transaction open: aborts it first
270
303
  clearHistory(): void;
@@ -279,7 +312,7 @@ class PlaylistEngine {
279
312
  on<K extends keyof EngineEvents>(event: K, listener: EngineEvents[K]): void;
280
313
  off<K extends keyof EngineEvents>(event: K, listener: EngineEvents[K]): void; // 'statechange' | 'play' | 'pause' | 'stop'
281
314
 
282
- dispose(): void;
315
+ dispose(options?: { keepAdapter?: boolean }): void; // keepAdapter: stop, leave the adapter undisposed
283
316
  }
284
317
  ```
285
318
 
@@ -298,14 +331,23 @@ interface Arrangement {
298
331
  // read
299
332
  getTracks(): readonly ArrangementTrack[];
300
333
  getMixer(): ReadonlyMap<string, TrackMixerValues>;
301
- subscribe(listener: () => void): () => void;
334
+ // Called with the kind of change: 'set' | 'add' | 'remove' | 'update' | 'reorder' | 'restore' |
335
+ // 'restoreMix' | 'load' | 'mixer' | 'recording' | 'recompute' | 'history'; and removedClips, the
336
+ // { trackId, clipId } of clips the change took out because nothing of their audio was left (#859)
337
+ subscribe(
338
+ listener: (change: {
339
+ readonly type: ArrangementChangeType;
340
+ readonly removedClips?: readonly { readonly trackId: string; readonly clipId: string }[];
341
+ }) => void
342
+ ): () => void;
302
343
  readonly tracksVersion: number;
303
344
  readonly mixerVersion: number;
304
345
 
305
346
  // tracks
306
347
  setTracks(tracks: readonly ArrangementTrack[]): void;
307
- addTrack(track: ArrangementTrack): void;
348
+ addTrack(track: ArrangementTrack, options?: AddTrackOptions): void; // { index }: where it enters (default: the end)
308
349
  removeTrack(trackId: string, options?: RemoveTrackOptions): void;
350
+ removeClip(trackId: string, clipId: string, options?: RemoveClipOptions): void; // an undo step; undoable: false takes it out of every state
309
351
  updateTrack(
310
352
  trackId: string,
311
353
  next: ArrangementTrack | ((track: ArrangementTrack) => ArrangementTrack)
@@ -315,15 +357,20 @@ interface Arrangement {
315
357
  // clips (a clip that is still loading cannot be edited)
316
358
  moveClip(trackId: string, clipId: string, deltaSamples: number): number;
317
359
  trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;
318
- splitClip(trackId: string, clipId: string, atSample: number): void;
360
+ splitClip(trackId: string, clipId: string, atSample: number): void; // the left half keeps clipId
319
361
  getClipBounds(trackId: string, clipId: string): ClipBounds | null;
320
362
  constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
321
363
 
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;
364
+ // mixer (each call is an undo step; see MixerChangeOptions)
365
+ setTrackVolume(trackId: string, volume: number, options?: MixerChangeOptions): void;
366
+ setTrackMute(trackId: string, muted: boolean, options?: MixerChangeOptions): void;
367
+ setTrackSolo(trackId: string, soloed: boolean, options?: MixerChangeOptions): void;
368
+ setTrackPan(trackId: string, pan: number, options?: MixerChangeOptions): void;
369
+ setTrackPanLaw(trackId: string, panLaw: 'mono' | 'stereo', options?: MixerChangeOptions): void;
370
+
371
+ // the take's mute: the tracks a take is recording onto (outside the history)
372
+ readonly recordingTrackIds: ReadonlySet<string>;
373
+ setTrackRecording(trackId: string, recording: boolean): void;
327
374
 
328
375
  // history
329
376
  readonly canUndo: boolean;
@@ -340,6 +387,13 @@ interface Arrangement {
340
387
  retry(src: ClipSource): void; // start a source whose load failed again
341
388
  }
342
389
 
390
+ interface MixerChangeOptions {
391
+ /** Changes with the same id, one after another, are one undo step. */
392
+ gesture?: string;
393
+ /** Not an undo step: the value is written into every saved state as well. */
394
+ undoable?: false;
395
+ }
396
+
343
397
  interface ArrangementSourceState {
344
398
  status: 'pending' | 'loaded' | 'failed';
345
399
  error?: Error; // when failed
@@ -378,10 +432,13 @@ interface PlayoutAdapter {
378
432
  setPpqn?(ppqn: number): void;
379
433
 
380
434
  init(): Promise<void>;
381
- setTracks(tracks: readonly ClipTrack[]): void; // the engine's own objects: read them, never write to them. Loaded clips only
382
- addTrack?(track: ClipTrack): void;
435
+ // PlayoutTrack (core): a ClipTrack without the view fields of TRACK_VIEW_FIELDS (name,
436
+ // color, height, renderMode, spectrogramConfig, spectrogramColorMap); a change of those
437
+ // alone makes no adapter call. Read the tracks, never write to them. Loaded clips only
438
+ setTracks(tracks: readonly PlayoutTrack[]): void;
439
+ addTrack?(track: PlayoutTrack): void;
383
440
  removeTrack?(trackId: string): void;
384
- updateTrack?(trackId: string, track: ClipTrack): void;
441
+ updateTrack?(trackId: string, track: PlayoutTrack): void;
385
442
 
386
443
  play(startTime: number, endTime?: number): void;
387
444
  pause(): void;
@@ -395,6 +452,9 @@ interface PlayoutAdapter {
395
452
  setTrackMute(trackId: string, muted: boolean): void;
396
453
  setTrackSolo(trackId: string, soloed: boolean): void;
397
454
  setTrackPan(trackId: string, pan: number): void;
455
+ // Optional. 'auto': from the track's clips (core's trackPanLaw). Without it the engine sends
456
+ // the track again (updateTrack, else setTracks), with the law in track.panLaw.
457
+ setTrackPanLaw?(trackId: string, panLaw: PanLaw): void;
398
458
  setLoop(enabled: boolean, start: number, end: number): void;
399
459
 
400
460
  setTempo?(bpm: number, atTick?: number): boolean | void;
@@ -410,7 +470,7 @@ Implement this against your own audio backend to use the engine outside Tone.js
410
470
 
411
471
  ### Pure operations
412
472
 
413
- `src/operations` exports framework-free helper functions the engine itself is built on — `constrainClipDrag`, `constrainBoundaryTrim`, `splitClip`, `canSplitAt`, `calculateDuration`, `findClosestZoomIndex`, `calculateViewportBounds`, `getVisibleChunkIndices`, and more — useful if you need the raw math without the stateful class.
473
+ `src/operations` exports framework-free helper functions the engine itself is built on — `constrainClipDrag`, `constrainBoundaryTrim`, `trackClipSpans` (what a move or a trim collides with, clips still loading included), `splitClip`, `canSplitAt`, `calculateDuration`, `findClosestZoomIndex`, `calculateViewportBounds`, `getVisibleChunkIndices`, and more — useful if you need the raw math without the stateful class. `findClipOverlap(clips)` names the first two clips of a list that overlap: an arrangement refuses a track whose clips do.
414
474
 
415
475
  ## Examples & Documentation
416
476