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

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.d.ts CHANGED
@@ -1,4 +1,4 @@
1
- import { AudioClip, ClipTrack } from '@waveform-playlist/core';
1
+ import { AudioClip, ClipTrack, ClipSource, ArrangementTrack, ValueSource } from '@waveform-playlist/core';
2
2
 
3
3
  /**
4
4
  * Clip Operations
@@ -48,7 +48,7 @@ declare function calculateSplitPoint(splitSample: number, samplesPerPixel: numbe
48
48
  * Split a clip into two clips at the given sample position.
49
49
  *
50
50
  * The left clip retains the original fadeIn; the right clip retains the original fadeOut.
51
- * Both clips share the same waveformData reference.
51
+ * Both clips share the same waveformData reference and the same `src`.
52
52
  * If the clip has a name, suffixes " (1)" and " (2)" are appended.
53
53
  *
54
54
  * @param clip - The clip to split
@@ -129,7 +129,7 @@ declare function shouldUpdateViewport(oldScrollLeft: number, newScrollLeft: numb
129
129
  * @param tracks - Array of clip tracks
130
130
  * @returns Duration in seconds
131
131
  */
132
- declare function calculateDuration(tracks: ClipTrack[]): number;
132
+ declare function calculateDuration(tracks: readonly ClipTrack[]): number;
133
133
  /**
134
134
  * Find the zoom level index closest to a given samplesPerPixel.
135
135
  * Returns exact match if found, otherwise the index whose value is
@@ -163,6 +163,233 @@ declare function calculateZoomScrollPosition(oldSamplesPerPixel: number, newSamp
163
163
  */
164
164
  declare function clampSeekPosition(time: number, duration: number): number;
165
165
 
166
+ /**
167
+ * The default way an arrangement turns a clip's source into an `AudioBuffer`:
168
+ * fetch and decode for a URL, `arrayBuffer()` and decode for a Blob or File.
169
+ * The abort signal is checked before the work starts and after each await, so
170
+ * a cancelled load never decodes or resolves.
171
+ */
172
+
173
+ type LoadSource = (src: ClipSource, context: {
174
+ signal: AbortSignal;
175
+ audioContext: BaseAudioContext;
176
+ }) => Promise<AudioBuffer>;
177
+ declare const defaultLoadSource: LoadSource;
178
+
179
+ /**
180
+ * The audio an arrangement's clips name: which sources are wanted, the loader
181
+ * that fetches them, and the switch of a loading clip to a loaded one.
182
+ *
183
+ * Wanted is every source a loading clip names in any state the arrangement
184
+ * holds (the current tracks, each undo and redo state, an open transaction's
185
+ * base), so an undo never starts a fetch again and a failed source stays
186
+ * failed until `retry`. A loaded clip that carries both its `src` and its
187
+ * `audioBuffer` gives the loader that buffer, and nothing is fetched for it.
188
+ * (No state has a loading clip on a MIDI track: the arrangement refuses one.)
189
+ *
190
+ * Nothing here holds tracks. The arrangement hands in its states to declare
191
+ * what is wanted and to have the loaded sources applied; `value` is derived
192
+ * from the loader and from what those passes found.
193
+ */
194
+
195
+ /** Where one source is. `error` is there when it failed. */
196
+ interface ArrangementSourceState {
197
+ status: 'pending' | 'loaded' | 'failed';
198
+ error?: Error;
199
+ }
200
+ /** What `arrangement.sources` holds. A new object only when a status changes. */
201
+ interface ArrangementSourcesValue {
202
+ /** Every source the arrangement's clips name. The order of the entries means nothing. */
203
+ sources: ReadonlyMap<ClipSource, ArrangementSourceState>;
204
+ pendingCount: number;
205
+ failedCount: number;
206
+ /** True while a source is pending. */
207
+ isLoading: boolean;
208
+ }
209
+
210
+ /**
211
+ * The mixer part of an arrangement: volume, mute, solo and pan by track id,
212
+ * as pure functions over an immutable Map.
213
+ *
214
+ * The values live here and not on the track objects, so a fader move
215
+ * replaces no track, and an undo (which restores tracks) never changes the
216
+ * mix. A track's own `volume` / `muted` / `soloed` / `pan` fields are the
217
+ * values it ENTERED with; they seed its entry when its id has none, and are
218
+ * not read while it has one.
219
+ */
220
+
221
+ interface TrackMixerValues {
222
+ volume: number;
223
+ muted: boolean;
224
+ soloed: boolean;
225
+ pan: number;
226
+ }
227
+
228
+ /**
229
+ * The public face of an arrangement.
230
+ */
231
+
232
+ interface ClipBounds {
233
+ offsetSamples: number;
234
+ durationSamples: number;
235
+ startSample: number;
236
+ sourceDurationSamples: number;
237
+ }
238
+ interface RemoveTrackOptions {
239
+ /**
240
+ * `false`: the removal is not an undo step, and the track is also taken
241
+ * out of every undo and redo state, so no undo or redo brings it back.
242
+ * For a track that should never have been there (a dropped file that could
243
+ * not be decoded).
244
+ */
245
+ undoable?: boolean;
246
+ }
247
+ /**
248
+ * The owner of the tracks, of the mix and of the undo history. Everything
249
+ * else reads it (`getTracks`, `getMixer`, `subscribe`) and changes it by
250
+ * calling its methods. A `PlaylistEngine` built on it plays it.
251
+ *
252
+ * Nothing it returns is a copy: never write to a tracks array, a track, a
253
+ * clip or the mixer Map. Outside production builds the tracks are frozen.
254
+ */
255
+ interface Arrangement {
256
+ /**
257
+ * The tracks and their clips: loaded clips (`AudioClip`) and clips whose
258
+ * audio is not loaded yet (`LoadingClip`; tell them apart with
259
+ * `isLoadingClip`). The same array until they change.
260
+ */
261
+ getTracks(): readonly ArrangementTrack[];
262
+ /**
263
+ * The current volume, mute, solo and pan by track id. The same Map until a
264
+ * value changes, a track with a new id enters, or entries of tracks that
265
+ * are gone are dropped (`mixerVersion` counts value changes only). A
266
+ * track's own mixer fields in `getTracks()` are the values it entered
267
+ * with; the current ones are here.
268
+ */
269
+ getMixer(): ReadonlyMap<string, TrackMixerValues>;
270
+ /**
271
+ * Be told after every change (tracks, mix or history), once per change, in
272
+ * the order the changes were made. Returns a function that stops it. A
273
+ * listener that throws is reported with `console.warn` and does not fail
274
+ * the change.
275
+ */
276
+ subscribe(listener: () => void): () => void;
277
+ /** Counts changes to the tracks. */
278
+ readonly tracksVersion: number;
279
+ /** Counts changes to the mix. */
280
+ readonly mixerVersion: number;
281
+ /**
282
+ * Replace every track. Clears the undo history and ends an open
283
+ * transaction. An id that is in the tracks being replaced keeps its mix.
284
+ */
285
+ setTracks(tracks: readonly ArrangementTrack[]): void;
286
+ addTrack(track: ArrangementTrack): void;
287
+ removeTrack(trackId: string, options?: RemoveTrackOptions): void;
288
+ /**
289
+ * Replace a track, with a track or with a function of the current one.
290
+ * Changes nothing for an id no track has (a track object is still checked
291
+ * and may throw; a function is not called). The mixer fields of the new
292
+ * track are not read: use the setters. A track that is given a new id
293
+ * takes its mix with it.
294
+ */
295
+ updateTrack(trackId: string, next: ArrangementTrack | ((track: ArrangementTrack) => ArrangementTrack)): void;
296
+ /** Move a track to another place in the order. */
297
+ reorderTrack(trackId: string, toIndex: number): void;
298
+ /** Move a clip. Returns the delta actually applied (0 when it cannot move). */
299
+ moveClip(trackId: string, clipId: string, deltaSamples: number): number;
300
+ trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): void;
301
+ splitClip(trackId: string, clipId: string, atSample: number): void;
302
+ getClipBounds(trackId: string, clipId: string): ClipBounds | null;
303
+ constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
304
+ setTrackVolume(trackId: string, volume: number): void;
305
+ setTrackMute(trackId: string, muted: boolean): void;
306
+ setTrackSolo(trackId: string, soloed: boolean): void;
307
+ setTrackPan(trackId: string, pan: number): void;
308
+ readonly canUndo: boolean;
309
+ readonly canRedo: boolean;
310
+ /** With a transaction open: aborts it first. */
311
+ undo(): void;
312
+ /** With a transaction open: aborts it first. */
313
+ redo(): void;
314
+ clearHistory(): void;
315
+ /** Changes made until `commitTransaction` are one undo step. */
316
+ beginTransaction(): void;
317
+ commitTransaction(): void;
318
+ /** Put the tracks back as they were when the transaction began. */
319
+ abortTransaction(): void;
320
+ /**
321
+ * Where each source the clips name is: pending, loaded or failed (also a
322
+ * source of which a clip in the current tracks could not be made from its
323
+ * audio). Read it with `getSnapshot()` or
324
+ * `subscribe()`; the same object until a status changes. When a source is
325
+ * loaded, every loading clip that names it has become a loaded clip, in the
326
+ * current tracks and in every undo and redo state; that is not an undo step.
327
+ * The tracks change first and are announced first: a `subscribe` listener
328
+ * told of the loaded clip still reads the source as pending here.
329
+ */
330
+ readonly sources: ValueSource<ArrangementSourcesValue>;
331
+ /**
332
+ * Start a source whose load failed again. Does nothing for any other
333
+ * source, also one shown as failed because a clip could not be made from
334
+ * its audio (the audio is loaded; loading it again changes nothing).
335
+ */
336
+ retry(src: ClipSource): void;
337
+ }
338
+ interface CreateArrangementOptions {
339
+ /** The first tracks. Not an undo step. */
340
+ tracks?: readonly ArrangementTrack[];
341
+ /** Maximum number of undo steps (default 100). */
342
+ undoLimit?: number;
343
+ /**
344
+ * How a clip's source becomes an AudioBuffer. Default: `defaultLoadSource`
345
+ * (fetch a URL or read a Blob, then decode).
346
+ */
347
+ loadSource?: LoadSource;
348
+ }
349
+
350
+ /**
351
+ * The two points where something attaches to an arrangement: a context to
352
+ * decode audio with, and an engine's time base.
353
+ *
354
+ * They are reached through `Symbol.for` keys, not through `instanceof` or a
355
+ * method name. An app whose own version of this package differs from the one
356
+ * a library pins has two copies installed, and an arrangement made by one
357
+ * copy must be playable by an engine of the other: `Symbol.for` gives both
358
+ * copies the same key.
359
+ *
360
+ * The keys carry a version. An engine that finds the time-base key treats
361
+ * the object as an arrangement of this version and uses it BY NAME: the
362
+ * whole public `Arrangement` interface (every track, clip, mixer and history
363
+ * method it delegates to, `getTracks`, `getMixer`, the two version counters)
364
+ * and the internal `onChange(listener)` (with the `ArrangementChange` and
365
+ * `ArrangementVersions` shapes of this version), `recomputeStartSamples()`
366
+ * and `undoLimit`. A change to any of that needs a new key, so that copies
367
+ * which do not agree refuse each other instead of misreading each other.
368
+ */
369
+
370
+ type GetDecodeContext = () => Promise<BaseAudioContext>;
371
+ /**
372
+ * Give an arrangement the audio context its sources are decoded with.
373
+ * Nothing is fetched before; the sources its clips name are pending
374
+ * meanwhile. `getContext` is called for each load, so it may resume or
375
+ * create the context when the first one is needed.
376
+ *
377
+ * Returns the function that takes the context away again: the loads in
378
+ * flight are aborted and start again at the next attach; what is loaded
379
+ * stays. One context at a time: a second attach warns and replaces the first.
380
+ *
381
+ * A `PlaylistEngine` with an adapter does this itself with the adapter's
382
+ * context (see its `attachDecodeContext` option).
383
+ */
384
+ declare function attachDecodeContext(arrangement: Arrangement, getContext: GetDecodeContext): () => void;
385
+
386
+ /**
387
+ * Make an arrangement: the owner of the tracks, the mix and the undo
388
+ * history. It needs no engine; give it to `new PlaylistEngine({ arrangement })`
389
+ * to play it, and to the next engine when that one is disposed.
390
+ */
391
+ declare function createArrangement(options?: CreateArrangementOptions): Arrangement;
392
+
166
393
  /**
167
394
  * Interface for pluggable audio playback adapters.
168
395
  * Implement this to connect PlaylistEngine to any audio backend
@@ -174,7 +401,8 @@ interface PlayoutAdapter {
174
401
  /** Set the adapter's tick resolution. Optional — adapters with fixed PPQN ignore this. */
175
402
  setPpqn?(ppqn: number): void;
176
403
  init(): Promise<void>;
177
- setTracks(tracks: ClipTrack[]): void;
404
+ /** The tracks are the engine's own objects: read them, never write to them. */
405
+ setTracks(tracks: readonly ClipTrack[]): void;
178
406
  /** Incrementally add a single track without rebuilding the entire playout. */
179
407
  addTrack?(track: ClipTrack): void;
180
408
  /** Incrementally remove a single track without rebuilding the entire playout. */
@@ -206,10 +434,17 @@ interface PlayoutAdapter {
206
434
  setTempo?(bpm: number, atTick?: number): boolean | void;
207
435
  /** Set time signature at a tick position. */
208
436
  setMeter?(numerator: number, denominator: number, atTick?: number): void;
209
- /** Convert ticks to seconds using the adapter's tempo map. */
437
+ /** Convert ticks to seconds using the adapter's tempo map. Accepts a
438
+ * fractional tick position (e.g. from secondsToTicksExact). */
210
439
  ticksToSeconds?(tick: number): number;
211
- /** Convert seconds to ticks using the adapter's tempo map. */
440
+ /** Convert seconds to an integer tick using the adapter's tempo map. */
212
441
  secondsToTicks?(seconds: number): number;
442
+ /** Convert seconds to a fractional tick position using the adapter's tempo
443
+ * map — for sub-tick placement (a recorded note between ticks, before
444
+ * quantising). Optional; an adapter that cannot provide it leaves it out,
445
+ * and a consumer that needs it should fall back to secondsToTicks (no
446
+ * engine code path consumes it yet). */
447
+ secondsToTicksExact?(seconds: number): number;
213
448
  /** Register a worklet module URL on this adapter's AudioContext.
214
449
  * Abstracts native vs standardized-audio-context differences. */
215
450
  addWorkletModule?(url: string): Promise<void>;
@@ -235,7 +470,13 @@ interface PlayoutAdapter {
235
470
  * Snapshot of playlist engine state, emitted on every state change.
236
471
  */
237
472
  interface EngineState {
238
- tracks: ClipTrack[];
473
+ /**
474
+ * The tracks, each with its current mixer values. The same array until the
475
+ * tracks or the mix change. It is the engine's own, shared with the undo
476
+ * history: never write to it or to a track or clip in it (copy first).
477
+ * Outside production builds it is frozen, so a write throws.
478
+ */
479
+ tracks: readonly ClipTrack[];
239
480
  /** Monotonic counter incremented on any structural tracks mutation (setTracks, addTrack, removeTrack, moveClip, trimClip, splitClip). Does NOT change on per-track mixer edits — see `mixerVersion`. */
240
481
  tracksVersion: number;
241
482
  /** Monotonic counter incremented on per-track mixer edits (setTrackVolume, setTrackMute, setTrackSolo, setTrackPan). Lets consumers refresh a cached track snapshot to keep mixer state without triggering the structural resync work (audio-graph rewire, peak regeneration) gated on `tracksVersion`. */
@@ -275,11 +516,29 @@ interface EngineState {
275
516
  */
276
517
  interface PlaylistEngineOptions {
277
518
  adapter?: PlayoutAdapter;
519
+ /**
520
+ * The arrangement to play, from `createArrangement()`. It outlives the
521
+ * engine: dispose the engine, build another on the same arrangement, and
522
+ * the tracks, the mix and the undo history are all still there. Left out,
523
+ * the engine makes an arrangement of its own. One engine at a time.
524
+ */
525
+ arrangement?: Arrangement;
278
526
  sampleRate?: number;
279
527
  samplesPerPixel?: number;
280
528
  zoomLevels?: number[];
281
- /** Maximum number of undo steps (default 100). */
529
+ /**
530
+ * Maximum number of undo steps (default 100). Only when the engine makes its
531
+ * own arrangement; an arrangement that is passed in has its own limit.
532
+ */
282
533
  undoLimit?: number;
534
+ /**
535
+ * `false`: the engine does not give its arrangement the adapter's audio
536
+ * context to decode with, because the host does that itself with
537
+ * `attachDecodeContext()`. Default `true`: an engine with an adapter
538
+ * attaches `adapter.audioContext` when it is built and detaches it in
539
+ * `dispose()`. An engine without an adapter has no context to attach.
540
+ */
541
+ attachDecodeContext?: boolean;
283
542
  /** Initial tempo in BPM (default 120). */
284
543
  bpm?: number;
285
544
  /** Pulses per quarter note for headless mode (no adapter). When adapter is provided, adapter.ppqn is used instead. */
@@ -298,13 +557,20 @@ interface EngineEvents {
298
557
  /**
299
558
  * PlaylistEngine — Stateful, framework-agnostic timeline engine.
300
559
  *
301
- * Composes pure operations from ./operations with an event emitter
302
- * and optional PlayoutAdapter for audio playback delegation.
560
+ * Composes an Arrangement (the tracks, the mix, the undo history and
561
+ * transactions) with an event emitter and optional PlayoutAdapter for audio
562
+ * playback delegation. A track method calls the arrangement; the engine
563
+ * subscribes to the arrangement and, for each change it is told about, makes
564
+ * the adapter call and emits `statechange`.
303
565
  */
304
566
 
305
567
  type EventName = keyof EngineEvents;
306
568
  declare class PlaylistEngine {
307
- private _tracks;
569
+ private _arrangement;
570
+ private _stopFollowingArrangement;
571
+ private _detachFromArrangement;
572
+ private _detachDecodeContext;
573
+ private _adapterSync;
308
574
  private _currentTime;
309
575
  private _playStartPosition;
310
576
  private _isPlaying;
@@ -320,16 +586,9 @@ declare class PlaylistEngine {
320
586
  private _isLoopEnabled;
321
587
  private _bpm;
322
588
  private _ppqn;
323
- private _tracksVersion;
324
- private _mixerVersion;
325
589
  private _adapter;
326
590
  private _disposed;
327
591
  private _listeners;
328
- private _undoStack;
329
- private _redoStack;
330
- private _inTransaction;
331
- private _transactionSnapshot;
332
- private _transactionMutated;
333
592
  readonly undoLimit: number;
334
593
  constructor(options?: PlaylistEngineOptions);
335
594
  get canUndo(): boolean;
@@ -341,7 +600,7 @@ declare class PlaylistEngine {
341
600
  commitTransaction(): void;
342
601
  abortTransaction(): void;
343
602
  getState(): EngineState;
344
- setTracks(tracks: ClipTrack[]): void;
603
+ setTracks(tracks: readonly ClipTrack[]): void;
345
604
  addTrack(track: ClipTrack): void;
346
605
  removeTrack(trackId: string): void;
347
606
  /**
@@ -351,22 +610,21 @@ declare class PlaylistEngine {
351
610
  * playout and interrupt playback for a visual-only change.
352
611
  */
353
612
  reorderTrack(trackId: string, toIndex: number): void;
354
- /** Update a single track's clips on the adapter (no full rebuild). */
613
+ /**
614
+ * With a track: replace that track (an undo step). Without one: send the
615
+ * current track to the adapter again (no full rebuild, no change of state).
616
+ */
355
617
  updateTrack(trackId: string, track?: ClipTrack): void;
356
- /** Internal: update adapter after modifying this._tracks in place. */
357
- private _updateTrackOnAdapter;
358
618
  selectTrack(trackId: string | null): void;
359
619
  /** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
360
- getClipBounds(trackId: string, clipId: string): {
361
- offsetSamples: number;
362
- durationSamples: number;
363
- startSample: number;
364
- sourceDurationSamples: number;
365
- } | null;
620
+ getClipBounds(trackId: string, clipId: string): ClipBounds | null;
366
621
  /** Constrain a trim delta using the engine's collision/bounds logic.
367
622
  * Uses the clip's current state and neighboring clips for constraints. */
368
623
  constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
369
- /** Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op). */
624
+ /**
625
+ * Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op).
626
+ * With `skipAdapter` the change is not sent to the adapter (a drag sends the track once, on drop).
627
+ */
370
628
  moveClip(trackId: string, clipId: string, deltaSamples: number, skipAdapter?: boolean): number;
371
629
  splitClip(trackId: string, clipId: string, atSample: number): void;
372
630
  trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number, skipAdapter?: boolean): void;
@@ -416,9 +674,24 @@ declare class PlaylistEngine {
416
674
  on<K extends EventName>(event: K, listener: EngineEvents[K]): void;
417
675
  off<K extends EventName>(event: K, listener: EngineEvents[K]): void;
418
676
  dispose(): void;
419
- private _snapshotTracks;
420
- private _pushUndoSnapshot;
421
- private _restoreTracks;
677
+ /** Runs a mixer setter on the arrangement. True when a value changed. */
678
+ private _mixerChanged;
679
+ /**
680
+ * The arrangement changed: bring the adapter in step, then emit
681
+ * `statechange`. Every change is one emission. An adapter that throws
682
+ * stops the emission and fails the arrangement call that is delivering
683
+ * (for a change made from inside a listener, that is the outer call).
684
+ */
685
+ private _onArrangementChange;
686
+ /**
687
+ * Audio arrived by itself: there is no caller to fail when the adapter
688
+ * throws. The error is reported, the `statechange` is still emitted (the
689
+ * tracks did change), and the next track change sends the adapter every
690
+ * track.
691
+ */
692
+ private _followLoad;
693
+ /** The selected track id names a track; when that track is gone, nothing is selected. */
694
+ private _clearSelectionIfGone;
422
695
  private _emit;
423
696
  /**
424
697
  * Returns whether the current playback position is before loopEnd.
@@ -431,8 +704,7 @@ declare class PlaylistEngine {
431
704
  private _isBeforeLoopEnd;
432
705
  private _ticksToSeconds;
433
706
  private _secondsToTicks;
434
- private _recomputeStartSamples;
435
707
  private _emitStateChange;
436
708
  }
437
709
 
438
- export { type EngineEvents, type EngineState, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, findClosestZoomIndex, getVisibleChunkIndices, shouldUpdateViewport, splitClip };
710
+ export { type Arrangement, type ArrangementSourceState, type ArrangementSourcesValue, type ClipBounds, type CreateArrangementOptions, type EngineEvents, type EngineState, type LoadSource, PlaylistEngine, type PlaylistEngineOptions, type PlayoutAdapter, type RemoveTrackOptions, type TrackMixerValues, attachDecodeContext, calculateDuration, calculateSplitPoint, calculateViewportBounds, calculateZoomScrollPosition, canSplitAt, clampSeekPosition, constrainBoundaryTrim, constrainClipDrag, createArrangement, defaultLoadSource, findClosestZoomIndex, getVisibleChunkIndices, shouldUpdateViewport, splitClip };