@dawcore/transport 0.0.13 → 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.js CHANGED
@@ -22,69 +22,230 @@ var index_exports = {};
22
22
  __export(index_exports, {
23
23
  ClipPlayer: () => ClipPlayer,
24
24
  Clock: () => Clock,
25
+ DEFAULT_TIMER_INTERVAL_MS: () => DEFAULT_TIMER_INTERVAL_MS,
25
26
  MasterNode: () => MasterNode,
26
27
  MeterMap: () => MeterMap,
27
28
  MetronomePlayer: () => MetronomePlayer,
28
29
  NativePlayoutAdapter: () => NativePlayoutAdapter,
30
+ RENDER_QUANTUM_FRAMES: () => RENDER_QUANTUM_FRAMES,
29
31
  SampleTimeline: () => SampleTimeline,
30
32
  Scheduler: () => Scheduler,
31
33
  TempoMap: () => TempoMap,
32
34
  Timer: () => Timer,
33
35
  TrackNode: () => TrackNode,
34
- Transport: () => Transport
36
+ Transport: () => Transport,
37
+ quantizeTick: () => quantizeTick
35
38
  });
36
39
  module.exports = __toCommonJS(index_exports);
37
40
 
38
41
  // src/core/clock.ts
42
+ var RENDER_QUANTUM_FRAMES = 128;
43
+ var LATTICE_SNAP_FRAMES = 1e-3;
39
44
  var Clock = class {
40
45
  constructor(audioContext) {
41
46
  this._running = false;
42
- this._audioTimeAtStart = 0;
43
- this._clockTimeAtStart = 0;
47
+ /** Snapped context frame when the current run was anchored. */
48
+ this._contextFrameAtAnchor = 0;
49
+ /** Position at the last seek, in frames (fractional after a seconds seek). */
50
+ this._seekFrames = 0;
51
+ /** The same position in seconds — bit-exactly what seekTo(seconds) got. */
52
+ this._seekSeconds = 0;
53
+ /** Whole frames elapsed in earlier runs since the last seek. */
54
+ this._elapsedBeforeAnchor = 0;
55
+ /** The PREVIOUS snapped context reading (not a high-water mark): a lower
56
+ * reading than this one, while running, is a re-base. */
57
+ this._lastContextFrame = -Infinity;
58
+ this._rebaseCount = 0;
59
+ this._lastRebaseFrames = 0;
60
+ const rate = audioContext.sampleRate;
61
+ if (!(Number.isFinite(rate) && rate > 0)) {
62
+ throw new Error(
63
+ "[waveform-playlist] Clock: audioContext.sampleRate must be a positive finite number, got " + rate
64
+ );
65
+ }
44
66
  this._audioContext = audioContext;
67
+ this._sampleRate = rate;
68
+ }
69
+ /** The rate frames are counted in: the AudioContext's. */
70
+ get sampleRate() {
71
+ return this._sampleRate;
72
+ }
73
+ /** How many backward context readings were absorbed while running. The
74
+ * Transport diffs this against its own cursor each tick to re-create
75
+ * sources armed in the old time base; observers may read it freely. */
76
+ get rebaseCount() {
77
+ return this._rebaseCount;
78
+ }
79
+ /** Size (frames) of the most recently absorbed backward reading. */
80
+ get lastRebaseFrames() {
81
+ return this._lastRebaseFrames;
82
+ }
83
+ /** Seconds → whole context frames, rounded once here. */
84
+ secondsToFrame(seconds) {
85
+ return Math.round(seconds * this._sampleRate);
86
+ }
87
+ /** Whole context frames → seconds (the inverse view). */
88
+ frameToSeconds(frame) {
89
+ return frame / this._sampleRate;
45
90
  }
46
91
  start() {
47
92
  if (this._running) return;
48
- this._audioTimeAtStart = this._audioContext.currentTime;
93
+ this._contextFrameAtAnchor = this._readContextFrame();
49
94
  this._running = true;
50
95
  }
51
96
  stop() {
52
97
  if (!this._running) return;
53
- this._clockTimeAtStart = this.getTime();
98
+ this._elapsedBeforeAnchor += this._elapsedFrames();
54
99
  this._running = false;
55
100
  }
56
101
  reset() {
57
102
  this._running = false;
58
- this._clockTimeAtStart = 0;
59
- this._audioTimeAtStart = 0;
103
+ this._seekFrames = 0;
104
+ this._seekSeconds = 0;
105
+ this._elapsedBeforeAnchor = 0;
106
+ this._contextFrameAtAnchor = 0;
60
107
  }
108
+ /** Position in seconds: the exact seek target plus whole elapsed frames. */
61
109
  getTime() {
62
- if (this._running) {
63
- return this._clockTimeAtStart + (this._audioContext.currentTime - this._audioTimeAtStart);
64
- }
65
- return this._clockTimeAtStart;
110
+ return this._seekSeconds + this._totalElapsedFrames() / this._sampleRate;
111
+ }
112
+ /** Position in whole context frames (rounded once, here). */
113
+ getFrame() {
114
+ return Math.round(this.getFrameExact());
115
+ }
116
+ /** Position in frames, keeping any sub-frame part a seconds seek introduced. */
117
+ getFrameExact() {
118
+ return this._seekFrames + this._totalElapsedFrames();
66
119
  }
67
120
  seekTo(time) {
68
- if (this._running) {
69
- this._clockTimeAtStart = time;
70
- this._audioTimeAtStart = this._audioContext.currentTime;
71
- } else {
72
- this._clockTimeAtStart = time;
73
- }
121
+ assertFinite("seekTo", time);
122
+ this._seekToPosition(time * this._sampleRate, time);
123
+ }
124
+ /** A fractional frame is rounded here, at the API boundary. */
125
+ seekToFrame(frame) {
126
+ assertFinite("seekToFrame", frame);
127
+ const whole = Math.round(frame);
128
+ this._seekToPosition(whole, whole / this._sampleRate);
74
129
  }
75
130
  /**
76
- * Convert transport time to AudioContext.currentTime space.
77
- * Used by players to schedule AudioBufferSourceNode.start(when).
131
+ * Convert transport time to AudioContext.currentTime space, for
132
+ * AudioBufferSourceNode.start(when). Anchor-based in both states: while
133
+ * running it never re-reads currentTime, so sub-quantum noise in a reading
134
+ * cannot shift scheduled events; stopped, the anchor is the same snapped
135
+ * "now" that start() is about to capture, so a `when` computed just before
136
+ * start() and one computed just after are identical.
78
137
  */
79
138
  toAudioTime(transportTime) {
80
- return this._audioContext.currentTime + (transportTime - this.getTime());
139
+ const positionFrames = transportTime * this._sampleRate;
140
+ const anchorFrame = this._running ? this._contextFrameAtAnchor : this._snappedContextFrame();
141
+ return (anchorFrame + (positionFrames - this._positionAtAnchorFrames())) / this._sampleRate;
81
142
  }
82
143
  isRunning() {
83
144
  return this._running;
84
145
  }
146
+ _seekToPosition(frames, seconds) {
147
+ this._seekFrames = frames;
148
+ this._seekSeconds = seconds;
149
+ this._elapsedBeforeAnchor = 0;
150
+ if (this._running) {
151
+ this._contextFrameAtAnchor = this._readContextFrame();
152
+ }
153
+ }
154
+ /** Position (frames) at the start of the current run. */
155
+ _positionAtAnchorFrames() {
156
+ return this._seekFrames + this._elapsedBeforeAnchor;
157
+ }
158
+ /** Whole frames elapsed since the last seek, across runs. */
159
+ _totalElapsedFrames() {
160
+ return this._elapsedBeforeAnchor + (this._running ? this._elapsedFrames() : 0);
161
+ }
162
+ /** Whole frames elapsed since the anchor (running only). */
163
+ _elapsedFrames() {
164
+ return this._readContextFrame() - this._contextFrameAtAnchor;
165
+ }
166
+ /** currentTime as an integer frame on the render-quantum lattice. Pure. */
167
+ _snappedContextFrame() {
168
+ const raw = this._audioContext.currentTime * this._sampleRate;
169
+ const onLattice = Math.round(raw / RENDER_QUANTUM_FRAMES) * RENDER_QUANTUM_FRAMES;
170
+ return Math.abs(raw - onLattice) < LATTICE_SNAP_FRAMES ? onLattice : Math.round(raw);
171
+ }
172
+ /** The snapped reading, with backward re-bases absorbed. Not pure: the
173
+ * first reader to see a backward reading shifts the anchor (idempotent —
174
+ * every later reader sees the already-held position). */
175
+ _readContextFrame() {
176
+ const frame = this._snappedContextFrame();
177
+ if (frame < this._lastContextFrame && this._running) {
178
+ const shift = this._lastContextFrame - frame;
179
+ this._contextFrameAtAnchor -= shift;
180
+ this._lastRebaseFrames = shift;
181
+ this._rebaseCount++;
182
+ }
183
+ this._lastContextFrame = frame;
184
+ return frame;
185
+ }
85
186
  };
187
+ function assertFinite(method, value) {
188
+ if (!Number.isFinite(value)) {
189
+ throw new Error(
190
+ "[waveform-playlist] Clock." + method + ": position must be finite, got " + value
191
+ );
192
+ }
193
+ }
194
+
195
+ // src/core/loop-range.ts
196
+ function assertValidLoopRange(source, enabled, start, end, unit) {
197
+ if (!enabled) return;
198
+ if (!Number.isFinite(start) || !Number.isFinite(end)) {
199
+ throw new Error(
200
+ "[waveform-playlist] " + source + ": non-finite " + unit + " values (" + start + ", " + end + ")"
201
+ );
202
+ }
203
+ if (unit === "tick" && (!Number.isInteger(start) || !Number.isInteger(end))) {
204
+ throw new Error(
205
+ "[waveform-playlist] " + source + ": ticks must be integers, got (" + start + ", " + end + ")"
206
+ );
207
+ }
208
+ if (start >= end) {
209
+ throw new Error(
210
+ "[waveform-playlist] " + source + ": start " + unit + " (" + start + ") must be less than end " + unit + " (" + end + ")"
211
+ );
212
+ }
213
+ }
214
+ function assertLoopRangeSpansATick(source, enabled, start, end, unit, startTick, endTick) {
215
+ if (!enabled || startTick < endTick) return;
216
+ throw new Error(
217
+ "[waveform-playlist] " + source + ": range (" + start + ", " + end + " " + unit + ") is shorter than one tick (both round to tick " + startTick + ")"
218
+ );
219
+ }
86
220
 
87
221
  // src/core/scheduler.ts
222
+ function formatSchedulerListenerError(error) {
223
+ const where = error.phase === "consume" ? " at tick " + error.event.tick : error.phase === "generate" ? " for ticks [" + error.fromTick + ", " + error.toTick + ")" : " jumping to tick " + error.tick;
224
+ return "scheduler listener threw during " + error.phase + "()" + where + ": " + describeError(error.error);
225
+ }
226
+ function describeError(error) {
227
+ return error instanceof Error ? error.name + ": " + error.message : String(error);
228
+ }
229
+ var MAX_LOGGED_KINDS_PER_LISTENER = 16;
230
+ var ListenerErrorLog = class {
231
+ constructor(_prefix) {
232
+ this._prefix = _prefix;
233
+ this._seen = /* @__PURE__ */ new WeakMap();
234
+ }
235
+ warnOnce(error) {
236
+ let kinds = this._seen.get(error.listener);
237
+ if (!kinds) {
238
+ kinds = /* @__PURE__ */ new Set();
239
+ this._seen.set(error.listener, kinds);
240
+ }
241
+ const kind = error.phase + "|" + describeError(error.error);
242
+ if (kinds.has(kind) || kinds.size >= MAX_LOGGED_KINDS_PER_LISTENER) return;
243
+ kinds.add(kind);
244
+ console.warn(
245
+ this._prefix + formatSchedulerListenerError(error) + ' (further failures of this kind are not logged; subscribe to the "error" event to handle them)'
246
+ );
247
+ }
248
+ };
88
249
  var Scheduler = class {
89
250
  constructor(tempoMap, options = {}) {
90
251
  this._rightEdge = 0;
@@ -94,9 +255,34 @@ var Scheduler = class {
94
255
  this._loopStart = 0;
95
256
  // integer ticks
96
257
  this._loopEnd = 0;
258
+ // integer ticks
259
+ this._playEnd = null;
260
+ this._errorLog = new ListenerErrorLog("[waveform-playlist] Scheduler: ");
261
+ /** The map an advance() in progress started with; null between calls. */
262
+ this._advancingWith = null;
97
263
  this._tempoMap = tempoMap;
98
264
  this._lookahead = options.lookahead ?? 0.2;
99
265
  this._onLoop = options.onLoop;
266
+ this._onError = options.onError;
267
+ }
268
+ /** Swap in a new (immutable) TempoMap. The scheduling cursor is re-anchored
269
+ * through seconds — the window already handed to listeners (in seconds)
270
+ * stays covered, so the next advance() neither regenerates it nor stalls
271
+ * until the clock catches up with the old edge's new tick value. If that
272
+ * puts the cursor at or past loopEnd (a faster tempo while looping) it is
273
+ * clamped to loopEnd and the next advance() wraps immediately. Loop bounds
274
+ * stay in ticks (they are musical positions); a seconds-defined play end
275
+ * is the Transport's to recompute. Called from inside advance() (a
276
+ * listener's generate()/consume() swapping the map directly) the swap is
277
+ * recorded and the re-anchor happens when that window completes — the
278
+ * window in progress keeps the TEMPO map it started with (loop bounds and
279
+ * the MeterMap are not snapshotted). Audio already scheduled in the
280
+ * lookahead keeps its old-tempo timing. */
281
+ setTempoMap(tempoMap) {
282
+ if (this._advancingWith === null) {
283
+ this._reanchorCursor(this._tempoMap, tempoMap);
284
+ }
285
+ this._tempoMap = tempoMap;
100
286
  }
101
287
  addListener(listener) {
102
288
  this._listeners.add(listener);
@@ -104,116 +290,296 @@ var Scheduler = class {
104
290
  removeListener(listener) {
105
291
  this._listeners.delete(listener);
106
292
  }
107
- /** Primary API — ticks as source of truth */
293
+ /** Primary API — ticks as source of truth. Throws on a non-finite or
294
+ * inverted/empty range when `enabled`; the previous loop stays in force. */
108
295
  setLoop(enabled, startTick, endTick) {
109
- if (enabled && (!Number.isFinite(startTick) || !Number.isFinite(endTick))) {
110
- console.warn(
111
- "[waveform-playlist] Scheduler.setLoop: non-finite tick values (" + startTick + ", " + endTick + ")"
112
- );
113
- return;
114
- }
115
- if (enabled && startTick >= endTick) {
116
- console.warn(
117
- "[waveform-playlist] Scheduler.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
118
- );
119
- return;
120
- }
296
+ assertValidLoopRange("Scheduler.setLoop", enabled, startTick, endTick, "tick");
121
297
  this._loopEnabled = enabled;
122
298
  this._loopStart = Math.round(startTick);
123
299
  this._loopEnd = Math.round(endTick);
124
300
  }
125
301
  /** Convenience — converts seconds to ticks via TempoMap */
126
302
  setLoopSeconds(enabled, startSec, endSec) {
303
+ assertValidLoopRange("Scheduler.setLoopSeconds", enabled, startSec, endSec, "second");
127
304
  const startTick = this._tempoMap.secondsToTicks(startSec);
128
305
  const endTick = this._tempoMap.secondsToTicks(endSec);
306
+ assertLoopRangeSpansATick(
307
+ "Scheduler.setLoopSeconds",
308
+ enabled,
309
+ startSec,
310
+ endSec,
311
+ "second",
312
+ startTick,
313
+ endTick
314
+ );
129
315
  this.setLoop(enabled, startTick, endTick);
130
316
  }
131
- /** Reset scheduling cursor. Takes seconds (from Clock), converts to ticks. */
317
+ /** Hard end bound (ticks) for non-loop playback: the lookahead window never
318
+ * generates events at or beyond this tick, so audio (metronome clicks, clips)
319
+ * can't be scheduled past the playback end and sound a beat into the next
320
+ * (nonexistent) bar. Null = unbounded. Set from Transport.play()'s endTime; the
321
+ * loop path is unaffected (loopEnd already bounds it). */
322
+ setPlayEnd(endTick) {
323
+ this._playEnd = endTick == null ? null : Math.round(endTick);
324
+ }
325
+ /** Reset scheduling cursor. Takes seconds (from Clock), converts to integer
326
+ * ticks — secondsToTicks rounds once here; the cursor is always whole ticks. */
132
327
  reset(timeSeconds) {
133
328
  this._rightEdge = this._tempoMap.secondsToTicks(timeSeconds);
134
329
  }
135
330
  /** Advance the scheduling window. Takes seconds (from Clock), converts to ticks. */
136
331
  advance(currentTimeSeconds) {
137
- const targetTick = this._tempoMap.secondsToTicks(currentTimeSeconds + this._lookahead);
332
+ const tempoMap = this._tempoMap;
333
+ this._advancingWith = tempoMap;
334
+ try {
335
+ this._advanceWith(tempoMap, currentTimeSeconds);
336
+ } finally {
337
+ this._advancingWith = null;
338
+ if (this._tempoMap !== tempoMap) {
339
+ this._reanchorCursor(tempoMap, this._tempoMap);
340
+ }
341
+ }
342
+ }
343
+ _advanceWith(tempoMap, currentTimeSeconds) {
344
+ const targetTick = tempoMap.secondsToTicks(currentTimeSeconds + this._lookahead);
138
345
  if (this._loopEnabled && this._loopEnd > this._loopStart) {
139
- const loopDuration = this._loopEnd - this._loopStart;
140
346
  let remaining = targetTick - this._rightEdge;
141
347
  while (remaining > 0) {
142
348
  const distToEnd = this._loopEnd - this._rightEdge;
143
- if (distToEnd <= 0 || distToEnd > remaining) {
349
+ if (distToEnd > remaining) {
144
350
  this._generateAndConsume(this._rightEdge, this._rightEdge + remaining);
145
351
  this._rightEdge += remaining;
146
352
  break;
147
353
  }
148
- this._generateAndConsume(this._rightEdge, this._loopEnd);
149
- remaining -= distToEnd;
354
+ if (distToEnd > 0) {
355
+ this._generateAndConsume(this._rightEdge, this._loopEnd);
356
+ remaining -= distToEnd;
357
+ }
150
358
  for (const listener of this._listeners) {
151
- listener.onPositionJump(this._loopStart);
359
+ try {
360
+ listener.onPositionJump(this._loopStart);
361
+ } catch (err) {
362
+ this._reportError({
363
+ phase: "positionJump",
364
+ listener,
365
+ tick: this._loopStart,
366
+ error: err
367
+ });
368
+ }
152
369
  }
153
370
  this._onLoop?.(
154
- this._tempoMap.ticksToSeconds(this._loopStart),
155
- this._tempoMap.ticksToSeconds(this._loopEnd),
371
+ tempoMap.ticksToSeconds(this._loopStart),
372
+ tempoMap.ticksToSeconds(this._loopEnd),
156
373
  currentTimeSeconds
157
374
  );
158
375
  this._rightEdge = this._loopStart;
159
- if (loopDuration <= 0) break;
160
376
  }
161
377
  return;
162
378
  }
163
- if (targetTick > this._rightEdge) {
164
- this._generateAndConsume(this._rightEdge, targetTick);
165
- this._rightEdge = targetTick;
379
+ const bound = this._playEnd !== null && targetTick > this._playEnd ? this._playEnd : targetTick;
380
+ if (bound > this._rightEdge) {
381
+ this._generateAndConsume(this._rightEdge, bound);
382
+ this._rightEdge = bound;
166
383
  }
167
384
  }
385
+ /** Move the cursor from `previous`-map ticks to `next`-map ticks through
386
+ * seconds, clamped to loopEnd so a faster tempo cannot strand it past the
387
+ * loop (the next advance() then wraps). */
388
+ _reanchorCursor(previous, next) {
389
+ if (previous === next) return;
390
+ const edgeSeconds = previous.ticksToSeconds(this._rightEdge);
391
+ let edge = next.secondsToTicks(edgeSeconds);
392
+ if (this._loopEnabled && this._loopEnd > this._loopStart && edge > this._loopEnd) {
393
+ edge = this._loopEnd;
394
+ }
395
+ this._rightEdge = edge;
396
+ }
168
397
  _generateAndConsume(fromTick, toTick) {
169
398
  for (const listener of this._listeners) {
399
+ let events;
170
400
  try {
171
- const events = listener.generate(fromTick, toTick);
172
- for (const event of events) {
173
- try {
174
- listener.consume(event);
175
- } catch (err) {
176
- console.warn("[waveform-playlist] Scheduler: error consuming event:", String(err));
177
- }
178
- }
401
+ events = listener.generate(fromTick, toTick);
179
402
  } catch (err) {
180
- console.warn("[waveform-playlist] Scheduler: error generating events:", String(err));
403
+ this._reportError({
404
+ phase: "generate",
405
+ listener,
406
+ fromTick,
407
+ toTick,
408
+ error: err
409
+ });
410
+ continue;
181
411
  }
412
+ for (const event of events) {
413
+ try {
414
+ listener.consume(event);
415
+ } catch (err) {
416
+ this._reportError({ phase: "consume", listener, event, error: err });
417
+ }
418
+ }
419
+ }
420
+ }
421
+ _reportError(error) {
422
+ if (this._onError) {
423
+ this._onError(error);
424
+ return;
182
425
  }
426
+ this._errorLog.warnOnce(error);
183
427
  }
184
428
  };
185
429
 
186
430
  // src/core/timer.ts
431
+ var DEFAULT_TIMER_INTERVAL_MS = 25;
432
+ var TIMER_WORKER_SCRIPT = "var timeoutId = null;\nvar intervalMs = " + DEFAULT_TIMER_INTERVAL_MS + ";\nfunction tick() {\n timeoutId = setTimeout(tick, intervalMs);\n postMessage('tick');\n}\nonmessage = function (event) {\n var message = event.data;\n if (timeoutId !== null) { clearTimeout(timeoutId); timeoutId = null; }\n if (message && message.type === 'start') {\n intervalMs = message.intervalMs;\n timeoutId = setTimeout(tick, intervalMs);\n }\n};\n";
433
+ var WATCHDOG_INTERVALS = 4;
434
+ var workerRefusedOnThisPage = false;
435
+ function describeWorkerError(event) {
436
+ const e = event;
437
+ const where = e.filename ? " at " + e.filename + ":" + (e.lineno ?? "?") : "";
438
+ return "worker " + (e.type ?? "error") + ": " + (e.message ?? String(event)) + where;
439
+ }
440
+ function hasWorkerPlatform() {
441
+ return typeof Worker !== "undefined" && typeof Blob !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function";
442
+ }
187
443
  var Timer = class {
188
- constructor(onTick) {
189
- this._rafId = null;
444
+ constructor(onTick, options = {}) {
190
445
  this._running = false;
446
+ this._disposed = false;
447
+ this._warnedDisposed = false;
448
+ this._worker = null;
449
+ this._workerUrl = null;
450
+ /** Set once the Worker path has been ruled out for this Timer. */
451
+ this._useTimeoutFallback = false;
452
+ this._timeoutId = null;
453
+ /** Armed when `start` is posted to the Worker; cleared by its first tick. */
454
+ this._watchdogId = null;
455
+ const intervalMs = options.intervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
456
+ if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
457
+ throw new Error(
458
+ "[waveform-playlist] Timer: intervalMs must be a positive number, got " + intervalMs
459
+ );
460
+ }
191
461
  this._onTick = onTick;
462
+ this._intervalMs = intervalMs;
192
463
  }
193
464
  start() {
465
+ if (this._disposed) {
466
+ if (!this._warnedDisposed) {
467
+ this._warnedDisposed = true;
468
+ console.warn("[waveform-playlist] Timer: start() on a disposed Timer is ignored");
469
+ }
470
+ return;
471
+ }
194
472
  if (this._running) return;
195
473
  this._running = true;
196
- this._scheduleFrame();
474
+ const worker = this._ensureWorker();
475
+ if (worker) {
476
+ worker.postMessage({ type: "start", intervalMs: this._intervalMs });
477
+ this._armWatchdog();
478
+ } else if (this._timeoutId === null) {
479
+ this._scheduleTimeout();
480
+ }
197
481
  }
198
482
  stop() {
483
+ if (!this._running) return;
199
484
  this._running = false;
200
- if (this._rafId !== null) {
201
- cancelAnimationFrame(this._rafId);
202
- this._rafId = null;
485
+ this._clearWatchdog();
486
+ if (this._worker) {
487
+ this._worker.postMessage({ type: "stop" });
488
+ }
489
+ if (this._timeoutId !== null) {
490
+ clearTimeout(this._timeoutId);
491
+ this._timeoutId = null;
203
492
  }
204
493
  }
205
- _scheduleFrame() {
206
- this._rafId = requestAnimationFrame(() => {
207
- if (!this._running) return;
208
- try {
209
- this._onTick();
210
- } catch (err) {
211
- console.warn("[waveform-playlist] Timer tick error:", String(err));
212
- }
213
- if (this._running) {
214
- this._scheduleFrame();
215
- }
216
- });
494
+ /** Stop and release the Worker. A disposed Timer cannot be restarted —
495
+ * start() becomes a warned no-op, so a late play() on a disposed transport
496
+ * cannot leak a fresh Worker. */
497
+ dispose() {
498
+ this.stop();
499
+ this._disposed = true;
500
+ this._releaseWorker();
501
+ }
502
+ _handleTick() {
503
+ if (!this._running) return;
504
+ this._clearWatchdog();
505
+ try {
506
+ this._onTick();
507
+ } catch (err) {
508
+ console.warn("[waveform-playlist] Timer tick error: " + String(err));
509
+ }
510
+ }
511
+ _scheduleTimeout() {
512
+ this._timeoutId = setTimeout(() => {
513
+ this._timeoutId = null;
514
+ this._handleTick();
515
+ if (this._running && this._timeoutId === null) this._scheduleTimeout();
516
+ }, this._intervalMs);
517
+ }
518
+ _releaseWorker() {
519
+ if (this._worker) {
520
+ this._worker.onmessage = null;
521
+ this._worker.onerror = null;
522
+ this._worker.onmessageerror = null;
523
+ this._worker.terminate();
524
+ this._worker = null;
525
+ }
526
+ if (this._workerUrl !== null) {
527
+ URL.revokeObjectURL(this._workerUrl);
528
+ this._workerUrl = null;
529
+ }
530
+ }
531
+ _armWatchdog() {
532
+ this._clearWatchdog();
533
+ this._watchdogId = setTimeout(() => {
534
+ this._watchdogId = null;
535
+ this._fallBackFromWorker(
536
+ "no tick received within " + WATCHDOG_INTERVALS * this._intervalMs + " ms of start",
537
+ false
538
+ );
539
+ }, WATCHDOG_INTERVALS * this._intervalMs);
540
+ }
541
+ _clearWatchdog() {
542
+ if (this._watchdogId !== null) {
543
+ clearTimeout(this._watchdogId);
544
+ this._watchdogId = null;
545
+ }
546
+ }
547
+ /** The Worker path failed: release it and keep ticking on setTimeout. A
548
+ * constructor refusal is an environment fact remembered (and warned) once
549
+ * per page; a Worker that errored or went silent later is this Timer's
550
+ * own event and is warned every time. */
551
+ _fallBackFromWorker(reason, constructorRefused) {
552
+ this._useTimeoutFallback = true;
553
+ this._clearWatchdog();
554
+ this._releaseWorker();
555
+ const silenced = constructorRefused && workerRefusedOnThisPage;
556
+ if (constructorRefused) workerRefusedOnThisPage = true;
557
+ if (!silenced) {
558
+ console.warn(
559
+ "[waveform-playlist] Timer: could not run a Worker ticker (" + reason + "); falling back to a main-thread setTimeout loop, which browsers throttle in a hidden tab"
560
+ );
561
+ }
562
+ if (this._running && this._timeoutId === null) this._scheduleTimeout();
563
+ }
564
+ _ensureWorker() {
565
+ if (this._worker) return this._worker;
566
+ if (this._useTimeoutFallback || workerRefusedOnThisPage || !hasWorkerPlatform()) {
567
+ this._useTimeoutFallback = true;
568
+ return null;
569
+ }
570
+ try {
571
+ const url = URL.createObjectURL(new Blob([TIMER_WORKER_SCRIPT], { type: "text/javascript" }));
572
+ const worker = new Worker(url);
573
+ worker.onmessage = () => this._handleTick();
574
+ worker.onerror = (event) => this._fallBackFromWorker(describeWorkerError(event), false);
575
+ worker.onmessageerror = () => this._fallBackFromWorker("worker message error", false);
576
+ this._worker = worker;
577
+ this._workerUrl = url;
578
+ return worker;
579
+ } catch (err) {
580
+ this._fallBackFromWorker(String(err), true);
581
+ return null;
582
+ }
217
583
  }
218
584
  };
219
585
 
@@ -236,36 +602,100 @@ var SampleTimeline = class {
236
602
  return Math.round(seconds * this._sampleRate);
237
603
  }
238
604
  ticksToSamples(ticks) {
239
- if (!this._tempoMap) {
240
- throw new Error(
241
- "[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
242
- );
243
- }
244
- return Math.round(this._tempoMap.ticksToSeconds(ticks) * this._sampleRate);
605
+ return Math.round(this._requireTempoMap().ticksToSeconds(ticks) * this._sampleRate);
245
606
  }
607
+ /** Samples → integer ticks. The integer `Tick` contract belongs to THIS
608
+ * boundary: exactly one rounding, applied to the fractional position. */
246
609
  samplesToTicks(samples) {
610
+ return Math.round(this.samplesToTicksExact(samples));
611
+ }
612
+ /** Samples → fractional tick position (unrounded), for sub-tick placement. */
613
+ samplesToTicksExact(samples) {
614
+ return this._requireTempoMap().secondsToTicksExact(samples / this._sampleRate);
615
+ }
616
+ _requireTempoMap() {
247
617
  if (!this._tempoMap) {
248
618
  throw new Error(
249
619
  "[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
250
620
  );
251
621
  }
252
- return Math.round(this._tempoMap.secondsToTicks(samples / this._sampleRate));
622
+ return this._tempoMap;
253
623
  }
254
624
  };
255
625
 
256
626
  // src/timeline/tempo-map.ts
257
627
  var CURVE_EPSILON = 1e-15;
258
- var CURVE_SUBDIVISIONS = 64;
259
- function curveNormalizedAt(x, slope) {
260
- if (slope > 0.499999 && slope < 0.500001) return x;
628
+ var CURVE_LINEAR_SLOPE_EPSILON = 1e-12;
629
+ function isNearLinearSlope(slope) {
630
+ return Math.abs(slope - 0.5) < CURVE_LINEAR_SLOPE_EPSILON;
631
+ }
632
+ function curveCoefficients(slope) {
261
633
  const p = Math.max(CURVE_EPSILON, Math.min(1 - CURVE_EPSILON, slope));
262
- return p * p / (1 - p * 2) * (Math.pow((1 - p) / p, 2 * x) - 1);
634
+ const d = 1 - 2 * p;
635
+ const c = 2 * Math.log1p(d / p);
636
+ return { c, cB: c * p * p / d };
637
+ }
638
+ function log1pOverY(y) {
639
+ return y === 0 ? 1 : Math.log1p(y) / y;
640
+ }
641
+ function expm1NegOverK(k) {
642
+ return k === 0 ? 1 : -Math.expm1(-k) / k;
643
+ }
644
+ function curveNormalizedAt(x, slope) {
645
+ if (isNearLinearSlope(slope)) return x;
646
+ const { c, cB } = curveCoefficients(slope);
647
+ return cB / c * Math.expm1(c * x);
648
+ }
649
+ function assertFiniteInput(what, value) {
650
+ if (!Number.isFinite(value)) {
651
+ throw new Error("[waveform-playlist] TempoMap: " + what + " must be finite, got " + value);
652
+ }
653
+ }
654
+ function assertFiniteResult(input, value) {
655
+ if (!Number.isFinite(value)) {
656
+ throw new Error(
657
+ "[waveform-playlist] TempoMap: " + input + " is outside the domain of the tempo map (result not finite)"
658
+ );
659
+ }
660
+ return value;
661
+ }
662
+ var INTERNAL = /* @__PURE__ */ Symbol("TempoMap.internal");
663
+ function freezeInterpolation(interpolation) {
664
+ return typeof interpolation === "object" ? Object.freeze({ type: "curve", slope: interpolation.slope }) : interpolation;
665
+ }
666
+ function sealEntries(entries) {
667
+ return Object.freeze(
668
+ entries.map(
669
+ (e) => Object.isFrozen(e) && Object.isFrozen(e.interpolation) ? e : Object.freeze({ ...e, interpolation: freezeInterpolation(e.interpolation) })
670
+ )
671
+ );
672
+ }
673
+ function validateTick(what, tick) {
674
+ if (!Number.isFinite(tick) || tick < 0 || !Number.isInteger(tick)) {
675
+ throw new Error(
676
+ "[waveform-playlist] TempoMap: " + what + " tick must be a non-negative integer, got " + tick
677
+ );
678
+ }
263
679
  }
264
680
  var TempoMap = class _TempoMap {
265
- constructor(ppqn = 960, initialBpm = 120) {
266
- _TempoMap._validateBpm(initialBpm);
681
+ constructor(ppqn = 960, init = 120, token) {
682
+ if (!Number.isInteger(ppqn) || ppqn <= 0) {
683
+ throw new Error("[waveform-playlist] TempoMap: ppqn must be a positive integer, got " + ppqn);
684
+ }
267
685
  this._ppqn = ppqn;
268
- this._entries = [{ tick: 0, bpm: initialBpm, interpolation: "step", secondsAtTick: 0 }];
686
+ if (typeof init === "number") {
687
+ _TempoMap._validateBpm(init);
688
+ this._entries = sealEntries([
689
+ { tick: 0, bpm: init, interpolation: "step", secondsAtTick: 0 }
690
+ ]);
691
+ } else {
692
+ if (token !== INTERNAL) {
693
+ throw new Error(
694
+ "[waveform-playlist] TempoMap: the entries constructor is internal \u2014 use new TempoMap(ppqn, bpm) and withTempo()"
695
+ );
696
+ }
697
+ this._entries = init;
698
+ }
269
699
  }
270
700
  /** A non-finite or non-positive BPM silently corrupts the secondsAtTick
271
701
  * cache (Infinity, or non-monotonic values that break the binary search
@@ -285,37 +715,110 @@ var TempoMap = class _TempoMap {
285
715
  get entryCount() {
286
716
  return this._entries.length;
287
717
  }
288
- setTempo(bpm, atTick = 0, options) {
718
+ /** The entries, in tick order, frozen. `secondsAtTick` is the cumulative
719
+ * seconds up to each entry. */
720
+ get entries() {
721
+ return this._entries;
722
+ }
723
+ /** Return a new map with `bpm` at `atTick` (replacing an existing entry
724
+ * there). Tick 0 is always 'step'. Throws on an invalid BPM, curve slope
725
+ * or atTick (non-negative integer); this map is never modified. */
726
+ withTempo(bpm, atTick = 0, options) {
289
727
  _TempoMap._validateBpm(bpm);
290
- const interpolation = options?.interpolation ?? "step";
291
- if (typeof interpolation === "object" && interpolation.type === "curve") {
292
- const s = interpolation.slope;
728
+ validateTick("atTick", atTick);
729
+ const requested = options?.interpolation ?? "step";
730
+ if (typeof requested === "object" && requested.type === "curve") {
731
+ const s = requested.slope;
293
732
  if (!Number.isFinite(s) || s <= 0 || s >= 1) {
294
733
  throw new Error(
295
734
  "[waveform-playlist] TempoMap: curve slope must be between 0 and 1 (exclusive), got " + s
296
735
  );
297
736
  }
298
737
  }
738
+ const interpolation = freezeInterpolation(requested);
739
+ const entries = [...this._entries];
299
740
  if (atTick === 0) {
300
- this._entries[0] = { ...this._entries[0], bpm, interpolation: "step" };
301
- this._recomputeCache(0);
302
- return;
741
+ entries[0] = { ...entries[0], bpm, interpolation: "step" };
742
+ return this._derive(entries, 0);
303
743
  }
304
- let i = this._entries.length - 1;
305
- while (i > 0 && this._entries[i].tick > atTick) i--;
306
- if (this._entries[i].tick === atTick) {
307
- this._entries[i] = { ...this._entries[i], bpm, interpolation };
744
+ let i = this._entryIndexAt(atTick);
745
+ if (entries[i].tick === atTick) {
746
+ entries[i] = { ...entries[i], bpm, interpolation };
308
747
  } else {
309
- const secondsAtTick = this._ticksToSecondsInternal(atTick);
310
- this._entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick });
748
+ entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick: 0 });
311
749
  i = i + 1;
312
750
  }
313
- this._recomputeCache(i);
751
+ return this._derive(entries, i);
752
+ }
753
+ /** Return a new map without the entry at exactly `atTick`. The tick-0 entry
754
+ * is permanent (a map must always have a tempo), and a tick with no entry
755
+ * is a no-op — both return this same map. An invalid tick throws. */
756
+ withoutTempo(atTick) {
757
+ validateTick("atTick", atTick);
758
+ if (atTick === 0) return this;
759
+ const i = this._entries.findIndex((e) => e.tick === atTick);
760
+ if (i === -1) return this;
761
+ return this._derive([...this._entries.slice(0, i), ...this._entries.slice(i + 1)], i);
762
+ }
763
+ /** Return a new single-entry map keeping only the tick-0 tempo. */
764
+ withoutTempos() {
765
+ return new _TempoMap(this._ppqn, this._entries[0].bpm);
766
+ }
767
+ /** Build the successor map: recompute cumulative seconds from `fromIndex`
768
+ * into a fresh, sealed entry list. Entries before `fromIndex` are the
769
+ * previous map's frozen objects, reused by reference. Nothing on `this`
770
+ * is written. */
771
+ _derive(entries, fromIndex) {
772
+ for (let i = Math.max(1, fromIndex); i < entries.length; i++) {
773
+ const prev = entries[i - 1];
774
+ entries[i] = {
775
+ ...entries[i],
776
+ secondsAtTick: prev.secondsAtTick + this._segmentSeconds(prev, entries[i])
777
+ };
778
+ }
779
+ return new _TempoMap(this._ppqn, sealEntries(entries), INTERNAL);
780
+ }
781
+ /** Seconds spanned from `prev` to `entry` under `entry`'s interpolation. */
782
+ _segmentSeconds(prev, entry) {
783
+ const tickDelta = entry.tick - prev.tick;
784
+ if (entry.interpolation === "linear") {
785
+ return this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
786
+ }
787
+ if (typeof entry.interpolation === "object") {
788
+ return this._ticksToSecondsCurve(
789
+ tickDelta,
790
+ prev.bpm,
791
+ entry.bpm,
792
+ tickDelta,
793
+ entry.interpolation.slope
794
+ );
795
+ }
796
+ return tickDelta * (60 / (prev.bpm * this._ppqn));
314
797
  }
798
+ /** Tick position → seconds. Accepts a fractional position (e.g. the value
799
+ * secondsToTicksExact returned) as well as an integer Tick. */
315
800
  ticksToSeconds(ticks) {
316
- return this._ticksToSecondsInternal(ticks);
801
+ assertFiniteInput("ticks", ticks);
802
+ return assertFiniteResult("ticks " + ticks, this._ticksToSecondsInternal(ticks));
317
803
  }
804
+ /** Seconds → integer ticks, rounded once here at the `Tick` boundary.
805
+ * Use secondsToTicksExact() for sub-tick placement. */
318
806
  secondsToTicks(seconds) {
807
+ return Math.round(this.secondsToTicksExact(seconds));
808
+ }
809
+ /** Seconds → fractional tick position (unrounded). The integer producers
810
+ * round this once at their own boundary (secondsToTicks,
811
+ * SampleTimeline.samplesToTicks); sub-tick consumers (placing a recorded
812
+ * note between ticks before quantising, continuous beat positions) use it
813
+ * directly. Not clamped: negative seconds convert at the constant initial
814
+ * tempo to negative ticks (whatever the first segment's interpolation),
815
+ * and seconds past the last entry extrapolate the last tempo forwards. */
816
+ secondsToTicksExact(seconds) {
817
+ assertFiniteInput("seconds", seconds);
818
+ return assertFiniteResult("seconds " + seconds, this._secondsToTicksRaw(seconds));
819
+ }
820
+ _secondsToTicksRaw(seconds) {
821
+ if (seconds < 0) return seconds * this._entries[0].bpm * this._ppqn / 60;
319
822
  let lo = 0;
320
823
  let hi = this._entries.length - 1;
321
824
  while (lo < hi) {
@@ -330,50 +833,31 @@ var TempoMap = class _TempoMap {
330
833
  const secondsIntoSegment = seconds - entry.secondsAtTick;
331
834
  const nextEntry = lo < this._entries.length - 1 ? this._entries[lo + 1] : null;
332
835
  if (nextEntry && nextEntry.interpolation === "linear") {
333
- return Math.round(
334
- entry.tick + this._secondsToTicksLinear(
335
- secondsIntoSegment,
336
- entry.bpm,
337
- nextEntry.bpm,
338
- nextEntry.tick - entry.tick
339
- )
836
+ return entry.tick + this._secondsToTicksLinear(
837
+ secondsIntoSegment,
838
+ entry.bpm,
839
+ nextEntry.bpm,
840
+ nextEntry.tick - entry.tick
340
841
  );
341
842
  }
342
843
  if (nextEntry && typeof nextEntry.interpolation === "object") {
343
- return Math.round(
344
- entry.tick + this._secondsToTicksCurve(
345
- secondsIntoSegment,
346
- entry.bpm,
347
- nextEntry.bpm,
348
- nextEntry.tick - entry.tick,
349
- nextEntry.interpolation.slope
350
- )
844
+ return entry.tick + this._secondsToTicksCurve(
845
+ secondsIntoSegment,
846
+ entry.bpm,
847
+ nextEntry.bpm,
848
+ nextEntry.tick - entry.tick,
849
+ nextEntry.interpolation.slope
351
850
  );
352
851
  }
353
852
  const ticksPerSecond = entry.bpm / 60 * this._ppqn;
354
- return Math.round(entry.tick + secondsIntoSegment * ticksPerSecond);
853
+ return entry.tick + secondsIntoSegment * ticksPerSecond;
355
854
  }
356
855
  beatsToSeconds(beats) {
357
856
  return this.ticksToSeconds(beats * this._ppqn);
358
857
  }
858
+ /** Continuous beat position (fractional) — not quantised to whole ticks. */
359
859
  secondsToBeats(seconds) {
360
- return this.secondsToTicks(seconds) / this._ppqn;
361
- }
362
- clearTempos() {
363
- const first = this._entries[0];
364
- this._entries = [{ tick: 0, bpm: first.bpm, interpolation: "step", secondsAtTick: 0 }];
365
- }
366
- /** Remove the tempo entry at exactly `atTick`, if one exists. The tick-0
367
- * entry is permanent (a map must always have a tempo) — removing it is a
368
- * no-op, matching removeMeter's treatment of the initial meter. The
369
- * seconds cache is recomputed from the removal point, the same partial
370
- * update setTempo uses. */
371
- removeTempo(atTick) {
372
- if (atTick === 0) return;
373
- const i = this._entries.findIndex((e) => e.tick === atTick);
374
- if (i === -1) return;
375
- this._entries = [...this._entries.slice(0, i), ...this._entries.slice(i + 1)];
376
- this._recomputeCache(i);
860
+ return this.secondsToTicksExact(seconds) / this._ppqn;
377
861
  }
378
862
  /** Get the interpolated BPM at a tick position */
379
863
  _getTempoAt(atTick) {
@@ -395,6 +879,7 @@ var TempoMap = class _TempoMap {
395
879
  return entry.bpm;
396
880
  }
397
881
  _ticksToSecondsInternal(ticks) {
882
+ if (ticks < 0) return ticks * 60 / (this._entries[0].bpm * this._ppqn);
398
883
  const entryIndex = this._entryIndexAt(ticks);
399
884
  const entry = this._entries[entryIndex];
400
885
  const ticksIntoSegment = ticks - entry.tick;
@@ -435,10 +920,9 @@ var TempoMap = class _TempoMap {
435
920
  * Closed-form via exponential: bpmAtTick = bpm0 * exp(seconds * deltaBpm * ppqn / (60 * T))
436
921
  * then ticks = (bpmAtTick - bpm0) * T / deltaBpm
437
922
  *
438
- * Note: exp(log(x)) has ~1 ULP floating-point error, so round-trips depend on
439
- * Math.round() in the caller (secondsToTicks). This is sufficient for all tested
440
- * BPM ranges (10–300 BPM) but is not algebraically exact like the previous
441
- * trapezoidal/quadratic approach was.
923
+ * Note: exp(log(x)) has ~1 ULP floating-point error, so integer round-trips
924
+ * rely on the rounding in secondsToTicks; secondsToTicksExact returns the
925
+ * raw value. Sufficient for all tested BPM ranges (10–300 BPM).
442
926
  */
443
927
  _secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks) {
444
928
  if (totalSegmentTicks === 0 || seconds === 0) return 0;
@@ -450,43 +934,71 @@ var TempoMap = class _TempoMap {
450
934
  return (bpmAtTick - bpm0) / deltaBpm * totalSegmentTicks;
451
935
  }
452
936
  /**
453
- * Subdivided trapezoidal integration for a Möbius-Ease tempo curve.
454
- * The BPM at progress p is: bpm0 + curveNormalizedAt(p, slope) * (bpm1 - bpm0).
455
- * We subdivide into CURVE_SUBDIVISIONS intervals and apply trapezoidal rule.
937
+ * Exact integration for a Möbius-Ease tempo curve.
938
+ * With x = ticks / T the BPM is bpm0 + Δ·(p²/(1 − 2p))·(e^(c·x) − 1), i.e.
939
+ * A + B·e^(c·x) for B = Δ·p²/(1 − 2p), A = bpm0 − B. Its reciprocal has the
940
+ * antiderivative u/A − ln(A + B·e^(c·u))/(c·A), so
941
+ * seconds = base · (c·x − ln(bpm(x)/bpm0)) / (c·A), base = T·60/ppqn.
942
+ * Everything is carried as c·A and c·B so the slope → 0.5 limit (B → ∞,
943
+ * c → 0) stays finite. Two algebraically equal forms are used, chosen per
944
+ * call so neither one cancels:
945
+ * - log1p form: base · (1 − e^(−c·x))/(c·bpm0) · log1p(y)/y with
946
+ * y = (A/bpm0)·(e^(−c·x) − 1). Exact as A → 0 (the plain form is 0/0
947
+ * there) and as c → 0. Used while 1 + y = bpm(x)·e^(−c·x)/bpm0 > 0.5.
948
+ * - plain form, when 1 + y ≤ 0.5 (steep concave ramps near their end, or
949
+ * convex descending ramps, where forming 1 + y loses digits). There the
950
+ * numerator −ln(1 + y) is at least ln 2 in magnitude, and A ≠ 0 (A = 0
951
+ * forces 1 + y = 1), so nothing cancels.
952
+ * Error is floating-point only (≈1e-15 relative), independent of segment
953
+ * length — the previous 64-step trapezoid drifted by up to ~2e-3 relative
954
+ * (2.8 ms per bar, 0.7 s over a 256-bar ramp at steep slopes).
456
955
  */
457
956
  _ticksToSecondsCurve(ticks, bpm0, bpm1, totalSegmentTicks, slope) {
458
957
  if (totalSegmentTicks === 0 || ticks === 0) return 0;
459
- const n = CURVE_SUBDIVISIONS;
460
- const dt = ticks / n;
461
- let seconds = 0;
462
- let prevBpm = bpm0;
463
- for (let i = 1; i <= n; i++) {
464
- const progress = dt * i / totalSegmentTicks;
465
- const curBpm = bpm0 + curveNormalizedAt(progress, slope) * (bpm1 - bpm0);
466
- seconds += dt * 60 / this._ppqn * (1 / prevBpm + 1 / curBpm) / 2;
467
- prevBpm = curBpm;
468
- }
469
- return seconds;
958
+ if (isNearLinearSlope(slope)) {
959
+ return this._ticksToSecondsLinear(ticks, bpm0, bpm1, totalSegmentTicks);
960
+ }
961
+ const { c, cB, cA, base } = this._curveSegment(bpm0, bpm1, totalSegmentTicks, slope);
962
+ const x = ticks / totalSegmentTicks;
963
+ const expm1NegCx = Math.expm1(-c * x);
964
+ const y = cA / (c * bpm0) * expm1NegCx;
965
+ if (1 + y > 0.5) {
966
+ return base * (-expm1NegCx / (c * bpm0)) * log1pOverY(y);
967
+ }
968
+ const logRatio = Math.log1p(cB / (c * bpm0) * Math.expm1(c * x));
969
+ return base * (c * x - logRatio) / cA;
470
970
  }
471
971
  /**
472
- * Inverse of _ticksToSecondsCurve: given seconds into a curved segment,
473
- * return ticks. Uses binary search since there's no closed-form inverse.
972
+ * Closed-form inverse of _ticksToSecondsCurve. Solving the log1p form for x:
973
+ * K = seconds·c·A/base
974
+ * z = e^(−c·x) − 1 = −(bpm0·seconds·c/base) · (1 − e^(−K))/K
975
+ * x = −log1p(z)/c
976
+ * (1 − e^(−K))/K → 1 as K → 0 makes A → 0 exact; c → 0 is exact because
977
+ * z ∝ c and log1p(z)/c keeps the ratio. When e^(−c·x) is small (z ≤ −0.5: a
978
+ * steep concave ramp near its end) and |B| < |A|/2, forming it as 1 + z
979
+ * loses digits; there the equal product form
980
+ * e^(−c·x) = (c·bpm0·e^(−K) − c·B)/(c·A) is used — its digit loss is
981
+ * |B|/|A| times the 1 + z form's, so the guard makes it the better choice by
982
+ * at least 2×. Returns fractional ticks; callers round at their unit boundary.
474
983
  */
475
984
  _secondsToTicksCurve(seconds, bpm0, bpm1, totalSegmentTicks, slope) {
476
985
  if (totalSegmentTicks === 0 || seconds === 0) return 0;
477
- const iterations = Math.min(40, Math.max(1, Math.ceil(Math.log2(2 * totalSegmentTicks))));
478
- let lo = 0;
479
- let hi = totalSegmentTicks;
480
- for (let i = 0; i < iterations; i++) {
481
- const mid = (lo + hi) / 2;
482
- const midSeconds = this._ticksToSecondsCurve(mid, bpm0, bpm1, totalSegmentTicks, slope);
483
- if (midSeconds < seconds) {
484
- lo = mid;
485
- } else {
486
- hi = mid;
487
- }
986
+ if (isNearLinearSlope(slope)) {
987
+ return this._secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks);
988
+ }
989
+ const { c, cB, cA, base } = this._curveSegment(bpm0, bpm1, totalSegmentTicks, slope);
990
+ const k = seconds * cA / base;
991
+ const z = -(bpm0 * seconds * c / base) * expm1NegOverK(k);
992
+ if (z > -0.5 || Math.abs(cB) >= 0.5 * Math.abs(cA)) {
993
+ return -Math.log1p(z) / c * totalSegmentTicks;
488
994
  }
489
- return (lo + hi) / 2;
995
+ const expNegCx = (c * bpm0 * Math.exp(-k) - cB) / cA;
996
+ return -Math.log(expNegCx) / c * totalSegmentTicks;
997
+ }
998
+ _curveSegment(bpm0, bpm1, totalSegmentTicks, slope) {
999
+ const { c, cB: cBNormalized } = curveCoefficients(slope);
1000
+ const cB = cBNormalized * (bpm1 - bpm0);
1001
+ return { c, cB, cA: c * bpm0 - cB, base: totalSegmentTicks * 60 / this._ppqn };
490
1002
  }
491
1003
  _entryIndexAt(tick) {
492
1004
  let lo = 0;
@@ -501,32 +1013,6 @@ var TempoMap = class _TempoMap {
501
1013
  }
502
1014
  return lo;
503
1015
  }
504
- _recomputeCache(fromIndex) {
505
- for (let i = Math.max(1, fromIndex); i < this._entries.length; i++) {
506
- const prev = this._entries[i - 1];
507
- const tickDelta = this._entries[i].tick - prev.tick;
508
- const entry = this._entries[i];
509
- let segmentSeconds;
510
- if (entry.interpolation === "linear") {
511
- segmentSeconds = this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
512
- } else if (typeof entry.interpolation === "object") {
513
- segmentSeconds = this._ticksToSecondsCurve(
514
- tickDelta,
515
- prev.bpm,
516
- entry.bpm,
517
- tickDelta,
518
- entry.interpolation.slope
519
- );
520
- } else {
521
- const secondsPerTick = 60 / (prev.bpm * this._ppqn);
522
- segmentSeconds = tickDelta * secondsPerTick;
523
- }
524
- this._entries[i] = {
525
- ...entry,
526
- secondsAtTick: prev.secondsAtTick + segmentSeconds
527
- };
528
- }
529
- }
530
1016
  };
531
1017
 
532
1018
  // src/timeline/meter-map.ts
@@ -582,6 +1068,7 @@ var MeterMap = class {
582
1068
  const idx = this._entries.findIndex((e) => e.tick === atTick);
583
1069
  if (idx > 0) {
584
1070
  this._entries.splice(idx, 1);
1071
+ this._resnapDownstreamEntries(idx - 1);
585
1072
  this._recomputeCache(idx);
586
1073
  } else if (idx === -1) {
587
1074
  console.warn("[waveform-playlist] MeterMap.removeMeter: no entry at tick " + atTick);
@@ -708,6 +1195,80 @@ var MeterMap = class {
708
1195
  }
709
1196
  };
710
1197
 
1198
+ // src/timeline/quantize.ts
1199
+ var MODES = ["nearest", "next", "previous"];
1200
+ var ON_LINE_EPSILON = 1e-6;
1201
+ function quantizeTick(meterMap, tick, subdivision, options = {}) {
1202
+ const mode = options.mode ?? "nearest";
1203
+ const strength = options.strength ?? 1;
1204
+ validateQuantizeInput(tick, subdivision, mode, strength);
1205
+ const entry = meterMap.getEntryAt(tick);
1206
+ const ticksPerBar = meterMap.ticksPerBar(entry.tick);
1207
+ const barStart = entry.tick + Math.floor((tick - entry.tick) / ticksPerBar) * ticksPerBar;
1208
+ const nextBarStart = barStart + ticksPerBar;
1209
+ const step = resolveStep(meterMap, subdivision, ticksPerBar, meterMap.ticksPerBeat(entry.tick));
1210
+ const previous = barStart + Math.floor((tick - barStart) / step) * step;
1211
+ const candidateNext = Math.min(previous + step, nextBarStart);
1212
+ const onLine = Math.abs(tick - previous) < ON_LINE_EPSILON || Math.abs(tick - candidateNext) < ON_LINE_EPSILON;
1213
+ if (onLine) {
1214
+ const line = Math.abs(tick - previous) < ON_LINE_EPSILON ? previous : candidateNext;
1215
+ return Math.round(tick + (line - tick) * strength);
1216
+ }
1217
+ const target = pickLine(mode, tick, previous, candidateNext);
1218
+ return Math.round(tick + (target - tick) * strength);
1219
+ }
1220
+ function resolveStep(meterMap, subdivision, ticksPerBar, ticksPerBeat) {
1221
+ if (subdivision === "bar") return ticksPerBar;
1222
+ if (subdivision === "beat") return ticksPerBeat;
1223
+ if ("ticks" in subdivision) return subdivision.ticks;
1224
+ let step = meterMap.ppqn * 4 / subdivision.note;
1225
+ if (subdivision.dotted) step = step * 3 / 2;
1226
+ if (subdivision.triplet) step = step * 2 / 3;
1227
+ return step;
1228
+ }
1229
+ var NOTE_VALUES = [1, 2, 4, 8, 16, 32, 64];
1230
+ function isValidSubdivision(subdivision) {
1231
+ if (subdivision === "bar" || subdivision === "beat") return true;
1232
+ if (typeof subdivision !== "object" || subdivision === null) return false;
1233
+ if ("ticks" in subdivision) {
1234
+ return Number.isInteger(subdivision.ticks) && subdivision.ticks > 0;
1235
+ }
1236
+ return "note" in subdivision && NOTE_VALUES.includes(subdivision.note);
1237
+ }
1238
+ function describeSubdivision(subdivision) {
1239
+ if (typeof subdivision === "object" && subdivision !== null) {
1240
+ return JSON.stringify(subdivision);
1241
+ }
1242
+ return String(subdivision);
1243
+ }
1244
+ function pickLine(mode, tick, previous, next) {
1245
+ if (mode === "previous") return previous;
1246
+ if (mode === "next") return next;
1247
+ return tick - previous < next - tick ? previous : next;
1248
+ }
1249
+ function validateQuantizeInput(tick, subdivision, mode, strength) {
1250
+ if (!Number.isFinite(tick) || tick < 0) {
1251
+ throw new Error(
1252
+ "[waveform-playlist] quantizeTick: tick must be a finite number >= 0, got " + tick
1253
+ );
1254
+ }
1255
+ if (!isValidSubdivision(subdivision)) {
1256
+ throw new Error(
1257
+ "[waveform-playlist] quantizeTick: subdivision must be { ticks: positive integer }, { note: 1 | 2 | 4 | 8 | 16 | 32 | 64, dotted?, triplet? }, 'bar' or 'beat', got " + describeSubdivision(subdivision)
1258
+ );
1259
+ }
1260
+ if (!MODES.includes(mode)) {
1261
+ throw new Error(
1262
+ "[waveform-playlist] quantizeTick: mode must be 'nearest', 'next' or 'previous', got " + String(mode)
1263
+ );
1264
+ }
1265
+ if (!Number.isFinite(strength) || strength < 0 || strength > 1) {
1266
+ throw new Error(
1267
+ "[waveform-playlist] quantizeTick: strength must be between 0 and 1, got " + strength
1268
+ );
1269
+ }
1270
+ }
1271
+
711
1272
  // src/audio/master-node.ts
712
1273
  var MasterNode = class {
713
1274
  constructor(audioContext) {
@@ -839,6 +1400,10 @@ var ClipPlayer = class {
839
1400
  this._tempoMap = tempoMap;
840
1401
  this._toAudioTime = toAudioTime;
841
1402
  }
1403
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
1404
+ setTempoMap(tempoMap) {
1405
+ this._tempoMap = tempoMap;
1406
+ }
842
1407
  setTracks(tracks, trackNodes) {
843
1408
  this._tracks.clear();
844
1409
  this._trackNodes = trackNodes;
@@ -1052,6 +1617,10 @@ var MetronomePlayer = class {
1052
1617
  this._destination = destination;
1053
1618
  this._toAudioTime = toAudioTime;
1054
1619
  }
1620
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
1621
+ setTempoMap(tempoMap) {
1622
+ this._tempoMap = tempoMap;
1623
+ }
1055
1624
  setEnabled(enabled) {
1056
1625
  this._enabled = enabled;
1057
1626
  if (!enabled) {
@@ -1207,12 +1776,9 @@ var CountInPlayer = class {
1207
1776
  });
1208
1777
  const transportTime = this._tempoMap.ticksToSeconds(event.tick);
1209
1778
  source.start(this._toAudioTime(transportTime));
1210
- } catch (err) {
1211
- console.warn(
1212
- "[waveform-playlist] CountInPlayer.consume: failed to schedule beat " + event.beat + "/" + event.totalBeats + ": " + String(err)
1213
- );
1779
+ } finally {
1780
+ this._onBeat?.(event.beat, event.totalBeats);
1214
1781
  }
1215
- this._onBeat?.(event.beat, event.totalBeats);
1216
1782
  }
1217
1783
  onPositionJump(_newTick) {
1218
1784
  }
@@ -1278,6 +1844,11 @@ var _Transport = class _Transport {
1278
1844
  this._soloedTrackIds = /* @__PURE__ */ new Set();
1279
1845
  this._mutedTrackIds = /* @__PURE__ */ new Set();
1280
1846
  this._playing = false;
1847
+ this._disposed = false;
1848
+ /** `Clock.rebaseCount` as of the last resync; a higher count means sources
1849
+ * armed in the old time base are still scheduled. */
1850
+ this._rebasesHandled = 0;
1851
+ this._warnedDiscontinuity = false;
1281
1852
  this._loopEnabled = false;
1282
1853
  this._loopStartTick = 0;
1283
1854
  this._loopStartSeconds = 0;
@@ -1296,17 +1867,32 @@ var _Transport = class _Transport {
1296
1867
  this._accentBuffer = null;
1297
1868
  this._normalBuffer = null;
1298
1869
  this._schedulerLookahead = 0.2;
1870
+ this._errorLog = new ListenerErrorLog("[waveform-playlist] Transport: ");
1299
1871
  this._ppqn = 960;
1300
1872
  this._audioContext = audioContext;
1873
+ if (!(Number.isFinite(audioContext.sampleRate) && audioContext.sampleRate > 0)) {
1874
+ throw new Error(
1875
+ "[waveform-playlist] Transport: the AudioContext must report a positive finite sampleRate, got " + audioContext.sampleRate
1876
+ );
1877
+ }
1301
1878
  const sampleRate = options.sampleRate ?? audioContext.sampleRate;
1302
1879
  const ppqn = options.ppqn ?? 960;
1303
1880
  const tempo = options.tempo ?? 120;
1304
1881
  const numerator = options.numerator ?? 4;
1305
1882
  const denominator = options.denominator ?? 4;
1306
1883
  const lookahead = options.schedulerLookahead ?? 0.2;
1884
+ const timerIntervalMs = options.timerIntervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
1307
1885
  this._ppqn = ppqn;
1308
1886
  this._schedulerLookahead = lookahead;
1309
- _Transport._validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead);
1887
+ _Transport._validateOptions(
1888
+ sampleRate,
1889
+ ppqn,
1890
+ tempo,
1891
+ numerator,
1892
+ denominator,
1893
+ lookahead,
1894
+ timerIntervalMs
1895
+ );
1310
1896
  this._clock = new Clock(audioContext);
1311
1897
  this._sampleTimeline = new SampleTimeline(sampleRate);
1312
1898
  this._meterMap = new MeterMap(ppqn, numerator, denominator);
@@ -1316,13 +1902,33 @@ var _Transport = class _Transport {
1316
1902
  onLoop: (loopStartSeconds, loopEndSeconds, currentTimeSeconds) => {
1317
1903
  const timeToBoundary = loopEndSeconds - currentTimeSeconds;
1318
1904
  this._clock.seekTo(loopStartSeconds - timeToBoundary);
1319
- }
1905
+ },
1906
+ onError: (error) => this._emitError(error)
1320
1907
  });
1321
1908
  this._sampleTimeline.setTempoMap(this._tempoMap);
1322
1909
  this._initAudioGraph(audioContext);
1323
1910
  this._initCountIn(audioContext, options);
1324
- this._timer = new Timer(() => {
1911
+ this._timer = new Timer(
1912
+ () => {
1913
+ try {
1914
+ this._tick();
1915
+ } catch (err) {
1916
+ this._onTickFailure(err);
1917
+ }
1918
+ },
1919
+ { intervalMs: timerIntervalMs }
1920
+ );
1921
+ }
1922
+ /** One scheduling tick. Anything thrown here is a transport-internal
1923
+ * fault (not a listener failure — those are caught by the scheduler); the
1924
+ * wrapper above stops the transport rather than retrying it 40×/s. */
1925
+ _tick() {
1926
+ {
1325
1927
  const time = this._clock.getTime();
1928
+ if (this._clock.rebaseCount !== this._rebasesHandled) {
1929
+ this._rebasesHandled = this._clock.rebaseCount;
1930
+ this._resyncAfterDiscontinuity(time);
1931
+ }
1326
1932
  if (this._countingIn) {
1327
1933
  this._countInScheduler?.advance(time);
1328
1934
  if (time >= this._countInDuration) {
@@ -1332,10 +1938,65 @@ var _Transport = class _Transport {
1332
1938
  }
1333
1939
  if (this._endTime !== void 0 && time >= this._endTime) {
1334
1940
  this.stop();
1941
+ this._emit("ended");
1335
1942
  return;
1336
1943
  }
1337
1944
  this._scheduler.advance(time);
1338
- });
1945
+ this._emit("tick", { seconds: this.getCurrentTime() });
1946
+ }
1947
+ }
1948
+ /** The clock absorbed a backward context re-base since the last resync:
1949
+ * sources armed through the old anchor's toAudioTime() hold ABSOLUTE
1950
+ * context times and would now fire late by the shift. Outside a count-in,
1951
+ * re-create them from the held position (the seek-while-playing path minus
1952
+ * the move), clamped to loopStart like getCurrentTime() — right after a
1953
+ * wrap the clock sits behind loopStart and a resync from there would play
1954
+ * pre-loop material. During a count-in the clicks already armed are
1955
+ * dropped rather than regenerated (CountInPlayer counts beats, so a
1956
+ * regenerate would double-fire); the count-in→play transition is
1957
+ * clock-driven and still lands on the held clock. */
1958
+ _resyncAfterDiscontinuity(time) {
1959
+ const shiftSeconds = this._clock.frameToSeconds(this._clock.lastRebaseFrames);
1960
+ let seconds;
1961
+ if (this._countingIn) {
1962
+ this._countInPlayer.silence();
1963
+ seconds = this._countInStartPosition;
1964
+ } else {
1965
+ seconds = this._loopEnabled && time < this._loopStartSeconds ? this._loopStartSeconds : time;
1966
+ this._silenceAll();
1967
+ this._scheduler.reset(seconds);
1968
+ this._clipPlayer.onPositionJump(this._tempoMap.secondsToTicks(seconds));
1969
+ }
1970
+ const listeners = this._listeners.get("discontinuity");
1971
+ if (listeners && listeners.size > 0) {
1972
+ this._emit("discontinuity", { seconds, shiftSeconds });
1973
+ } else if (!this._warnedDiscontinuity) {
1974
+ this._warnedDiscontinuity = true;
1975
+ console.warn(
1976
+ "[waveform-playlist] Transport: discontinuity \u2014 the AudioContext clock went backwards by " + shiftSeconds + " s while playing (re-base #" + this._clock.rebaseCount + "); position held at " + seconds + ' s and scheduled audio re-created. Subscribe to the "discontinuity" event for further occurrences.'
1977
+ );
1978
+ }
1979
+ }
1980
+ /** Sources are (re)created from the current anchor here: any re-base
1981
+ * absorbed before this point concerns audio that no longer exists. */
1982
+ _markRebasesHandled() {
1983
+ this._rebasesHandled = this._clock.rebaseCount;
1984
+ }
1985
+ /** A tick threw: warn once and stop, so the engine sees a `stop` and no
1986
+ * one is left looking at a "playing" transport that renders silence. */
1987
+ _onTickFailure(err) {
1988
+ console.warn(
1989
+ "[waveform-playlist] Transport: stopping \u2014 the scheduling tick threw: " + (err instanceof Error ? err.name + ": " + err.message + (err.stack ? "\n" + err.stack : "") : String(err))
1990
+ );
1991
+ try {
1992
+ this.stop();
1993
+ } catch (stopErr) {
1994
+ console.warn(
1995
+ "[waveform-playlist] Transport: stop() after a tick failure also threw: " + String(stopErr)
1996
+ );
1997
+ this._timer.stop();
1998
+ this._playing = false;
1999
+ }
1339
2000
  }
1340
2001
  get audioContext() {
1341
2002
  return this._audioContext;
@@ -1343,8 +2004,16 @@ var _Transport = class _Transport {
1343
2004
  get ppqn() {
1344
2005
  return this._ppqn;
1345
2006
  }
2007
+ /** The current tempo map. Immutable: every tempo edit swaps in a new map,
2008
+ * so a reference you hold keeps converting with the tempo it had. */
2009
+ get tempoMap() {
2010
+ return this._tempoMap;
2011
+ }
1346
2012
  // --- Playback ---
1347
2013
  play(startTime, endTime) {
2014
+ if (this._refuseIfDisposed("play")) return;
2015
+ if (startTime !== void 0) assertFiniteSeconds("play", "startTime", startTime);
2016
+ if (endTime !== void 0) assertFiniteSeconds("play", "endTime", endTime);
1348
2017
  if (this._playing) return;
1349
2018
  if (startTime !== void 0) {
1350
2019
  this._clock.seekTo(startTime);
@@ -1356,6 +2025,10 @@ var _Transport = class _Transport {
1356
2025
  const currentTime = this._clock.getTime();
1357
2026
  this._scheduler.reset(currentTime);
1358
2027
  this._endTime = endTime;
2028
+ this._scheduler.setPlayEnd(
2029
+ endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
2030
+ );
2031
+ this._markRebasesHandled();
1359
2032
  this._clock.start();
1360
2033
  const currentTick = this._tempoMap.secondsToTicks(currentTime);
1361
2034
  this._clipPlayer.onPositionJump(currentTick);
@@ -1389,11 +2062,14 @@ var _Transport = class _Transport {
1389
2062
  this._silenceAll();
1390
2063
  this._playing = false;
1391
2064
  this._endTime = void 0;
2065
+ this._scheduler.setPlayEnd(null);
1392
2066
  if (wasPlaying) {
1393
2067
  this._emit("stop");
1394
2068
  }
1395
2069
  }
1396
2070
  seek(time) {
2071
+ if (this._refuseIfDisposed("seek")) return;
2072
+ assertFiniteSeconds("seek", "time", time);
1397
2073
  const wasPlaying = this._playing;
1398
2074
  const wasCountingIn = this._countingIn;
1399
2075
  if (wasCountingIn) {
@@ -1405,8 +2081,10 @@ var _Transport = class _Transport {
1405
2081
  }
1406
2082
  this._silenceAll();
1407
2083
  this._clock.seekTo(time);
2084
+ this._markRebasesHandled();
1408
2085
  this._scheduler.reset(time);
1409
2086
  this._endTime = void 0;
2087
+ this._scheduler.setPlayEnd(null);
1410
2088
  if (wasPlaying && !wasCountingIn) {
1411
2089
  this._clock.start();
1412
2090
  const seekTick = this._tempoMap.secondsToTicks(time);
@@ -1425,6 +2103,32 @@ var _Transport = class _Transport {
1425
2103
  }
1426
2104
  return t;
1427
2105
  }
2106
+ /** Current position in whole AudioContext frames (the clock's native unit
2107
+ * for elapsed time). Same loop-wrap clamp and count-in hold as
2108
+ * getCurrentTime(). CONTEXT-rate frames — `getCurrentSample()` is the
2109
+ * timeline-rate view. */
2110
+ getCurrentFrame() {
2111
+ if (this._countingIn) {
2112
+ return this._clock.secondsToFrame(this._countInStartPosition);
2113
+ }
2114
+ const frame = this._clock.getFrame();
2115
+ const loopStartFrame = this._clock.secondsToFrame(this._loopStartSeconds);
2116
+ if (this._loopEnabled && frame < loopStartFrame) {
2117
+ return loopStartFrame;
2118
+ }
2119
+ return frame;
2120
+ }
2121
+ /** Current position in SampleTimeline samples (the `sampleRate` option's
2122
+ * rate; equal to getCurrentFrame() only when that matches the context).
2123
+ * Rounded once, at the Sample boundary. */
2124
+ getCurrentSample() {
2125
+ return this._sampleTimeline.secondsToSamples(this.getCurrentTime());
2126
+ }
2127
+ /** How many backward AudioContext clock readings the transport has absorbed
2128
+ * (see the `discontinuity` event). Diagnostics. */
2129
+ get rebaseCount() {
2130
+ return this._clock.rebaseCount;
2131
+ }
1428
2132
  isPlaying() {
1429
2133
  return this._playing;
1430
2134
  }
@@ -1539,14 +2243,12 @@ var _Transport = class _Transport {
1539
2243
  this._masterNode.setVolume(volume);
1540
2244
  }
1541
2245
  // --- Loop ---
1542
- /** Primary loop API — ticks as source of truth */
2246
+ /** Primary loop API — ticks as source of truth. Throws when `enabled` and
2247
+ * the range is non-finite, empty or inverted; nothing is changed and no
2248
+ * `loop` event fires. (NativePlayoutAdapter translates the engine's
2249
+ * default empty region to a disabled loop before reaching here.) */
1543
2250
  setLoop(enabled, startTick, endTick) {
1544
- if (enabled && startTick >= endTick) {
1545
- console.warn(
1546
- "[waveform-playlist] Transport.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
1547
- );
1548
- return;
1549
- }
2251
+ assertValidLoopRange("Transport.setLoop", enabled, startTick, endTick, "tick");
1550
2252
  this._loopEnabled = enabled;
1551
2253
  this._loopStartTick = startTick;
1552
2254
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
@@ -1554,28 +2256,37 @@ var _Transport = class _Transport {
1554
2256
  this._clipPlayer.setLoop(enabled, startTick, endTick);
1555
2257
  this._emit("loop");
1556
2258
  }
1557
- /** Convenience — converts seconds to ticks */
2259
+ /** Convenience — converts seconds to ticks. Same validation as setLoop,
2260
+ * applied in seconds so the error names the caller's unit. */
1558
2261
  setLoopSeconds(enabled, startSec, endSec) {
2262
+ assertValidLoopRange("Transport.setLoopSeconds", enabled, startSec, endSec, "second");
1559
2263
  const startTick = this._tempoMap.secondsToTicks(startSec);
1560
2264
  const endTick = this._tempoMap.secondsToTicks(endSec);
2265
+ assertLoopRangeSpansATick(
2266
+ "Transport.setLoopSeconds",
2267
+ enabled,
2268
+ startSec,
2269
+ endSec,
2270
+ "second",
2271
+ startTick,
2272
+ endTick
2273
+ );
1561
2274
  this.setLoop(enabled, startTick, endTick);
1562
2275
  }
1563
- /** Convenience — sets loop in samples */
2276
+ /** Convenience — sets loop in samples. Same validation as setLoop. */
1564
2277
  setLoopSamples(enabled, startSample, endSample) {
1565
- if (enabled && (!Number.isFinite(startSample) || !Number.isFinite(endSample))) {
1566
- console.warn(
1567
- "[waveform-playlist] Transport.setLoopSamples: non-finite sample values (" + startSample + ", " + endSample + ")"
1568
- );
1569
- return;
1570
- }
1571
- if (enabled && startSample >= endSample) {
1572
- console.warn(
1573
- "[waveform-playlist] Transport.setLoopSamples: startSample (" + startSample + ") must be less than endSample (" + endSample + ")"
1574
- );
1575
- return;
1576
- }
2278
+ assertValidLoopRange("Transport.setLoopSamples", enabled, startSample, endSample, "sample");
1577
2279
  const startTick = this._sampleTimeline.samplesToTicks(startSample);
1578
2280
  const endTick = this._sampleTimeline.samplesToTicks(endSample);
2281
+ assertLoopRangeSpansATick(
2282
+ "Transport.setLoopSamples",
2283
+ enabled,
2284
+ startSample,
2285
+ endSample,
2286
+ "sample",
2287
+ startTick,
2288
+ endTick
2289
+ );
1579
2290
  this._loopEnabled = enabled;
1580
2291
  this._loopStartTick = startTick;
1581
2292
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
@@ -1594,7 +2305,7 @@ var _Transport = class _Transport {
1594
2305
  );
1595
2306
  return false;
1596
2307
  }
1597
- this._tempoMap.setTempo(bpm, atTick, options);
2308
+ this._replaceTempoMap(this._tempoMap.withTempo(bpm, atTick, options));
1598
2309
  if (this._loopEnabled) {
1599
2310
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1600
2311
  }
@@ -1631,7 +2342,7 @@ var _Transport = class _Transport {
1631
2342
  });
1632
2343
  }
1633
2344
  clearTempos() {
1634
- this._tempoMap.clearTempos();
2345
+ this._replaceTempoMap(this._tempoMap.withoutTempos());
1635
2346
  if (this._loopEnabled) {
1636
2347
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1637
2348
  }
@@ -1642,7 +2353,7 @@ var _Transport = class _Transport {
1642
2353
  * invalidation and event; the emitted bpm is the tempo now in force at
1643
2354
  * the removed position. */
1644
2355
  removeTempo(atTick) {
1645
- this._tempoMap.removeTempo(atTick);
2356
+ this._replaceTempoMap(this._tempoMap.withoutTempo(atTick));
1646
2357
  if (this._loopEnabled) {
1647
2358
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1648
2359
  }
@@ -1651,14 +2362,28 @@ var _Transport = class _Transport {
1651
2362
  barToTick(bar) {
1652
2363
  return this._meterMap.barToTick(bar);
1653
2364
  }
2365
+ /** Snap a (possibly fractional) tick to the meter grid: `subdivision` is
2366
+ * `{ ticks }`, `{ note, dotted?, triplet? }`, 'bar' or 'beat'; `mode` is
2367
+ * 'nearest' (default) | 'next' | 'previous'; `strength` 0–1 scales the
2368
+ * move. Grid lines restart at each bar line, so odd meters stay aligned.
2369
+ * Pure function over the (live) MeterMap. */
2370
+ quantizeTick(tick, subdivision, options) {
2371
+ return quantizeTick(this._meterMap, tick, subdivision, options);
2372
+ }
1654
2373
  tickToBar(tick) {
1655
2374
  return this._meterMap.tickToBar(tick);
1656
2375
  }
1657
- /** Convert transport time (seconds) to tick position, using the tempo map. */
2376
+ /** Convert transport time (seconds) to an integer tick position, using the tempo map. */
1658
2377
  timeToTick(seconds) {
1659
2378
  return this._tempoMap.secondsToTicks(seconds);
1660
2379
  }
1661
- /** Convert tick position to transport time (seconds), using the tempo map. */
2380
+ /** Convert transport time (seconds) to a fractional tick position — for
2381
+ * sub-tick placement (e.g. a recorded note between ticks, before quantising). */
2382
+ timeToTickExact(seconds) {
2383
+ return this._tempoMap.secondsToTicksExact(seconds);
2384
+ }
2385
+ /** Convert a tick position (integer Tick or the fractional value
2386
+ * timeToTickExact returned) to transport time (seconds). */
1662
2387
  tickToTime(tick) {
1663
2388
  return this._tempoMap.ticksToSeconds(tick);
1664
2389
  }
@@ -1750,18 +2475,20 @@ var _Transport = class _Transport {
1750
2475
  // --- Dispose ---
1751
2476
  dispose() {
1752
2477
  this.stop();
2478
+ this._disposed = true;
1753
2479
  for (const node of this._trackNodes.values()) {
1754
2480
  node.dispose();
1755
2481
  }
1756
2482
  this._trackNodes.clear();
1757
2483
  this._masterNode.dispose();
2484
+ this._timer.dispose();
1758
2485
  this._listeners.clear();
1759
2486
  }
1760
2487
  // --- Private ---
1761
- static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead) {
1762
- if (sampleRate <= 0) {
2488
+ static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead, timerIntervalMs) {
2489
+ if (!(Number.isFinite(sampleRate) && sampleRate > 0)) {
1763
2490
  throw new Error(
1764
- "[waveform-playlist] Transport: sampleRate must be positive, got " + sampleRate
2491
+ "[waveform-playlist] Transport: options.sampleRate must be a positive finite number, got " + sampleRate
1765
2492
  );
1766
2493
  }
1767
2494
  if (ppqn <= 0 || !Number.isInteger(ppqn)) {
@@ -1787,6 +2514,11 @@ var _Transport = class _Transport {
1787
2514
  "[waveform-playlist] Transport: schedulerLookahead must be positive, got " + lookahead
1788
2515
  );
1789
2516
  }
2517
+ if (!(timerIntervalMs > 0) || timerIntervalMs >= lookahead * 1e3) {
2518
+ throw new Error(
2519
+ "[waveform-playlist] Transport: timerIntervalMs must be positive and shorter than the lookahead (" + lookahead * 1e3 + " ms), got " + timerIntervalMs
2520
+ );
2521
+ }
1790
2522
  }
1791
2523
  _initAudioGraph(audioContext) {
1792
2524
  this._masterNode = new MasterNode(audioContext);
@@ -1845,6 +2577,9 @@ var _Transport = class _Transport {
1845
2577
  this._countingIn = true;
1846
2578
  this._playing = true;
1847
2579
  this._endTime = endTime;
2580
+ this._scheduler.setPlayEnd(
2581
+ endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
2582
+ );
1848
2583
  const playPositionTick = this._tempoMap.secondsToTicks(currentTime);
1849
2584
  const meter = this._meterMap.getMeter(playPositionTick);
1850
2585
  const totalBeats = meter.numerator * this._countInBars;
@@ -1855,7 +2590,8 @@ var _Transport = class _Transport {
1855
2590
  const countInMeterMap = new MeterMap(this._ppqn, meter.numerator, meter.denominator);
1856
2591
  this._countInDuration = countInTempoMap.ticksToSeconds(countInTicks);
1857
2592
  this._countInScheduler = new Scheduler(countInTempoMap, {
1858
- lookahead: this._schedulerLookahead
2593
+ lookahead: this._schedulerLookahead,
2594
+ onError: (error) => this._emitError(error)
1859
2595
  });
1860
2596
  this._countInPlayer.configure({
1861
2597
  totalBeats,
@@ -1870,6 +2606,7 @@ var _Transport = class _Transport {
1870
2606
  this._countInScheduler.addListener(this._countInPlayer);
1871
2607
  this._countInScheduler.reset(0);
1872
2608
  this._clock.seekTo(0);
2609
+ this._markRebasesHandled();
1873
2610
  this._clock.start();
1874
2611
  this._timer.start();
1875
2612
  }
@@ -1892,6 +2629,28 @@ var _Transport = class _Transport {
1892
2629
  this._countingIn = false;
1893
2630
  this._timer.stop();
1894
2631
  }
2632
+ /** Install a new immutable TempoMap everywhere one is held. The count-in
2633
+ * player is configured with its own dedicated map at each count-in start,
2634
+ * so it is not on this list. */
2635
+ _replaceTempoMap(next) {
2636
+ this._tempoMap = next;
2637
+ this._scheduler.setTempoMap(next);
2638
+ this._sampleTimeline.setTempoMap(next);
2639
+ this._clipPlayer.setTempoMap(next);
2640
+ this._metronomePlayer.setTempoMap(next);
2641
+ if (this._endTime !== void 0) {
2642
+ this._scheduler.setPlayEnd(next.secondsToTicks(this._endTime));
2643
+ }
2644
+ }
2645
+ /** A disposed transport has no timer or audio graph; a late play()/seek()
2646
+ * must not report "playing" with nothing ticking. */
2647
+ _refuseIfDisposed(what) {
2648
+ if (!this._disposed) return false;
2649
+ console.warn(
2650
+ "[waveform-playlist] Transport: " + what + "() on a disposed transport is ignored"
2651
+ );
2652
+ return true;
2653
+ }
1895
2654
  _silenceAll() {
1896
2655
  this._clipPlayer.silence();
1897
2656
  this._metronomePlayer.silence();
@@ -1905,6 +2664,22 @@ var _Transport = class _Transport {
1905
2664
  node.setMute(isExplicitlyMuted || isSoloMuted);
1906
2665
  }
1907
2666
  }
2667
+ /** Route a scheduler listener failure to `error` subscribers, or to
2668
+ * console.warn (once per listener and failure kind) when nobody is listening —
2669
+ * the failure must stay visible either way. Subscribers are called on a
2670
+ * microtask, after the scheduler window that produced the failure has
2671
+ * completed: a handler that reacts with stop()/setTracks()/off() must not
2672
+ * re-enter the listener iteration that is still running. */
2673
+ _emitError(error) {
2674
+ queueMicrotask(() => {
2675
+ const listeners = this._listeners.get("error");
2676
+ if (listeners && listeners.size > 0) {
2677
+ this._emit("error", error);
2678
+ } else {
2679
+ this._errorLog.warnOnce(error);
2680
+ }
2681
+ });
2682
+ }
1908
2683
  _emit(event, ...args) {
1909
2684
  const listeners = this._listeners.get(event);
1910
2685
  if (listeners) {
@@ -1925,12 +2700,21 @@ var _Transport = class _Transport {
1925
2700
  _Transport.MIN_COUNT_IN_BARS = 1;
1926
2701
  _Transport.MAX_COUNT_IN_BARS = 8;
1927
2702
  var Transport = _Transport;
2703
+ function assertFiniteSeconds(method, name, value) {
2704
+ if (!Number.isFinite(value)) {
2705
+ throw new Error(
2706
+ "[waveform-playlist] Transport." + method + ": " + name + " must be finite, got " + value
2707
+ );
2708
+ }
2709
+ }
1928
2710
 
1929
2711
  // src/adapter.ts
1930
2712
  var NativePlayoutAdapter = class {
1931
2713
  constructor(audioContext, options) {
2714
+ this._onPlaybackEnded = null;
1932
2715
  this._audioContext = audioContext;
1933
2716
  this._transport = new Transport(audioContext, options);
2717
+ this._transport.on("ended", () => this._onPlaybackEnded?.());
1934
2718
  }
1935
2719
  get audioContext() {
1936
2720
  return this._audioContext;
@@ -1951,21 +2735,26 @@ var NativePlayoutAdapter = class {
1951
2735
  const warmupTarget = Math.max(MIN_WARMUP, this._audioContext.outputLatency ?? MIN_WARMUP);
1952
2736
  if (this._audioContext.currentTime < warmupTarget) {
1953
2737
  const MAX_WARMUP_MS = 2e3;
1954
- await new Promise((resolve) => {
2738
+ const WARMUP_POLL_MS = 16;
2739
+ await new Promise((resolve, reject) => {
1955
2740
  const startMs = performance.now();
1956
2741
  const check = () => {
1957
2742
  if (this._audioContext.currentTime >= warmupTarget) {
1958
2743
  resolve();
1959
- } else if (this._audioContext.state === "closed" || performance.now() - startMs > MAX_WARMUP_MS) {
2744
+ } else if (this._audioContext.state === "closed") {
2745
+ reject(
2746
+ new Error("[waveform-playlist] Cannot init: AudioContext closed during warmup")
2747
+ );
2748
+ } else if (performance.now() - startMs > MAX_WARMUP_MS) {
1960
2749
  console.warn(
1961
2750
  "[waveform-playlist] AudioContext warmup timed out (currentTime=" + this._audioContext.currentTime + ", target=" + warmupTarget + ", state=" + this._audioContext.state + "). Proceeding without warmup."
1962
2751
  );
1963
2752
  resolve();
1964
2753
  } else {
1965
- requestAnimationFrame(check);
2754
+ setTimeout(check, WARMUP_POLL_MS);
1966
2755
  }
1967
2756
  };
1968
- requestAnimationFrame(check);
2757
+ setTimeout(check, WARMUP_POLL_MS);
1969
2758
  });
1970
2759
  }
1971
2760
  }
@@ -1991,6 +2780,13 @@ var NativePlayoutAdapter = class {
1991
2780
  stop() {
1992
2781
  this._transport.stop();
1993
2782
  }
2783
+ /** Engine hook: adapter-initiated completion of a bounded play(start, end)
2784
+ * (the transport's `ended` event). Never fired for a consumer
2785
+ * stop()/pause()/seek()/dispose(), whether issued through this adapter or
2786
+ * directly on `adapter.transport`. */
2787
+ onPlaybackEnded(callback) {
2788
+ this._onPlaybackEnded = callback;
2789
+ }
1994
2790
  seek(time) {
1995
2791
  this._transport.seek(time);
1996
2792
  }
@@ -2016,7 +2812,13 @@ var NativePlayoutAdapter = class {
2016
2812
  this._transport.setTrackPan(trackId, pan);
2017
2813
  }
2018
2814
  setLoop(enabled, start, end) {
2019
- this._transport.setLoopSeconds(enabled, start, end);
2815
+ const finite = Number.isFinite(start) && Number.isFinite(end);
2816
+ const degenerate = enabled && finite && this._transport.timeToTick(start) >= this._transport.timeToTick(end);
2817
+ if (degenerate && !(start === 0 && end === 0)) {
2818
+ const why = start > end ? "inverted loop region (" + start + " > " + end + ")" : start === end ? "empty loop region (" + start + ")" : "loop region (" + start + ", " + end + ") is shorter than one tick";
2819
+ console.warn("[waveform-playlist] NativePlayoutAdapter.setLoop: " + why + " \u2014 loop disabled");
2820
+ }
2821
+ this._transport.setLoopSeconds(enabled && !degenerate, start, end);
2020
2822
  }
2021
2823
  setCountIn(enabled) {
2022
2824
  this._transport.setCountIn(enabled);
@@ -2049,10 +2851,15 @@ var NativePlayoutAdapter = class {
2049
2851
  secondsToTicks(seconds) {
2050
2852
  return this._transport.timeToTick(seconds);
2051
2853
  }
2854
+ /** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
2855
+ secondsToTicksExact(seconds) {
2856
+ return this._transport.timeToTickExact(seconds);
2857
+ }
2052
2858
  get masterOutputNode() {
2053
2859
  return this._transport.masterOutputNode;
2054
2860
  }
2055
2861
  dispose() {
2862
+ this._onPlaybackEnded = null;
2056
2863
  this._transport.dispose();
2057
2864
  }
2058
2865
  };
@@ -2060,15 +2867,18 @@ var NativePlayoutAdapter = class {
2060
2867
  0 && (module.exports = {
2061
2868
  ClipPlayer,
2062
2869
  Clock,
2870
+ DEFAULT_TIMER_INTERVAL_MS,
2063
2871
  MasterNode,
2064
2872
  MeterMap,
2065
2873
  MetronomePlayer,
2066
2874
  NativePlayoutAdapter,
2875
+ RENDER_QUANTUM_FRAMES,
2067
2876
  SampleTimeline,
2068
2877
  Scheduler,
2069
2878
  TempoMap,
2070
2879
  Timer,
2071
2880
  TrackNode,
2072
- Transport
2881
+ Transport,
2882
+ quantizeTick
2073
2883
  });
2074
2884
  //# sourceMappingURL=index.js.map