@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.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. */
@@ -242,7 +470,13 @@ interface PlayoutAdapter {
242
470
  * Snapshot of playlist engine state, emitted on every state change.
243
471
  */
244
472
  interface EngineState {
245
- 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[];
246
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`. */
247
481
  tracksVersion: number;
248
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`. */
@@ -282,11 +516,29 @@ interface EngineState {
282
516
  */
283
517
  interface PlaylistEngineOptions {
284
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;
285
526
  sampleRate?: number;
286
527
  samplesPerPixel?: number;
287
528
  zoomLevels?: number[];
288
- /** 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
+ */
289
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;
290
542
  /** Initial tempo in BPM (default 120). */
291
543
  bpm?: number;
292
544
  /** Pulses per quarter note for headless mode (no adapter). When adapter is provided, adapter.ppqn is used instead. */
@@ -305,13 +557,20 @@ interface EngineEvents {
305
557
  /**
306
558
  * PlaylistEngine — Stateful, framework-agnostic timeline engine.
307
559
  *
308
- * Composes pure operations from ./operations with an event emitter
309
- * 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`.
310
565
  */
311
566
 
312
567
  type EventName = keyof EngineEvents;
313
568
  declare class PlaylistEngine {
314
- private _tracks;
569
+ private _arrangement;
570
+ private _stopFollowingArrangement;
571
+ private _detachFromArrangement;
572
+ private _detachDecodeContext;
573
+ private _adapterSync;
315
574
  private _currentTime;
316
575
  private _playStartPosition;
317
576
  private _isPlaying;
@@ -327,16 +586,9 @@ declare class PlaylistEngine {
327
586
  private _isLoopEnabled;
328
587
  private _bpm;
329
588
  private _ppqn;
330
- private _tracksVersion;
331
- private _mixerVersion;
332
589
  private _adapter;
333
590
  private _disposed;
334
591
  private _listeners;
335
- private _undoStack;
336
- private _redoStack;
337
- private _inTransaction;
338
- private _transactionSnapshot;
339
- private _transactionMutated;
340
592
  readonly undoLimit: number;
341
593
  constructor(options?: PlaylistEngineOptions);
342
594
  get canUndo(): boolean;
@@ -348,7 +600,7 @@ declare class PlaylistEngine {
348
600
  commitTransaction(): void;
349
601
  abortTransaction(): void;
350
602
  getState(): EngineState;
351
- setTracks(tracks: ClipTrack[]): void;
603
+ setTracks(tracks: readonly ClipTrack[]): void;
352
604
  addTrack(track: ClipTrack): void;
353
605
  removeTrack(trackId: string): void;
354
606
  /**
@@ -358,22 +610,21 @@ declare class PlaylistEngine {
358
610
  * playout and interrupt playback for a visual-only change.
359
611
  */
360
612
  reorderTrack(trackId: string, toIndex: number): void;
361
- /** 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
+ */
362
617
  updateTrack(trackId: string, track?: ClipTrack): void;
363
- /** Internal: update adapter after modifying this._tracks in place. */
364
- private _updateTrackOnAdapter;
365
618
  selectTrack(trackId: string | null): void;
366
619
  /** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
367
- getClipBounds(trackId: string, clipId: string): {
368
- offsetSamples: number;
369
- durationSamples: number;
370
- startSample: number;
371
- sourceDurationSamples: number;
372
- } | null;
620
+ getClipBounds(trackId: string, clipId: string): ClipBounds | null;
373
621
  /** Constrain a trim delta using the engine's collision/bounds logic.
374
622
  * Uses the clip's current state and neighboring clips for constraints. */
375
623
  constrainTrimDelta(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number): number;
376
- /** 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
+ */
377
628
  moveClip(trackId: string, clipId: string, deltaSamples: number, skipAdapter?: boolean): number;
378
629
  splitClip(trackId: string, clipId: string, atSample: number): void;
379
630
  trimClip(trackId: string, clipId: string, boundary: 'left' | 'right', deltaSamples: number, skipAdapter?: boolean): void;
@@ -423,9 +674,24 @@ declare class PlaylistEngine {
423
674
  on<K extends EventName>(event: K, listener: EngineEvents[K]): void;
424
675
  off<K extends EventName>(event: K, listener: EngineEvents[K]): void;
425
676
  dispose(): void;
426
- private _snapshotTracks;
427
- private _pushUndoSnapshot;
428
- 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;
429
695
  private _emit;
430
696
  /**
431
697
  * Returns whether the current playback position is before loopEnd.
@@ -438,8 +704,7 @@ declare class PlaylistEngine {
438
704
  private _isBeforeLoopEnd;
439
705
  private _ticksToSeconds;
440
706
  private _secondsToTicks;
441
- private _recomputeStartSamples;
442
707
  private _emitStateChange;
443
708
  }
444
709
 
445
- 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 };