@dawcore/transport 0.0.14 → 0.0.15

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
@@ -11,6 +11,15 @@ declare const __sample: unique symbol;
11
11
  type Sample = number & {
12
12
  readonly [__sample]: never;
13
13
  };
14
+ /** Branded type for AudioContext frames (the Clock's unit, at `audioContext.sampleRate`).
15
+ * Distinct from `Sample` (the SampleTimeline's `sampleRate` option, which may
16
+ * differ from the context's) so the two rates cannot be mixed silently. Like
17
+ * `Sample`, it does not distinguish frames of different AudioContexts (e.g. an
18
+ * offline render context at another rate). */
19
+ declare const __contextFrame: unique symbol;
20
+ type ContextFrame = number & {
21
+ readonly [__contextFrame]: never;
22
+ };
14
23
  interface SchedulerEvent {
15
24
  /** Tick position (integer) on the timeline */
16
25
  tick: Tick;
@@ -40,6 +49,9 @@ interface TransportOptions {
40
49
  denominator?: number;
41
50
  /** How far ahead to schedule audio, in seconds. Default: 0.2 */
42
51
  schedulerLookahead?: number;
52
+ /** Scheduling tick cadence in milliseconds (a Worker setTimeout loop).
53
+ * Must be shorter than the lookahead. Default: 25 */
54
+ timerIntervalMs?: number;
43
55
  /** Accent click frequency in Hz. Default: 1000 */
44
56
  accentFrequency?: number;
45
57
  /** Normal click frequency in Hz. Default: 800 */
@@ -65,14 +77,14 @@ interface MeterEntry {
65
77
  * 'step' = instant jump (default). 'linear' = linear ramp.
66
78
  * { type: 'curve', slope } = Möbius-Ease curve (slope 0-1 exclusive). */
67
79
  type TempoInterpolation = 'step' | 'linear' | {
68
- type: 'curve';
69
- slope: number;
80
+ readonly type: 'curve';
81
+ readonly slope: number;
70
82
  };
71
83
  interface TempoEntry {
72
84
  /** Tick position where this tempo starts */
73
- tick: Tick;
85
+ readonly tick: Tick;
74
86
  /** Beats per minute */
75
- bpm: number;
87
+ readonly bpm: number;
76
88
  /** How to arrive at this BPM from the previous entry */
77
89
  readonly interpolation: TempoInterpolation;
78
90
  /** Cached cumulative seconds up to this tick (for O(log n) lookup). Derived — do not set manually. */
@@ -115,33 +127,177 @@ interface MeterChangeEventData {
115
127
  /** Tick position where the meter was set or removed */
116
128
  atTick: Tick;
117
129
  }
130
+ /** Payload of the transport `error` event and the Scheduler `onError` option:
131
+ * a scheduler listener (ClipPlayer, MetronomePlayer, CountInPlayer, or a
132
+ * custom one) threw. The scheduler skipped the failing unit of work — that
133
+ * listener's window (`generate`), that one event (`consume`) or that one
134
+ * jump (`positionJump`) — and kept going; the host decides what to do.
135
+ * Discriminated on `phase`, so the context each phase carries is required,
136
+ * not optional. */
137
+ type SchedulerListenerError = (SchedulerListenerErrorBase & {
138
+ readonly phase: 'generate';
139
+ /** The window [fromTick, toTick) that generate() was asked for */
140
+ readonly fromTick: Tick;
141
+ readonly toTick: Tick;
142
+ }) | (SchedulerListenerErrorBase & {
143
+ readonly phase: 'consume';
144
+ /** The event being consumed */
145
+ readonly event: SchedulerEvent;
146
+ }) | (SchedulerListenerErrorBase & {
147
+ readonly phase: 'positionJump';
148
+ /** The tick the scheduler jumped to (the loop start) */
149
+ readonly tick: Tick;
150
+ });
151
+ interface SchedulerListenerErrorBase {
152
+ /** The listener that threw */
153
+ readonly listener: SchedulerListener<SchedulerEvent>;
154
+ /** The thrown value, unchanged */
155
+ readonly error: unknown;
156
+ }
118
157
 
158
+ /** Web Audio renders in blocks of 128 frames (the spec default; a context
159
+ * created with a non-default `renderSizeHint` renders in other block sizes),
160
+ * so `AudioContext.currentTime` normally advances by exactly this many frames
161
+ * per render and a reading sits on this lattice up to float noise. A context
162
+ * off the lattice simply keeps its raw integer frame (see LATTICE_SNAP_FRAMES). */
163
+ declare const RENDER_QUANTUM_FRAMES = 128;
164
+ /**
165
+ * Transport position, with elapsed time counted in integer context frames
166
+ * (#636).
167
+ *
168
+ * The position is `seekPosition + elapsedFrames`, where `elapsedFrames` is
169
+ * ONE integer accumulator: whole frames elapsed in earlier runs since the last
170
+ * seek (`_elapsedBeforeAnchor`) plus, while running, the frames since the
171
+ * current anchor (`contextFrame − contextFrameAtAnchor`). `contextFrame` is
172
+ * `currentTime × sampleRate` snapped to the render-quantum lattice. The seek
173
+ * position is kept in BOTH units — `_seekFrames` (fractional after a seconds
174
+ * seek) and `_seekSeconds` (the exact seconds a caller passed) — so
175
+ * `getTime()` returns a seek target bit-exactly (`(t × rate) / rate` differs
176
+ * from `t` for roughly one millisecond position in seven at 44.1 kHz) and the
177
+ * two views cannot drift apart across pause/resume cycles: both add the same
178
+ * integer. `getFrame()` rounds once at the ContextFrame boundary;
179
+ * `getFrameExact()` keeps the fraction — the round-once rule of the tick
180
+ * conversions.
181
+ *
182
+ * Anchoring events (the full table, including `reset()`, is in
183
+ * packages/transport/CLAUDE.md — keep the two in step):
184
+ * - `start()` anchors the current position to the current context frame. It
185
+ * reads the context BEFORE setting `_running`, so a context that moved
186
+ * backwards while stopped re-anchors silently instead of counting a re-base.
187
+ * - `seekTo()`/`seekToFrame()` while running re-anchor to the current frame.
188
+ * - `stop()` folds the frames elapsed in this run into the accumulator.
189
+ * - A context reading that goes BACKWARDS while running moves the anchor with
190
+ * it so the position holds instead of jumping back. The spec makes
191
+ * currentTime monotonic and #636 describes Chromium STALLING it on device
192
+ * changes, so this is a defensive path. Whoever reads first absorbs it —
193
+ * reads are idempotent (the outcome does not depend on which reader saw it)
194
+ * — and `rebaseCount` / `lastRebaseFrames` let the Transport notice on its
195
+ * next tick and re-create the sources it armed in the old time base.
196
+ * - A STALLED reading (suspend, device change) simply freezes the position:
197
+ * no audio is rendering, so no transport time elapses. Nothing to re-anchor.
198
+ * Forward jumps are taken at face value — the context rendered that audio.
199
+ *
200
+ * Frames are CONTEXT-rate frames (`audioContext.sampleRate`, the
201
+ * `ContextFrame` brand); a Transport built with a different `sampleRate`
202
+ * option converts via its SampleTimeline (`Sample` brand).
203
+ */
119
204
  declare class Clock {
120
- private _audioContext;
205
+ private readonly _audioContext;
206
+ private readonly _sampleRate;
121
207
  private _running;
122
- private _audioTimeAtStart;
123
- private _clockTimeAtStart;
208
+ /** Snapped context frame when the current run was anchored. */
209
+ private _contextFrameAtAnchor;
210
+ /** Position at the last seek, in frames (fractional after a seconds seek). */
211
+ private _seekFrames;
212
+ /** The same position in seconds — bit-exactly what seekTo(seconds) got. */
213
+ private _seekSeconds;
214
+ /** Whole frames elapsed in earlier runs since the last seek. */
215
+ private _elapsedBeforeAnchor;
216
+ /** The PREVIOUS snapped context reading (not a high-water mark): a lower
217
+ * reading than this one, while running, is a re-base. */
218
+ private _lastContextFrame;
219
+ private _rebaseCount;
220
+ private _lastRebaseFrames;
124
221
  constructor(audioContext: AudioContext);
222
+ /** The rate frames are counted in: the AudioContext's. */
223
+ get sampleRate(): number;
224
+ /** How many backward context readings were absorbed while running. The
225
+ * Transport diffs this against its own cursor each tick to re-create
226
+ * sources armed in the old time base; observers may read it freely. */
227
+ get rebaseCount(): number;
228
+ /** Size (frames) of the most recently absorbed backward reading. */
229
+ get lastRebaseFrames(): number;
230
+ /** Seconds → whole context frames, rounded once here. */
231
+ secondsToFrame(seconds: number): ContextFrame;
232
+ /** Whole context frames → seconds (the inverse view). */
233
+ frameToSeconds(frame: ContextFrame): number;
125
234
  start(): void;
126
235
  stop(): void;
127
236
  reset(): void;
237
+ /** Position in seconds: the exact seek target plus whole elapsed frames. */
128
238
  getTime(): number;
239
+ /** Position in whole context frames (rounded once, here). */
240
+ getFrame(): ContextFrame;
241
+ /** Position in frames, keeping any sub-frame part a seconds seek introduced. */
242
+ getFrameExact(): number;
129
243
  seekTo(time: number): void;
244
+ /** A fractional frame is rounded here, at the API boundary. */
245
+ seekToFrame(frame: ContextFrame): void;
130
246
  /**
131
- * Convert transport time to AudioContext.currentTime space.
132
- * Used by players to schedule AudioBufferSourceNode.start(when).
247
+ * Convert transport time to AudioContext.currentTime space, for
248
+ * AudioBufferSourceNode.start(when). Anchor-based in both states: while
249
+ * running it never re-reads currentTime, so sub-quantum noise in a reading
250
+ * cannot shift scheduled events; stopped, the anchor is the same snapped
251
+ * "now" that start() is about to capture, so a `when` computed just before
252
+ * start() and one computed just after are identical.
133
253
  */
134
254
  toAudioTime(transportTime: number): number;
135
255
  isRunning(): boolean;
256
+ private _seekToPosition;
257
+ /** Position (frames) at the start of the current run. */
258
+ private _positionAtAnchorFrames;
259
+ /** Whole frames elapsed since the last seek, across runs. */
260
+ private _totalElapsedFrames;
261
+ /** Whole frames elapsed since the anchor (running only). */
262
+ private _elapsedFrames;
263
+ /** currentTime as an integer frame on the render-quantum lattice. Pure. */
264
+ private _snappedContextFrame;
265
+ /** The snapped reading, with backward re-bases absorbed. Not pure: the
266
+ * first reader to see a backward reading shifts the anchor (idempotent —
267
+ * every later reader sees the already-held position). */
268
+ private _readContextFrame;
136
269
  }
137
270
 
138
271
  interface SetTempoOptions {
139
272
  interpolation?: TempoInterpolation;
140
273
  }
274
+ /** Module-private token: the entries constructor form is only reachable from
275
+ * withTempo/withoutTempo (via _derive). A caller without the token gets a
276
+ * thrown error instead of a map built from unvalidated, unsealed entries. */
277
+ declare const INTERNAL: unique symbol;
278
+ /** The type of the module-private constructor token. Exported so the
279
+ * constructor overload can name it in the published declarations; no value
280
+ * of this type exists outside this module, so the overload is unusable
281
+ * (not just guarded at runtime) from anywhere else. */
282
+ type TempoMapInternalToken = typeof INTERNAL;
283
+ /**
284
+ * Immutable tempo map (#636). Every edit — withTempo, withoutTempo,
285
+ * withoutTempos — returns a NEW map and leaves this one untouched, so a
286
+ * reference captured by a scheduler window, a snapshot in a UI, or a
287
+ * count-in's dedicated map can never observe a half-updated cache. Transport
288
+ * owns the current map and swaps it into every holder on each edit.
289
+ */
141
290
  declare class TempoMap {
142
- private _ppqn;
143
- private _entries;
291
+ private readonly _ppqn;
292
+ private readonly _entries;
293
+ /** `new TempoMap(ppqn, initialBpm)` — a single-tempo map. The entries
294
+ * form is internal: it is how withTempo/withoutTempo build their result
295
+ * (entries already validated, cached and sealed) and it requires a
296
+ * module-private token, so it cannot be used from outside. */
297
+ /** Defaults: 960 PPQN, 120 BPM. */
144
298
  constructor(ppqn?: number, initialBpm?: number);
299
+ /** @internal */
300
+ constructor(ppqn: number, entries: readonly TempoEntry[], token: TempoMapInternalToken);
145
301
  /** A non-finite or non-positive BPM silently corrupts the secondsAtTick
146
302
  * cache (Infinity, or non-monotonic values that break the binary search
147
303
  * in secondsToTicks) — reject it at the boundary instead. */
@@ -150,18 +306,44 @@ declare class TempoMap {
150
306
  /** Number of tempo entries in the map. Always >= 1 — the tick-0 entry is
151
307
  * permanent. Used by Transport.setTempo to detect multi-entry maps. */
152
308
  get entryCount(): number;
153
- setTempo(bpm: number, atTick?: Tick, options?: SetTempoOptions): void;
154
- ticksToSeconds(ticks: Tick): number;
309
+ /** The entries, in tick order, frozen. `secondsAtTick` is the cumulative
310
+ * seconds up to each entry. */
311
+ get entries(): readonly TempoEntry[];
312
+ /** Return a new map with `bpm` at `atTick` (replacing an existing entry
313
+ * there). Tick 0 is always 'step'. Throws on an invalid BPM, curve slope
314
+ * or atTick (non-negative integer); this map is never modified. */
315
+ withTempo(bpm: number, atTick?: Tick, options?: SetTempoOptions): TempoMap;
316
+ /** Return a new map without the entry at exactly `atTick`. The tick-0 entry
317
+ * is permanent (a map must always have a tempo), and a tick with no entry
318
+ * is a no-op — both return this same map. An invalid tick throws. */
319
+ withoutTempo(atTick: Tick): TempoMap;
320
+ /** Return a new single-entry map keeping only the tick-0 tempo. */
321
+ withoutTempos(): TempoMap;
322
+ /** Build the successor map: recompute cumulative seconds from `fromIndex`
323
+ * into a fresh, sealed entry list. Entries before `fromIndex` are the
324
+ * previous map's frozen objects, reused by reference. Nothing on `this`
325
+ * is written. */
326
+ private _derive;
327
+ /** Seconds spanned from `prev` to `entry` under `entry`'s interpolation. */
328
+ private _segmentSeconds;
329
+ /** Tick position → seconds. Accepts a fractional position (e.g. the value
330
+ * secondsToTicksExact returned) as well as an integer Tick. */
331
+ ticksToSeconds(ticks: number): number;
332
+ /** Seconds → integer ticks, rounded once here at the `Tick` boundary.
333
+ * Use secondsToTicksExact() for sub-tick placement. */
155
334
  secondsToTicks(seconds: number): Tick;
335
+ /** Seconds → fractional tick position (unrounded). The integer producers
336
+ * round this once at their own boundary (secondsToTicks,
337
+ * SampleTimeline.samplesToTicks); sub-tick consumers (placing a recorded
338
+ * note between ticks before quantising, continuous beat positions) use it
339
+ * directly. Not clamped: negative seconds convert at the constant initial
340
+ * tempo to negative ticks (whatever the first segment's interpolation),
341
+ * and seconds past the last entry extrapolate the last tempo forwards. */
342
+ secondsToTicksExact(seconds: number): number;
343
+ private _secondsToTicksRaw;
156
344
  beatsToSeconds(beats: number): number;
345
+ /** Continuous beat position (fractional) — not quantised to whole ticks. */
157
346
  secondsToBeats(seconds: number): number;
158
- clearTempos(): void;
159
- /** Remove the tempo entry at exactly `atTick`, if one exists. The tick-0
160
- * entry is permanent (a map must always have a tempo) — removing it is a
161
- * no-op, matching removeMeter's treatment of the initial meter. The
162
- * seconds cache is recomputed from the removal point, the same partial
163
- * update setTempo uses. */
164
- removeTempo(atTick: Tick): void;
165
347
  /** Get the interpolated BPM at a tick position */
166
348
  private _getTempoAt;
167
349
  private _ticksToSecondsInternal;
@@ -176,25 +358,48 @@ declare class TempoMap {
176
358
  * Closed-form via exponential: bpmAtTick = bpm0 * exp(seconds * deltaBpm * ppqn / (60 * T))
177
359
  * then ticks = (bpmAtTick - bpm0) * T / deltaBpm
178
360
  *
179
- * Note: exp(log(x)) has ~1 ULP floating-point error, so round-trips depend on
180
- * Math.round() in the caller (secondsToTicks). This is sufficient for all tested
181
- * BPM ranges (10–300 BPM) but is not algebraically exact like the previous
182
- * trapezoidal/quadratic approach was.
361
+ * Note: exp(log(x)) has ~1 ULP floating-point error, so integer round-trips
362
+ * rely on the rounding in secondsToTicks; secondsToTicksExact returns the
363
+ * raw value. Sufficient for all tested BPM ranges (10–300 BPM).
183
364
  */
184
365
  private _secondsToTicksLinear;
185
366
  /**
186
- * Subdivided trapezoidal integration for a Möbius-Ease tempo curve.
187
- * The BPM at progress p is: bpm0 + curveNormalizedAt(p, slope) * (bpm1 - bpm0).
188
- * We subdivide into CURVE_SUBDIVISIONS intervals and apply trapezoidal rule.
367
+ * Exact integration for a Möbius-Ease tempo curve.
368
+ * With x = ticks / T the BPM is bpm0 + Δ·(p²/(1 − 2p))·(e^(c·x) − 1), i.e.
369
+ * A + B·e^(c·x) for B = Δ·p²/(1 − 2p), A = bpm0 − B. Its reciprocal has the
370
+ * antiderivative u/A − ln(A + B·e^(c·u))/(c·A), so
371
+ * seconds = base · (c·x − ln(bpm(x)/bpm0)) / (c·A), base = T·60/ppqn.
372
+ * Everything is carried as c·A and c·B so the slope → 0.5 limit (B → ∞,
373
+ * c → 0) stays finite. Two algebraically equal forms are used, chosen per
374
+ * call so neither one cancels:
375
+ * - log1p form: base · (1 − e^(−c·x))/(c·bpm0) · log1p(y)/y with
376
+ * y = (A/bpm0)·(e^(−c·x) − 1). Exact as A → 0 (the plain form is 0/0
377
+ * there) and as c → 0. Used while 1 + y = bpm(x)·e^(−c·x)/bpm0 > 0.5.
378
+ * - plain form, when 1 + y ≤ 0.5 (steep concave ramps near their end, or
379
+ * convex descending ramps, where forming 1 + y loses digits). There the
380
+ * numerator −ln(1 + y) is at least ln 2 in magnitude, and A ≠ 0 (A = 0
381
+ * forces 1 + y = 1), so nothing cancels.
382
+ * Error is floating-point only (≈1e-15 relative), independent of segment
383
+ * length — the previous 64-step trapezoid drifted by up to ~2e-3 relative
384
+ * (2.8 ms per bar, 0.7 s over a 256-bar ramp at steep slopes).
189
385
  */
190
386
  private _ticksToSecondsCurve;
191
387
  /**
192
- * Inverse of _ticksToSecondsCurve: given seconds into a curved segment,
193
- * return ticks. Uses binary search since there's no closed-form inverse.
388
+ * Closed-form inverse of _ticksToSecondsCurve. Solving the log1p form for x:
389
+ * K = seconds·c·A/base
390
+ * z = e^(−c·x) − 1 = −(bpm0·seconds·c/base) · (1 − e^(−K))/K
391
+ * x = −log1p(z)/c
392
+ * (1 − e^(−K))/K → 1 as K → 0 makes A → 0 exact; c → 0 is exact because
393
+ * z ∝ c and log1p(z)/c keeps the ratio. When e^(−c·x) is small (z ≤ −0.5: a
394
+ * steep concave ramp near its end) and |B| < |A|/2, forming it as 1 + z
395
+ * loses digits; there the equal product form
396
+ * e^(−c·x) = (c·bpm0·e^(−K) − c·B)/(c·A) is used — its digit loss is
397
+ * |B|/|A| times the 1 + z form's, so the guard makes it the better choice by
398
+ * at least 2×. Returns fractional ticks; callers round at their unit boundary.
194
399
  */
195
400
  private _secondsToTicksCurve;
401
+ private _curveSegment;
196
402
  private _entryIndexAt;
197
- private _recomputeCache;
198
403
  }
199
404
 
200
405
  interface SchedulerOptions {
@@ -204,6 +409,12 @@ interface SchedulerOptions {
204
409
  * advance() so the Transport can compute the correct clock seek target
205
410
  * without re-reading the live AudioContext.currentTime. */
206
411
  onLoop?: (loopStartSeconds: number, loopEndSeconds: number, currentTimeSeconds: number) => void;
412
+ /** Called when a listener's generate(), consume() or onPositionJump()
413
+ * throws. The failing listener is skipped for that window (consume: that
414
+ * event; positionJump: that jump) and the remaining listeners/events still
415
+ * run. Without a handler the failure is reported with console.warn, once
416
+ * per listener and failure kind, so it is never silent. */
417
+ onError?: (error: SchedulerListenerError) => void;
207
418
  }
208
419
  declare class Scheduler<T extends SchedulerEvent> {
209
420
  private _lookahead;
@@ -214,11 +425,30 @@ declare class Scheduler<T extends SchedulerEvent> {
214
425
  private _loopEnd;
215
426
  private _playEnd;
216
427
  private _onLoop;
428
+ private _onError;
429
+ private readonly _errorLog;
217
430
  private _tempoMap;
431
+ /** The map an advance() in progress started with; null between calls. */
432
+ private _advancingWith;
218
433
  constructor(tempoMap: TempoMap, options?: SchedulerOptions);
434
+ /** Swap in a new (immutable) TempoMap. The scheduling cursor is re-anchored
435
+ * through seconds — the window already handed to listeners (in seconds)
436
+ * stays covered, so the next advance() neither regenerates it nor stalls
437
+ * until the clock catches up with the old edge's new tick value. If that
438
+ * puts the cursor at or past loopEnd (a faster tempo while looping) it is
439
+ * clamped to loopEnd and the next advance() wraps immediately. Loop bounds
440
+ * stay in ticks (they are musical positions); a seconds-defined play end
441
+ * is the Transport's to recompute. Called from inside advance() (a
442
+ * listener's generate()/consume() swapping the map directly) the swap is
443
+ * recorded and the re-anchor happens when that window completes — the
444
+ * window in progress keeps the TEMPO map it started with (loop bounds and
445
+ * the MeterMap are not snapshotted). Audio already scheduled in the
446
+ * lookahead keeps its old-tempo timing. */
447
+ setTempoMap(tempoMap: TempoMap): void;
219
448
  addListener(listener: SchedulerListener<T>): void;
220
449
  removeListener(listener: SchedulerListener<T>): void;
221
- /** Primary API — ticks as source of truth */
450
+ /** Primary API — ticks as source of truth. Throws on a non-finite or
451
+ * inverted/empty range when `enabled`; the previous loop stays in force. */
222
452
  setLoop(enabled: boolean, startTick: Tick, endTick: Tick): void;
223
453
  /** Convenience — converts seconds to ticks via TempoMap */
224
454
  setLoopSeconds(enabled: boolean, startSec: number, endSec: number): void;
@@ -228,21 +458,81 @@ declare class Scheduler<T extends SchedulerEvent> {
228
458
  * (nonexistent) bar. Null = unbounded. Set from Transport.play()'s endTime; the
229
459
  * loop path is unaffected (loopEnd already bounds it). */
230
460
  setPlayEnd(endTick: Tick | null): void;
231
- /** Reset scheduling cursor. Takes seconds (from Clock), converts to ticks. */
461
+ /** Reset scheduling cursor. Takes seconds (from Clock), converts to integer
462
+ * ticks — secondsToTicks rounds once here; the cursor is always whole ticks. */
232
463
  reset(timeSeconds: number): void;
233
464
  /** Advance the scheduling window. Takes seconds (from Clock), converts to ticks. */
234
465
  advance(currentTimeSeconds: number): void;
466
+ private _advanceWith;
467
+ /** Move the cursor from `previous`-map ticks to `next`-map ticks through
468
+ * seconds, clamped to loopEnd so a faster tempo cannot strand it past the
469
+ * loop (the next advance() then wraps). */
470
+ private _reanchorCursor;
235
471
  private _generateAndConsume;
472
+ private _reportError;
236
473
  }
237
474
 
475
+ /**
476
+ * Drives the scheduler at a fixed cadence.
477
+ *
478
+ * Primary source: a Web Worker running a setTimeout loop. Browsers stop
479
+ * requestAnimationFrame and throttle main-thread timers in a hidden tab, but
480
+ * Worker timers and message delivery keep their cadence, so the scheduler's
481
+ * lookahead window never runs dry while the tab is in the background (#636).
482
+ * One Worker lives from the first start() until dispose(); start/stop are
483
+ * messages, so a seek during playback costs no Worker spin-up.
484
+ *
485
+ * Fallback: a main-thread setTimeout loop, used when there is no Worker/Blob
486
+ * URL support (Node, SSR), when constructing the Worker throws (a CSP
487
+ * without `worker-src blob:`), when the Worker fires `error`/`messageerror`
488
+ * after construction, or when a started Worker never delivers its first tick
489
+ * within WATCHDOG_INTERVALS ticks (a Worker the browser killed without an
490
+ * event). Correct while the tab is visible or audible; a hidden, silent tab
491
+ * may throttle it to 1 Hz and, after several minutes, to once per minute —
492
+ * far beyond the 200 ms lookahead. Only a synchronous constructor refusal is
493
+ * remembered page-wide (it is an environment fact, warned once); a later
494
+ * Worker death is per Timer and is warned each time it happens.
495
+ *
496
+ * requestAnimationFrame is never used — it belongs to UI position updates.
497
+ */
498
+ /** Tick cadence. 25 ms gives 8× headroom under the scheduler's default
499
+ * 200 ms lookahead; a Worker message every 25 ms is negligible load. */
500
+ declare const DEFAULT_TIMER_INTERVAL_MS = 25;
501
+ interface TimerOptions {
502
+ /** Milliseconds between ticks. Default DEFAULT_TIMER_INTERVAL_MS. */
503
+ intervalMs?: number;
504
+ }
238
505
  declare class Timer {
239
- private _onTick;
240
- private _rafId;
506
+ private readonly _onTick;
507
+ private readonly _intervalMs;
241
508
  private _running;
242
- constructor(onTick: () => void);
509
+ private _disposed;
510
+ private _warnedDisposed;
511
+ private _worker;
512
+ private _workerUrl;
513
+ /** Set once the Worker path has been ruled out for this Timer. */
514
+ private _useTimeoutFallback;
515
+ private _timeoutId;
516
+ /** Armed when `start` is posted to the Worker; cleared by its first tick. */
517
+ private _watchdogId;
518
+ constructor(onTick: () => void, options?: TimerOptions);
243
519
  start(): void;
244
520
  stop(): void;
245
- private _scheduleFrame;
521
+ /** Stop and release the Worker. A disposed Timer cannot be restarted —
522
+ * start() becomes a warned no-op, so a late play() on a disposed transport
523
+ * cannot leak a fresh Worker. */
524
+ dispose(): void;
525
+ private _handleTick;
526
+ private _scheduleTimeout;
527
+ private _releaseWorker;
528
+ private _armWatchdog;
529
+ private _clearWatchdog;
530
+ /** The Worker path failed: release it and keep ticking on setTimeout. A
531
+ * constructor refusal is an environment fact remembered (and warned) once
532
+ * per page; a Worker that errored or went silent later is this Timer's
533
+ * own event and is warned every time. */
534
+ private _fallBackFromWorker;
535
+ private _ensureWorker;
246
536
  }
247
537
 
248
538
  declare class SampleTimeline {
@@ -254,7 +544,12 @@ declare class SampleTimeline {
254
544
  samplesToSeconds(samples: Sample): number;
255
545
  secondsToSamples(seconds: number): Sample;
256
546
  ticksToSamples(ticks: Tick): Sample;
547
+ /** Samples → integer ticks. The integer `Tick` contract belongs to THIS
548
+ * boundary: exactly one rounding, applied to the fractional position. */
257
549
  samplesToTicks(samples: Sample): Tick;
550
+ /** Samples → fractional tick position (unrounded), for sub-tick placement. */
551
+ samplesToTicksExact(samples: Sample): number;
552
+ private _requireTempoMap;
258
553
  }
259
554
 
260
555
  declare class MeterMap {
@@ -286,6 +581,45 @@ declare class MeterMap {
286
581
  private _validateMeter;
287
582
  }
288
583
 
584
+ /** Grid step for quantizeTick.
585
+ * - `{ ticks }`: an explicit tick count (positive integer) — a duration, not
586
+ * a position, hence the object form rather than a bare number.
587
+ * - `{ note, dotted?, triplet? }`: a note value by denominator (4 = quarter,
588
+ * 8 = eighth, 16 = sixteenth …), resolved against the MeterMap's PPQN;
589
+ * dotted ×3/2, triplet ×2/3.
590
+ * - `'bar'` / `'beat'`: the bar or beat length of the meter in force at the
591
+ * tick's bar. */
592
+ type GridSubdivision = {
593
+ readonly ticks: number;
594
+ } | {
595
+ readonly note: number;
596
+ readonly dotted?: boolean;
597
+ readonly triplet?: boolean;
598
+ } | 'bar' | 'beat';
599
+ /** 'nearest' (exact ties go up), 'next' (ceiling), 'previous' (floor). All
600
+ * three are idempotent: a tick already on a grid line stays put. This differs
601
+ * from Tone's `nextSubdivision`, which is strictly after the current time —
602
+ * for "the line after this one" pass `tick + 1` with 'next'. */
603
+ type QuantizeMode = 'nearest' | 'next' | 'previous';
604
+ interface QuantizeOptions {
605
+ /** Default 'nearest'. */
606
+ mode?: QuantizeMode;
607
+ /** 0–1, default 1: how far to move toward the chosen line (1 = onto it). */
608
+ strength?: number;
609
+ }
610
+ /**
611
+ * Snap a tick to a meter-aware grid. Pure: reads the MeterMap, mutates nothing.
612
+ *
613
+ * Grid lines restart at each bar line (the metronome re-anchors the same way
614
+ * at each meter entry), so odd meters stay aligned: in 7/8 a quarter-note grid
615
+ * is 0, 960, 1920, 2880 and then the next bar line at 3360 — never 3840. A
616
+ * subdivision longer than the bar leaves only the bar lines.
617
+ *
618
+ * `tick` may be fractional (e.g. `Transport.timeToTickExact()` of a recorded
619
+ * note); the result is always an integer Tick.
620
+ */
621
+ declare function quantizeTick(meterMap: MeterMap, tick: number, subdivision: GridSubdivision, options?: QuantizeOptions): Tick;
622
+
289
623
  declare class MasterNode {
290
624
  private _gainNode;
291
625
  private _destination;
@@ -357,6 +691,8 @@ declare class ClipPlayer implements SchedulerListener<ClipEvent> {
357
691
  private _loopEnabled;
358
692
  private _loopEndSamples;
359
693
  constructor(audioContext: AudioContext, sampleTimeline: SampleTimeline, tempoMap: TempoMap, toAudioTime: (transportTime: number) => number);
694
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
695
+ setTempoMap(tempoMap: TempoMap): void;
360
696
  setTracks(tracks: ClipTrack[], trackNodes: Map<string, TrackNode>): void;
361
697
  /** Set loop region using ticks. startTick is unused — loop clamping only needs
362
698
  * the end boundary; mid-clip restart at loopStart is handled by onPositionJump. */
@@ -386,6 +722,8 @@ declare class MetronomePlayer implements SchedulerListener<MetronomeEvent> {
386
722
  private _normalBuffer;
387
723
  private _activeSources;
388
724
  constructor(audioContext: AudioContext, tempoMap: TempoMap, meterMap: MeterMap, destination: AudioNode, toAudioTime: (transportTime: number) => number);
725
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
726
+ setTempoMap(tempoMap: TempoMap): void;
389
727
  setEnabled(enabled: boolean): void;
390
728
  setClickSounds(accent: AudioBuffer, normal: AudioBuffer): void;
391
729
  generate(fromTick: Tick, toTick: Tick): MetronomeEvent[];
@@ -420,6 +758,44 @@ interface TransportEvents {
420
758
  meterchange: (event: MeterChangeEventData) => void;
421
759
  countIn: (event: CountInEventData) => void;
422
760
  countInEnd: () => void;
761
+ /** A bounded play(start, end) reached `end` and the transport stopped
762
+ * itself. Fires right AFTER the `stop` event, so a handler sees a stopped
763
+ * transport and may restart it (loop-on-end); never for a consumer
764
+ * stop()/pause()/seek(). (NativePlayoutAdapter forwards this to the
765
+ * engine's onPlaybackEnded hook.) */
766
+ ended: () => void;
767
+ /** One scheduler tick advanced the timeline: fires every
768
+ * `timerIntervalMs` (default 25 ms) while playing, AFTER the scheduler
769
+ * consumed the tick, with `seconds` = what `getCurrentTime()` returns
770
+ * (loop-start clamp included, so a wrap reads as the position moving
771
+ * BACKWARDS — the transport emits no event for a wrap). Driven by the
772
+ * Worker timer, so it keeps its cadence in a hidden tab where
773
+ * requestAnimationFrame stops. Not emitted during a count-in (the position
774
+ * is held) nor on the tick that ends a bounded play (`stop`/`ended` fire
775
+ * instead). Meant for consumers that poll the playhead for state the
776
+ * transport does not announce (e.g. a tempo-map boundary crossed during
777
+ * playback); UI position updates should still use rAF. */
778
+ tick: (event: {
779
+ seconds: number;
780
+ }) => void;
781
+ /** The AudioContext's clock was read lower than before while playing (a
782
+ * defensive path — the spec makes `currentTime` monotonic). The position
783
+ * was held: `seconds` is what getCurrentTime() reports (the loop-start
784
+ * clamp and count-in hold included) and `shiftSeconds` how far the context
785
+ * clock went back. Outside a count-in every scheduled source was re-created
786
+ * from the held position; during one the clicks already armed (which would
787
+ * fire late by the shift) are dropped and the count-in continues.
788
+ * Diagnostics only — nothing for a consumer to do. With no subscriber the
789
+ * first occurrence is warned to the console instead. */
790
+ discontinuity: (event: {
791
+ seconds: number;
792
+ shiftSeconds: number;
793
+ }) => void;
794
+ /** A scheduler listener threw while generating or consuming events. The
795
+ * scheduler skipped it and kept going; the host decides what to do. With
796
+ * no `error` listener registered the failure is reported via console.warn
797
+ * instead, so it is never silent. */
798
+ error: (event: SchedulerListenerError) => void;
423
799
  }
424
800
  type TransportEventType = keyof TransportEvents;
425
801
  declare class Transport {
@@ -438,6 +814,11 @@ declare class Transport {
438
814
  private _soloedTrackIds;
439
815
  private _mutedTrackIds;
440
816
  private _playing;
817
+ private _disposed;
818
+ /** `Clock.rebaseCount` as of the last resync; a higher count means sources
819
+ * armed in the old time base are still scheduled. */
820
+ private _rebasesHandled;
821
+ private _warnedDiscontinuity;
441
822
  private _endTime;
442
823
  private _loopEnabled;
443
824
  private _loopStartTick;
@@ -455,15 +836,52 @@ declare class Transport {
455
836
  private _accentBuffer;
456
837
  private _normalBuffer;
457
838
  private _schedulerLookahead;
839
+ private readonly _errorLog;
458
840
  private _ppqn;
459
841
  constructor(audioContext: AudioContext, options?: TransportOptions);
842
+ /** One scheduling tick. Anything thrown here is a transport-internal
843
+ * fault (not a listener failure — those are caught by the scheduler); the
844
+ * wrapper above stops the transport rather than retrying it 40×/s. */
845
+ private _tick;
846
+ /** The clock absorbed a backward context re-base since the last resync:
847
+ * sources armed through the old anchor's toAudioTime() hold ABSOLUTE
848
+ * context times and would now fire late by the shift. Outside a count-in,
849
+ * re-create them from the held position (the seek-while-playing path minus
850
+ * the move), clamped to loopStart like getCurrentTime() — right after a
851
+ * wrap the clock sits behind loopStart and a resync from there would play
852
+ * pre-loop material. During a count-in the clicks already armed are
853
+ * dropped rather than regenerated (CountInPlayer counts beats, so a
854
+ * regenerate would double-fire); the count-in→play transition is
855
+ * clock-driven and still lands on the held clock. */
856
+ private _resyncAfterDiscontinuity;
857
+ /** Sources are (re)created from the current anchor here: any re-base
858
+ * absorbed before this point concerns audio that no longer exists. */
859
+ private _markRebasesHandled;
860
+ /** A tick threw: warn once and stop, so the engine sees a `stop` and no
861
+ * one is left looking at a "playing" transport that renders silence. */
862
+ private _onTickFailure;
460
863
  get audioContext(): AudioContext;
461
864
  get ppqn(): number;
865
+ /** The current tempo map. Immutable: every tempo edit swaps in a new map,
866
+ * so a reference you hold keeps converting with the tempo it had. */
867
+ get tempoMap(): TempoMap;
462
868
  play(startTime?: number, endTime?: number): void;
463
869
  pause(): void;
464
870
  stop(): void;
465
871
  seek(time: number): void;
466
872
  getCurrentTime(): number;
873
+ /** Current position in whole AudioContext frames (the clock's native unit
874
+ * for elapsed time). Same loop-wrap clamp and count-in hold as
875
+ * getCurrentTime(). CONTEXT-rate frames — `getCurrentSample()` is the
876
+ * timeline-rate view. */
877
+ getCurrentFrame(): ContextFrame;
878
+ /** Current position in SampleTimeline samples (the `sampleRate` option's
879
+ * rate; equal to getCurrentFrame() only when that matches the context).
880
+ * Rounded once, at the Sample boundary. */
881
+ getCurrentSample(): Sample;
882
+ /** How many backward AudioContext clock readings the transport has absorbed
883
+ * (see the `discontinuity` event). Diagnostics. */
884
+ get rebaseCount(): number;
467
885
  isPlaying(): boolean;
468
886
  setTracks(tracks: ClipTrack[]): void;
469
887
  addTrack(track: ClipTrack): void;
@@ -474,11 +892,15 @@ declare class Transport {
474
892
  setTrackMute(trackId: string, muted: boolean): void;
475
893
  setTrackSolo(trackId: string, soloed: boolean): void;
476
894
  setMasterVolume(volume: number): void;
477
- /** Primary loop API — ticks as source of truth */
895
+ /** Primary loop API — ticks as source of truth. Throws when `enabled` and
896
+ * the range is non-finite, empty or inverted; nothing is changed and no
897
+ * `loop` event fires. (NativePlayoutAdapter translates the engine's
898
+ * default empty region to a disabled loop before reaching here.) */
478
899
  setLoop(enabled: boolean, startTick: Tick, endTick: Tick): void;
479
- /** Convenience — converts seconds to ticks */
900
+ /** Convenience — converts seconds to ticks. Same validation as setLoop,
901
+ * applied in seconds so the error names the caller's unit. */
480
902
  setLoopSeconds(enabled: boolean, startSec: number, endSec: number): void;
481
- /** Convenience — sets loop in samples */
903
+ /** Convenience — sets loop in samples. Same validation as setLoop. */
482
904
  setLoopSamples(enabled: boolean, startSample: Sample, endSample: Sample): void;
483
905
  /** Returns true when the tempo was applied, false when a defaulted (no
484
906
  * atTick) write was refused because the tempo map has multiple entries —
@@ -496,11 +918,21 @@ declare class Transport {
496
918
  * the removed position. */
497
919
  removeTempo(atTick: Tick): void;
498
920
  barToTick(bar: number): Tick;
921
+ /** Snap a (possibly fractional) tick to the meter grid: `subdivision` is
922
+ * `{ ticks }`, `{ note, dotted?, triplet? }`, 'bar' or 'beat'; `mode` is
923
+ * 'nearest' (default) | 'next' | 'previous'; `strength` 0–1 scales the
924
+ * move. Grid lines restart at each bar line, so odd meters stay aligned.
925
+ * Pure function over the (live) MeterMap. */
926
+ quantizeTick(tick: number, subdivision: GridSubdivision, options?: QuantizeOptions): Tick;
499
927
  tickToBar(tick: Tick): number;
500
- /** Convert transport time (seconds) to tick position, using the tempo map. */
928
+ /** Convert transport time (seconds) to an integer tick position, using the tempo map. */
501
929
  timeToTick(seconds: number): Tick;
502
- /** Convert tick position to transport time (seconds), using the tempo map. */
503
- tickToTime(tick: Tick): number;
930
+ /** Convert transport time (seconds) to a fractional tick position — for
931
+ * sub-tick placement (e.g. a recorded note between ticks, before quantising). */
932
+ timeToTickExact(seconds: number): number;
933
+ /** Convert a tick position (integer Tick or the fractional value
934
+ * timeToTickExact returned) to transport time (seconds). */
935
+ tickToTime(tick: number): number;
504
936
  setMetronomeEnabled(enabled: boolean): void;
505
937
  setMetronomeClickSounds(accent: AudioBuffer, normal: AudioBuffer): void;
506
938
  static readonly MIN_COUNT_IN_BARS = 1;
@@ -535,14 +967,29 @@ declare class Transport {
535
967
  private _startCountIn;
536
968
  private _finishCountIn;
537
969
  private _cancelCountIn;
970
+ /** Install a new immutable TempoMap everywhere one is held. The count-in
971
+ * player is configured with its own dedicated map at each count-in start,
972
+ * so it is not on this list. */
973
+ private _replaceTempoMap;
974
+ /** A disposed transport has no timer or audio graph; a late play()/seek()
975
+ * must not report "playing" with nothing ticking. */
976
+ private _refuseIfDisposed;
538
977
  private _silenceAll;
539
978
  private _applyMuteState;
979
+ /** Route a scheduler listener failure to `error` subscribers, or to
980
+ * console.warn (once per listener and failure kind) when nobody is listening —
981
+ * the failure must stay visible either way. Subscribers are called on a
982
+ * microtask, after the scheduler window that produced the failure has
983
+ * completed: a handler that reacts with stop()/setTracks()/off() must not
984
+ * re-enter the listener iteration that is still running. */
985
+ private _emitError;
540
986
  private _emit;
541
987
  }
542
988
 
543
989
  declare class NativePlayoutAdapter implements PlayoutAdapter {
544
990
  private _transport;
545
991
  private _audioContext;
992
+ private _onPlaybackEnded;
546
993
  constructor(audioContext: AudioContext, options?: TransportOptions);
547
994
  get audioContext(): AudioContext;
548
995
  get ppqn(): number;
@@ -555,6 +1002,11 @@ declare class NativePlayoutAdapter implements PlayoutAdapter {
555
1002
  play(startTime: number, endTime?: number): void;
556
1003
  pause(): void;
557
1004
  stop(): void;
1005
+ /** Engine hook: adapter-initiated completion of a bounded play(start, end)
1006
+ * (the transport's `ended` event). Never fired for a consumer
1007
+ * stop()/pause()/seek()/dispose(), whether issued through this adapter or
1008
+ * directly on `adapter.transport`. */
1009
+ onPlaybackEnded(callback: (() => void) | null): void;
558
1010
  seek(time: number): void;
559
1011
  getCurrentTime(): number;
560
1012
  isPlaying(): boolean;
@@ -573,8 +1025,10 @@ declare class NativePlayoutAdapter implements PlayoutAdapter {
573
1025
  setMeter(numerator: number, denominator: number, atTick?: number): void;
574
1026
  ticksToSeconds(tick: number): number;
575
1027
  secondsToTicks(seconds: number): number;
1028
+ /** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
1029
+ secondsToTicksExact(seconds: number): number;
576
1030
  get masterOutputNode(): AudioNode;
577
1031
  dispose(): void;
578
1032
  }
579
1033
 
580
- export { type ClickSoundOptions, type ClipEvent, ClipPlayer, Clock, type CountInEvent, type CountInEventData, type CountInMode, MasterNode, type MeterChangeEventData, type MeterEntry, MeterMap, type MeterSignature, type MetronomeEvent, MetronomePlayer, NativePlayoutAdapter, type Sample, SampleTimeline, Scheduler, type SchedulerEvent, type SchedulerListener, type SchedulerOptions, type SetTempoOptions, type TempoChangeEventData, type TempoEntry, type TempoInterpolation, TempoMap, type Tick, Timer, TrackNode, Transport, type TransportEvents, type TransportOptions, type TransportPosition };
1034
+ export { type ClickSoundOptions, type ClipEvent, ClipPlayer, Clock, type ContextFrame, type CountInEvent, type CountInEventData, type CountInMode, DEFAULT_TIMER_INTERVAL_MS, type GridSubdivision, MasterNode, type MeterChangeEventData, type MeterEntry, MeterMap, type MeterSignature, type MetronomeEvent, MetronomePlayer, NativePlayoutAdapter, type QuantizeMode, type QuantizeOptions, RENDER_QUANTUM_FRAMES, type Sample, SampleTimeline, Scheduler, type SchedulerEvent, type SchedulerListener, type SchedulerListenerError, type SchedulerOptions, type SetTempoOptions, type TempoChangeEventData, type TempoEntry, type TempoInterpolation, TempoMap, type TempoMapInternalToken, type Tick, Timer, type TimerOptions, TrackNode, Transport, type TransportEvents, type TransportOptions, type TransportPosition, quantizeTick };