@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.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;
@@ -96,9 +257,32 @@ var Scheduler = class {
96
257
  this._loopEnd = 0;
97
258
  // integer ticks
98
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;
99
263
  this._tempoMap = tempoMap;
100
264
  this._lookahead = options.lookahead ?? 0.2;
101
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;
102
286
  }
103
287
  addListener(listener) {
104
288
  this._listeners.add(listener);
@@ -106,28 +290,28 @@ var Scheduler = class {
106
290
  removeListener(listener) {
107
291
  this._listeners.delete(listener);
108
292
  }
109
- /** 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. */
110
295
  setLoop(enabled, startTick, endTick) {
111
- if (enabled && (!Number.isFinite(startTick) || !Number.isFinite(endTick))) {
112
- console.warn(
113
- "[waveform-playlist] Scheduler.setLoop: non-finite tick values (" + startTick + ", " + endTick + ")"
114
- );
115
- return;
116
- }
117
- if (enabled && startTick >= endTick) {
118
- console.warn(
119
- "[waveform-playlist] Scheduler.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
120
- );
121
- return;
122
- }
296
+ assertValidLoopRange("Scheduler.setLoop", enabled, startTick, endTick, "tick");
123
297
  this._loopEnabled = enabled;
124
298
  this._loopStart = Math.round(startTick);
125
299
  this._loopEnd = Math.round(endTick);
126
300
  }
127
301
  /** Convenience — converts seconds to ticks via TempoMap */
128
302
  setLoopSeconds(enabled, startSec, endSec) {
303
+ assertValidLoopRange("Scheduler.setLoopSeconds", enabled, startSec, endSec, "second");
129
304
  const startTick = this._tempoMap.secondsToTicks(startSec);
130
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
+ );
131
315
  this.setLoop(enabled, startTick, endTick);
132
316
  }
133
317
  /** Hard end bound (ticks) for non-loop playback: the lookahead window never
@@ -138,35 +322,57 @@ var Scheduler = class {
138
322
  setPlayEnd(endTick) {
139
323
  this._playEnd = endTick == null ? null : Math.round(endTick);
140
324
  }
141
- /** Reset scheduling cursor. Takes seconds (from Clock), converts to ticks. */
325
+ /** Reset scheduling cursor. Takes seconds (from Clock), converts to integer
326
+ * ticks — secondsToTicks rounds once here; the cursor is always whole ticks. */
142
327
  reset(timeSeconds) {
143
328
  this._rightEdge = this._tempoMap.secondsToTicks(timeSeconds);
144
329
  }
145
330
  /** Advance the scheduling window. Takes seconds (from Clock), converts to ticks. */
146
331
  advance(currentTimeSeconds) {
147
- 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);
148
345
  if (this._loopEnabled && this._loopEnd > this._loopStart) {
149
- const loopDuration = this._loopEnd - this._loopStart;
150
346
  let remaining = targetTick - this._rightEdge;
151
347
  while (remaining > 0) {
152
348
  const distToEnd = this._loopEnd - this._rightEdge;
153
- if (distToEnd <= 0 || distToEnd > remaining) {
349
+ if (distToEnd > remaining) {
154
350
  this._generateAndConsume(this._rightEdge, this._rightEdge + remaining);
155
351
  this._rightEdge += remaining;
156
352
  break;
157
353
  }
158
- this._generateAndConsume(this._rightEdge, this._loopEnd);
159
- remaining -= distToEnd;
354
+ if (distToEnd > 0) {
355
+ this._generateAndConsume(this._rightEdge, this._loopEnd);
356
+ remaining -= distToEnd;
357
+ }
160
358
  for (const listener of this._listeners) {
161
- 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
+ }
162
369
  }
163
370
  this._onLoop?.(
164
- this._tempoMap.ticksToSeconds(this._loopStart),
165
- this._tempoMap.ticksToSeconds(this._loopEnd),
371
+ tempoMap.ticksToSeconds(this._loopStart),
372
+ tempoMap.ticksToSeconds(this._loopEnd),
166
373
  currentTimeSeconds
167
374
  );
168
375
  this._rightEdge = this._loopStart;
169
- if (loopDuration <= 0) break;
170
376
  }
171
377
  return;
172
378
  }
@@ -176,55 +382,204 @@ var Scheduler = class {
176
382
  this._rightEdge = bound;
177
383
  }
178
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
+ }
179
397
  _generateAndConsume(fromTick, toTick) {
180
398
  for (const listener of this._listeners) {
399
+ let events;
181
400
  try {
182
- const events = listener.generate(fromTick, toTick);
183
- for (const event of events) {
184
- try {
185
- listener.consume(event);
186
- } catch (err) {
187
- console.warn("[waveform-playlist] Scheduler: error consuming event:", String(err));
188
- }
189
- }
401
+ events = listener.generate(fromTick, toTick);
190
402
  } catch (err) {
191
- 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;
192
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;
193
425
  }
426
+ this._errorLog.warnOnce(error);
194
427
  }
195
428
  };
196
429
 
197
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
+ }
198
443
  var Timer = class {
199
- constructor(onTick) {
200
- this._rafId = null;
444
+ constructor(onTick, options = {}) {
201
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
+ }
202
461
  this._onTick = onTick;
462
+ this._intervalMs = intervalMs;
203
463
  }
204
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
+ }
205
472
  if (this._running) return;
206
473
  this._running = true;
207
- 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
+ }
208
481
  }
209
482
  stop() {
483
+ if (!this._running) return;
210
484
  this._running = false;
211
- if (this._rafId !== null) {
212
- cancelAnimationFrame(this._rafId);
213
- 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;
214
492
  }
215
493
  }
216
- _scheduleFrame() {
217
- this._rafId = requestAnimationFrame(() => {
218
- if (!this._running) return;
219
- try {
220
- this._onTick();
221
- } catch (err) {
222
- console.warn("[waveform-playlist] Timer tick error:", String(err));
223
- }
224
- if (this._running) {
225
- this._scheduleFrame();
226
- }
227
- });
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
+ }
228
583
  }
229
584
  };
230
585
 
@@ -247,36 +602,100 @@ var SampleTimeline = class {
247
602
  return Math.round(seconds * this._sampleRate);
248
603
  }
249
604
  ticksToSamples(ticks) {
250
- if (!this._tempoMap) {
251
- throw new Error(
252
- "[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
253
- );
254
- }
255
- return Math.round(this._tempoMap.ticksToSeconds(ticks) * this._sampleRate);
605
+ return Math.round(this._requireTempoMap().ticksToSeconds(ticks) * this._sampleRate);
256
606
  }
607
+ /** Samples → integer ticks. The integer `Tick` contract belongs to THIS
608
+ * boundary: exactly one rounding, applied to the fractional position. */
257
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() {
258
617
  if (!this._tempoMap) {
259
618
  throw new Error(
260
619
  "[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
261
620
  );
262
621
  }
263
- return Math.round(this._tempoMap.secondsToTicks(samples / this._sampleRate));
622
+ return this._tempoMap;
264
623
  }
265
624
  };
266
625
 
267
626
  // src/timeline/tempo-map.ts
268
627
  var CURVE_EPSILON = 1e-15;
269
- var CURVE_SUBDIVISIONS = 64;
270
- function curveNormalizedAt(x, slope) {
271
- 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) {
272
633
  const p = Math.max(CURVE_EPSILON, Math.min(1 - CURVE_EPSILON, slope));
273
- 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
+ }
274
679
  }
275
680
  var TempoMap = class _TempoMap {
276
- constructor(ppqn = 960, initialBpm = 120) {
277
- _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
+ }
278
685
  this._ppqn = ppqn;
279
- 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
+ }
280
699
  }
281
700
  /** A non-finite or non-positive BPM silently corrupts the secondsAtTick
282
701
  * cache (Infinity, or non-monotonic values that break the binary search
@@ -296,37 +715,110 @@ var TempoMap = class _TempoMap {
296
715
  get entryCount() {
297
716
  return this._entries.length;
298
717
  }
299
- 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) {
300
727
  _TempoMap._validateBpm(bpm);
301
- const interpolation = options?.interpolation ?? "step";
302
- if (typeof interpolation === "object" && interpolation.type === "curve") {
303
- 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;
304
732
  if (!Number.isFinite(s) || s <= 0 || s >= 1) {
305
733
  throw new Error(
306
734
  "[waveform-playlist] TempoMap: curve slope must be between 0 and 1 (exclusive), got " + s
307
735
  );
308
736
  }
309
737
  }
738
+ const interpolation = freezeInterpolation(requested);
739
+ const entries = [...this._entries];
310
740
  if (atTick === 0) {
311
- this._entries[0] = { ...this._entries[0], bpm, interpolation: "step" };
312
- this._recomputeCache(0);
313
- return;
741
+ entries[0] = { ...entries[0], bpm, interpolation: "step" };
742
+ return this._derive(entries, 0);
314
743
  }
315
- let i = this._entries.length - 1;
316
- while (i > 0 && this._entries[i].tick > atTick) i--;
317
- if (this._entries[i].tick === atTick) {
318
- 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 };
319
747
  } else {
320
- const secondsAtTick = this._ticksToSecondsInternal(atTick);
321
- this._entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick });
748
+ entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick: 0 });
322
749
  i = i + 1;
323
750
  }
324
- 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));
325
797
  }
798
+ /** Tick position → seconds. Accepts a fractional position (e.g. the value
799
+ * secondsToTicksExact returned) as well as an integer Tick. */
326
800
  ticksToSeconds(ticks) {
327
- return this._ticksToSecondsInternal(ticks);
801
+ assertFiniteInput("ticks", ticks);
802
+ return assertFiniteResult("ticks " + ticks, this._ticksToSecondsInternal(ticks));
328
803
  }
804
+ /** Seconds → integer ticks, rounded once here at the `Tick` boundary.
805
+ * Use secondsToTicksExact() for sub-tick placement. */
329
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;
330
822
  let lo = 0;
331
823
  let hi = this._entries.length - 1;
332
824
  while (lo < hi) {
@@ -341,50 +833,31 @@ var TempoMap = class _TempoMap {
341
833
  const secondsIntoSegment = seconds - entry.secondsAtTick;
342
834
  const nextEntry = lo < this._entries.length - 1 ? this._entries[lo + 1] : null;
343
835
  if (nextEntry && nextEntry.interpolation === "linear") {
344
- return Math.round(
345
- entry.tick + this._secondsToTicksLinear(
346
- secondsIntoSegment,
347
- entry.bpm,
348
- nextEntry.bpm,
349
- nextEntry.tick - entry.tick
350
- )
836
+ return entry.tick + this._secondsToTicksLinear(
837
+ secondsIntoSegment,
838
+ entry.bpm,
839
+ nextEntry.bpm,
840
+ nextEntry.tick - entry.tick
351
841
  );
352
842
  }
353
843
  if (nextEntry && typeof nextEntry.interpolation === "object") {
354
- return Math.round(
355
- entry.tick + this._secondsToTicksCurve(
356
- secondsIntoSegment,
357
- entry.bpm,
358
- nextEntry.bpm,
359
- nextEntry.tick - entry.tick,
360
- nextEntry.interpolation.slope
361
- )
844
+ return entry.tick + this._secondsToTicksCurve(
845
+ secondsIntoSegment,
846
+ entry.bpm,
847
+ nextEntry.bpm,
848
+ nextEntry.tick - entry.tick,
849
+ nextEntry.interpolation.slope
362
850
  );
363
851
  }
364
852
  const ticksPerSecond = entry.bpm / 60 * this._ppqn;
365
- return Math.round(entry.tick + secondsIntoSegment * ticksPerSecond);
853
+ return entry.tick + secondsIntoSegment * ticksPerSecond;
366
854
  }
367
855
  beatsToSeconds(beats) {
368
856
  return this.ticksToSeconds(beats * this._ppqn);
369
857
  }
858
+ /** Continuous beat position (fractional) — not quantised to whole ticks. */
370
859
  secondsToBeats(seconds) {
371
- return this.secondsToTicks(seconds) / this._ppqn;
372
- }
373
- clearTempos() {
374
- const first = this._entries[0];
375
- this._entries = [{ tick: 0, bpm: first.bpm, interpolation: "step", secondsAtTick: 0 }];
376
- }
377
- /** Remove the tempo entry at exactly `atTick`, if one exists. The tick-0
378
- * entry is permanent (a map must always have a tempo) — removing it is a
379
- * no-op, matching removeMeter's treatment of the initial meter. The
380
- * seconds cache is recomputed from the removal point, the same partial
381
- * update setTempo uses. */
382
- removeTempo(atTick) {
383
- if (atTick === 0) return;
384
- const i = this._entries.findIndex((e) => e.tick === atTick);
385
- if (i === -1) return;
386
- this._entries = [...this._entries.slice(0, i), ...this._entries.slice(i + 1)];
387
- this._recomputeCache(i);
860
+ return this.secondsToTicksExact(seconds) / this._ppqn;
388
861
  }
389
862
  /** Get the interpolated BPM at a tick position */
390
863
  _getTempoAt(atTick) {
@@ -406,6 +879,7 @@ var TempoMap = class _TempoMap {
406
879
  return entry.bpm;
407
880
  }
408
881
  _ticksToSecondsInternal(ticks) {
882
+ if (ticks < 0) return ticks * 60 / (this._entries[0].bpm * this._ppqn);
409
883
  const entryIndex = this._entryIndexAt(ticks);
410
884
  const entry = this._entries[entryIndex];
411
885
  const ticksIntoSegment = ticks - entry.tick;
@@ -446,10 +920,9 @@ var TempoMap = class _TempoMap {
446
920
  * Closed-form via exponential: bpmAtTick = bpm0 * exp(seconds * deltaBpm * ppqn / (60 * T))
447
921
  * then ticks = (bpmAtTick - bpm0) * T / deltaBpm
448
922
  *
449
- * Note: exp(log(x)) has ~1 ULP floating-point error, so round-trips depend on
450
- * Math.round() in the caller (secondsToTicks). This is sufficient for all tested
451
- * BPM ranges (10–300 BPM) but is not algebraically exact like the previous
452
- * 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).
453
926
  */
454
927
  _secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks) {
455
928
  if (totalSegmentTicks === 0 || seconds === 0) return 0;
@@ -461,43 +934,71 @@ var TempoMap = class _TempoMap {
461
934
  return (bpmAtTick - bpm0) / deltaBpm * totalSegmentTicks;
462
935
  }
463
936
  /**
464
- * Subdivided trapezoidal integration for a Möbius-Ease tempo curve.
465
- * The BPM at progress p is: bpm0 + curveNormalizedAt(p, slope) * (bpm1 - bpm0).
466
- * 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).
467
955
  */
468
956
  _ticksToSecondsCurve(ticks, bpm0, bpm1, totalSegmentTicks, slope) {
469
957
  if (totalSegmentTicks === 0 || ticks === 0) return 0;
470
- const n = CURVE_SUBDIVISIONS;
471
- const dt = ticks / n;
472
- let seconds = 0;
473
- let prevBpm = bpm0;
474
- for (let i = 1; i <= n; i++) {
475
- const progress = dt * i / totalSegmentTicks;
476
- const curBpm = bpm0 + curveNormalizedAt(progress, slope) * (bpm1 - bpm0);
477
- seconds += dt * 60 / this._ppqn * (1 / prevBpm + 1 / curBpm) / 2;
478
- prevBpm = curBpm;
479
- }
480
- 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;
481
970
  }
482
971
  /**
483
- * Inverse of _ticksToSecondsCurve: given seconds into a curved segment,
484
- * 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.
485
983
  */
486
984
  _secondsToTicksCurve(seconds, bpm0, bpm1, totalSegmentTicks, slope) {
487
985
  if (totalSegmentTicks === 0 || seconds === 0) return 0;
488
- const iterations = Math.min(40, Math.max(1, Math.ceil(Math.log2(2 * totalSegmentTicks))));
489
- let lo = 0;
490
- let hi = totalSegmentTicks;
491
- for (let i = 0; i < iterations; i++) {
492
- const mid = (lo + hi) / 2;
493
- const midSeconds = this._ticksToSecondsCurve(mid, bpm0, bpm1, totalSegmentTicks, slope);
494
- if (midSeconds < seconds) {
495
- lo = mid;
496
- } else {
497
- hi = mid;
498
- }
986
+ if (isNearLinearSlope(slope)) {
987
+ return this._secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks);
499
988
  }
500
- return (lo + hi) / 2;
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;
994
+ }
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 };
501
1002
  }
502
1003
  _entryIndexAt(tick) {
503
1004
  let lo = 0;
@@ -512,32 +1013,6 @@ var TempoMap = class _TempoMap {
512
1013
  }
513
1014
  return lo;
514
1015
  }
515
- _recomputeCache(fromIndex) {
516
- for (let i = Math.max(1, fromIndex); i < this._entries.length; i++) {
517
- const prev = this._entries[i - 1];
518
- const tickDelta = this._entries[i].tick - prev.tick;
519
- const entry = this._entries[i];
520
- let segmentSeconds;
521
- if (entry.interpolation === "linear") {
522
- segmentSeconds = this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
523
- } else if (typeof entry.interpolation === "object") {
524
- segmentSeconds = this._ticksToSecondsCurve(
525
- tickDelta,
526
- prev.bpm,
527
- entry.bpm,
528
- tickDelta,
529
- entry.interpolation.slope
530
- );
531
- } else {
532
- const secondsPerTick = 60 / (prev.bpm * this._ppqn);
533
- segmentSeconds = tickDelta * secondsPerTick;
534
- }
535
- this._entries[i] = {
536
- ...entry,
537
- secondsAtTick: prev.secondsAtTick + segmentSeconds
538
- };
539
- }
540
- }
541
1016
  };
542
1017
 
543
1018
  // src/timeline/meter-map.ts
@@ -593,6 +1068,7 @@ var MeterMap = class {
593
1068
  const idx = this._entries.findIndex((e) => e.tick === atTick);
594
1069
  if (idx > 0) {
595
1070
  this._entries.splice(idx, 1);
1071
+ this._resnapDownstreamEntries(idx - 1);
596
1072
  this._recomputeCache(idx);
597
1073
  } else if (idx === -1) {
598
1074
  console.warn("[waveform-playlist] MeterMap.removeMeter: no entry at tick " + atTick);
@@ -719,6 +1195,80 @@ var MeterMap = class {
719
1195
  }
720
1196
  };
721
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
+
722
1272
  // src/audio/master-node.ts
723
1273
  var MasterNode = class {
724
1274
  constructor(audioContext) {
@@ -850,6 +1400,10 @@ var ClipPlayer = class {
850
1400
  this._tempoMap = tempoMap;
851
1401
  this._toAudioTime = toAudioTime;
852
1402
  }
1403
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
1404
+ setTempoMap(tempoMap) {
1405
+ this._tempoMap = tempoMap;
1406
+ }
853
1407
  setTracks(tracks, trackNodes) {
854
1408
  this._tracks.clear();
855
1409
  this._trackNodes = trackNodes;
@@ -1063,6 +1617,10 @@ var MetronomePlayer = class {
1063
1617
  this._destination = destination;
1064
1618
  this._toAudioTime = toAudioTime;
1065
1619
  }
1620
+ /** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
1621
+ setTempoMap(tempoMap) {
1622
+ this._tempoMap = tempoMap;
1623
+ }
1066
1624
  setEnabled(enabled) {
1067
1625
  this._enabled = enabled;
1068
1626
  if (!enabled) {
@@ -1218,12 +1776,9 @@ var CountInPlayer = class {
1218
1776
  });
1219
1777
  const transportTime = this._tempoMap.ticksToSeconds(event.tick);
1220
1778
  source.start(this._toAudioTime(transportTime));
1221
- } catch (err) {
1222
- console.warn(
1223
- "[waveform-playlist] CountInPlayer.consume: failed to schedule beat " + event.beat + "/" + event.totalBeats + ": " + String(err)
1224
- );
1779
+ } finally {
1780
+ this._onBeat?.(event.beat, event.totalBeats);
1225
1781
  }
1226
- this._onBeat?.(event.beat, event.totalBeats);
1227
1782
  }
1228
1783
  onPositionJump(_newTick) {
1229
1784
  }
@@ -1289,6 +1844,11 @@ var _Transport = class _Transport {
1289
1844
  this._soloedTrackIds = /* @__PURE__ */ new Set();
1290
1845
  this._mutedTrackIds = /* @__PURE__ */ new Set();
1291
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;
1292
1852
  this._loopEnabled = false;
1293
1853
  this._loopStartTick = 0;
1294
1854
  this._loopStartSeconds = 0;
@@ -1307,17 +1867,32 @@ var _Transport = class _Transport {
1307
1867
  this._accentBuffer = null;
1308
1868
  this._normalBuffer = null;
1309
1869
  this._schedulerLookahead = 0.2;
1870
+ this._errorLog = new ListenerErrorLog("[waveform-playlist] Transport: ");
1310
1871
  this._ppqn = 960;
1311
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
+ }
1312
1878
  const sampleRate = options.sampleRate ?? audioContext.sampleRate;
1313
1879
  const ppqn = options.ppqn ?? 960;
1314
1880
  const tempo = options.tempo ?? 120;
1315
1881
  const numerator = options.numerator ?? 4;
1316
1882
  const denominator = options.denominator ?? 4;
1317
1883
  const lookahead = options.schedulerLookahead ?? 0.2;
1884
+ const timerIntervalMs = options.timerIntervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
1318
1885
  this._ppqn = ppqn;
1319
1886
  this._schedulerLookahead = lookahead;
1320
- _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
+ );
1321
1896
  this._clock = new Clock(audioContext);
1322
1897
  this._sampleTimeline = new SampleTimeline(sampleRate);
1323
1898
  this._meterMap = new MeterMap(ppqn, numerator, denominator);
@@ -1327,13 +1902,33 @@ var _Transport = class _Transport {
1327
1902
  onLoop: (loopStartSeconds, loopEndSeconds, currentTimeSeconds) => {
1328
1903
  const timeToBoundary = loopEndSeconds - currentTimeSeconds;
1329
1904
  this._clock.seekTo(loopStartSeconds - timeToBoundary);
1330
- }
1905
+ },
1906
+ onError: (error) => this._emitError(error)
1331
1907
  });
1332
1908
  this._sampleTimeline.setTempoMap(this._tempoMap);
1333
1909
  this._initAudioGraph(audioContext);
1334
1910
  this._initCountIn(audioContext, options);
1335
- 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
+ {
1336
1927
  const time = this._clock.getTime();
1928
+ if (this._clock.rebaseCount !== this._rebasesHandled) {
1929
+ this._rebasesHandled = this._clock.rebaseCount;
1930
+ this._resyncAfterDiscontinuity(time);
1931
+ }
1337
1932
  if (this._countingIn) {
1338
1933
  this._countInScheduler?.advance(time);
1339
1934
  if (time >= this._countInDuration) {
@@ -1343,10 +1938,65 @@ var _Transport = class _Transport {
1343
1938
  }
1344
1939
  if (this._endTime !== void 0 && time >= this._endTime) {
1345
1940
  this.stop();
1941
+ this._emit("ended");
1346
1942
  return;
1347
1943
  }
1348
1944
  this._scheduler.advance(time);
1349
- });
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
+ }
1350
2000
  }
1351
2001
  get audioContext() {
1352
2002
  return this._audioContext;
@@ -1354,8 +2004,16 @@ var _Transport = class _Transport {
1354
2004
  get ppqn() {
1355
2005
  return this._ppqn;
1356
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
+ }
1357
2012
  // --- Playback ---
1358
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);
1359
2017
  if (this._playing) return;
1360
2018
  if (startTime !== void 0) {
1361
2019
  this._clock.seekTo(startTime);
@@ -1370,6 +2028,7 @@ var _Transport = class _Transport {
1370
2028
  this._scheduler.setPlayEnd(
1371
2029
  endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
1372
2030
  );
2031
+ this._markRebasesHandled();
1373
2032
  this._clock.start();
1374
2033
  const currentTick = this._tempoMap.secondsToTicks(currentTime);
1375
2034
  this._clipPlayer.onPositionJump(currentTick);
@@ -1409,6 +2068,8 @@ var _Transport = class _Transport {
1409
2068
  }
1410
2069
  }
1411
2070
  seek(time) {
2071
+ if (this._refuseIfDisposed("seek")) return;
2072
+ assertFiniteSeconds("seek", "time", time);
1412
2073
  const wasPlaying = this._playing;
1413
2074
  const wasCountingIn = this._countingIn;
1414
2075
  if (wasCountingIn) {
@@ -1420,6 +2081,7 @@ var _Transport = class _Transport {
1420
2081
  }
1421
2082
  this._silenceAll();
1422
2083
  this._clock.seekTo(time);
2084
+ this._markRebasesHandled();
1423
2085
  this._scheduler.reset(time);
1424
2086
  this._endTime = void 0;
1425
2087
  this._scheduler.setPlayEnd(null);
@@ -1441,6 +2103,32 @@ var _Transport = class _Transport {
1441
2103
  }
1442
2104
  return t;
1443
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
+ }
1444
2132
  isPlaying() {
1445
2133
  return this._playing;
1446
2134
  }
@@ -1555,14 +2243,12 @@ var _Transport = class _Transport {
1555
2243
  this._masterNode.setVolume(volume);
1556
2244
  }
1557
2245
  // --- Loop ---
1558
- /** 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.) */
1559
2250
  setLoop(enabled, startTick, endTick) {
1560
- if (enabled && startTick >= endTick) {
1561
- console.warn(
1562
- "[waveform-playlist] Transport.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
1563
- );
1564
- return;
1565
- }
2251
+ assertValidLoopRange("Transport.setLoop", enabled, startTick, endTick, "tick");
1566
2252
  this._loopEnabled = enabled;
1567
2253
  this._loopStartTick = startTick;
1568
2254
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
@@ -1570,28 +2256,37 @@ var _Transport = class _Transport {
1570
2256
  this._clipPlayer.setLoop(enabled, startTick, endTick);
1571
2257
  this._emit("loop");
1572
2258
  }
1573
- /** 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. */
1574
2261
  setLoopSeconds(enabled, startSec, endSec) {
2262
+ assertValidLoopRange("Transport.setLoopSeconds", enabled, startSec, endSec, "second");
1575
2263
  const startTick = this._tempoMap.secondsToTicks(startSec);
1576
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
+ );
1577
2274
  this.setLoop(enabled, startTick, endTick);
1578
2275
  }
1579
- /** Convenience — sets loop in samples */
2276
+ /** Convenience — sets loop in samples. Same validation as setLoop. */
1580
2277
  setLoopSamples(enabled, startSample, endSample) {
1581
- if (enabled && (!Number.isFinite(startSample) || !Number.isFinite(endSample))) {
1582
- console.warn(
1583
- "[waveform-playlist] Transport.setLoopSamples: non-finite sample values (" + startSample + ", " + endSample + ")"
1584
- );
1585
- return;
1586
- }
1587
- if (enabled && startSample >= endSample) {
1588
- console.warn(
1589
- "[waveform-playlist] Transport.setLoopSamples: startSample (" + startSample + ") must be less than endSample (" + endSample + ")"
1590
- );
1591
- return;
1592
- }
2278
+ assertValidLoopRange("Transport.setLoopSamples", enabled, startSample, endSample, "sample");
1593
2279
  const startTick = this._sampleTimeline.samplesToTicks(startSample);
1594
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
+ );
1595
2290
  this._loopEnabled = enabled;
1596
2291
  this._loopStartTick = startTick;
1597
2292
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
@@ -1610,7 +2305,7 @@ var _Transport = class _Transport {
1610
2305
  );
1611
2306
  return false;
1612
2307
  }
1613
- this._tempoMap.setTempo(bpm, atTick, options);
2308
+ this._replaceTempoMap(this._tempoMap.withTempo(bpm, atTick, options));
1614
2309
  if (this._loopEnabled) {
1615
2310
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1616
2311
  }
@@ -1647,7 +2342,7 @@ var _Transport = class _Transport {
1647
2342
  });
1648
2343
  }
1649
2344
  clearTempos() {
1650
- this._tempoMap.clearTempos();
2345
+ this._replaceTempoMap(this._tempoMap.withoutTempos());
1651
2346
  if (this._loopEnabled) {
1652
2347
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1653
2348
  }
@@ -1658,7 +2353,7 @@ var _Transport = class _Transport {
1658
2353
  * invalidation and event; the emitted bpm is the tempo now in force at
1659
2354
  * the removed position. */
1660
2355
  removeTempo(atTick) {
1661
- this._tempoMap.removeTempo(atTick);
2356
+ this._replaceTempoMap(this._tempoMap.withoutTempo(atTick));
1662
2357
  if (this._loopEnabled) {
1663
2358
  this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
1664
2359
  }
@@ -1667,14 +2362,28 @@ var _Transport = class _Transport {
1667
2362
  barToTick(bar) {
1668
2363
  return this._meterMap.barToTick(bar);
1669
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
+ }
1670
2373
  tickToBar(tick) {
1671
2374
  return this._meterMap.tickToBar(tick);
1672
2375
  }
1673
- /** 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. */
1674
2377
  timeToTick(seconds) {
1675
2378
  return this._tempoMap.secondsToTicks(seconds);
1676
2379
  }
1677
- /** 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). */
1678
2387
  tickToTime(tick) {
1679
2388
  return this._tempoMap.ticksToSeconds(tick);
1680
2389
  }
@@ -1766,18 +2475,20 @@ var _Transport = class _Transport {
1766
2475
  // --- Dispose ---
1767
2476
  dispose() {
1768
2477
  this.stop();
2478
+ this._disposed = true;
1769
2479
  for (const node of this._trackNodes.values()) {
1770
2480
  node.dispose();
1771
2481
  }
1772
2482
  this._trackNodes.clear();
1773
2483
  this._masterNode.dispose();
2484
+ this._timer.dispose();
1774
2485
  this._listeners.clear();
1775
2486
  }
1776
2487
  // --- Private ---
1777
- static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead) {
1778
- if (sampleRate <= 0) {
2488
+ static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead, timerIntervalMs) {
2489
+ if (!(Number.isFinite(sampleRate) && sampleRate > 0)) {
1779
2490
  throw new Error(
1780
- "[waveform-playlist] Transport: sampleRate must be positive, got " + sampleRate
2491
+ "[waveform-playlist] Transport: options.sampleRate must be a positive finite number, got " + sampleRate
1781
2492
  );
1782
2493
  }
1783
2494
  if (ppqn <= 0 || !Number.isInteger(ppqn)) {
@@ -1803,6 +2514,11 @@ var _Transport = class _Transport {
1803
2514
  "[waveform-playlist] Transport: schedulerLookahead must be positive, got " + lookahead
1804
2515
  );
1805
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
+ }
1806
2522
  }
1807
2523
  _initAudioGraph(audioContext) {
1808
2524
  this._masterNode = new MasterNode(audioContext);
@@ -1874,7 +2590,8 @@ var _Transport = class _Transport {
1874
2590
  const countInMeterMap = new MeterMap(this._ppqn, meter.numerator, meter.denominator);
1875
2591
  this._countInDuration = countInTempoMap.ticksToSeconds(countInTicks);
1876
2592
  this._countInScheduler = new Scheduler(countInTempoMap, {
1877
- lookahead: this._schedulerLookahead
2593
+ lookahead: this._schedulerLookahead,
2594
+ onError: (error) => this._emitError(error)
1878
2595
  });
1879
2596
  this._countInPlayer.configure({
1880
2597
  totalBeats,
@@ -1889,6 +2606,7 @@ var _Transport = class _Transport {
1889
2606
  this._countInScheduler.addListener(this._countInPlayer);
1890
2607
  this._countInScheduler.reset(0);
1891
2608
  this._clock.seekTo(0);
2609
+ this._markRebasesHandled();
1892
2610
  this._clock.start();
1893
2611
  this._timer.start();
1894
2612
  }
@@ -1911,6 +2629,28 @@ var _Transport = class _Transport {
1911
2629
  this._countingIn = false;
1912
2630
  this._timer.stop();
1913
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
+ }
1914
2654
  _silenceAll() {
1915
2655
  this._clipPlayer.silence();
1916
2656
  this._metronomePlayer.silence();
@@ -1924,6 +2664,22 @@ var _Transport = class _Transport {
1924
2664
  node.setMute(isExplicitlyMuted || isSoloMuted);
1925
2665
  }
1926
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
+ }
1927
2683
  _emit(event, ...args) {
1928
2684
  const listeners = this._listeners.get(event);
1929
2685
  if (listeners) {
@@ -1944,12 +2700,21 @@ var _Transport = class _Transport {
1944
2700
  _Transport.MIN_COUNT_IN_BARS = 1;
1945
2701
  _Transport.MAX_COUNT_IN_BARS = 8;
1946
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
+ }
1947
2710
 
1948
2711
  // src/adapter.ts
1949
2712
  var NativePlayoutAdapter = class {
1950
2713
  constructor(audioContext, options) {
2714
+ this._onPlaybackEnded = null;
1951
2715
  this._audioContext = audioContext;
1952
2716
  this._transport = new Transport(audioContext, options);
2717
+ this._transport.on("ended", () => this._onPlaybackEnded?.());
1953
2718
  }
1954
2719
  get audioContext() {
1955
2720
  return this._audioContext;
@@ -1970,21 +2735,26 @@ var NativePlayoutAdapter = class {
1970
2735
  const warmupTarget = Math.max(MIN_WARMUP, this._audioContext.outputLatency ?? MIN_WARMUP);
1971
2736
  if (this._audioContext.currentTime < warmupTarget) {
1972
2737
  const MAX_WARMUP_MS = 2e3;
1973
- await new Promise((resolve) => {
2738
+ const WARMUP_POLL_MS = 16;
2739
+ await new Promise((resolve, reject) => {
1974
2740
  const startMs = performance.now();
1975
2741
  const check = () => {
1976
2742
  if (this._audioContext.currentTime >= warmupTarget) {
1977
2743
  resolve();
1978
- } 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) {
1979
2749
  console.warn(
1980
2750
  "[waveform-playlist] AudioContext warmup timed out (currentTime=" + this._audioContext.currentTime + ", target=" + warmupTarget + ", state=" + this._audioContext.state + "). Proceeding without warmup."
1981
2751
  );
1982
2752
  resolve();
1983
2753
  } else {
1984
- requestAnimationFrame(check);
2754
+ setTimeout(check, WARMUP_POLL_MS);
1985
2755
  }
1986
2756
  };
1987
- requestAnimationFrame(check);
2757
+ setTimeout(check, WARMUP_POLL_MS);
1988
2758
  });
1989
2759
  }
1990
2760
  }
@@ -2010,6 +2780,13 @@ var NativePlayoutAdapter = class {
2010
2780
  stop() {
2011
2781
  this._transport.stop();
2012
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
+ }
2013
2790
  seek(time) {
2014
2791
  this._transport.seek(time);
2015
2792
  }
@@ -2035,7 +2812,13 @@ var NativePlayoutAdapter = class {
2035
2812
  this._transport.setTrackPan(trackId, pan);
2036
2813
  }
2037
2814
  setLoop(enabled, start, end) {
2038
- 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);
2039
2822
  }
2040
2823
  setCountIn(enabled) {
2041
2824
  this._transport.setCountIn(enabled);
@@ -2068,10 +2851,15 @@ var NativePlayoutAdapter = class {
2068
2851
  secondsToTicks(seconds) {
2069
2852
  return this._transport.timeToTick(seconds);
2070
2853
  }
2854
+ /** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
2855
+ secondsToTicksExact(seconds) {
2856
+ return this._transport.timeToTickExact(seconds);
2857
+ }
2071
2858
  get masterOutputNode() {
2072
2859
  return this._transport.masterOutputNode;
2073
2860
  }
2074
2861
  dispose() {
2862
+ this._onPlaybackEnded = null;
2075
2863
  this._transport.dispose();
2076
2864
  }
2077
2865
  };
@@ -2079,15 +2867,18 @@ var NativePlayoutAdapter = class {
2079
2867
  0 && (module.exports = {
2080
2868
  ClipPlayer,
2081
2869
  Clock,
2870
+ DEFAULT_TIMER_INTERVAL_MS,
2082
2871
  MasterNode,
2083
2872
  MeterMap,
2084
2873
  MetronomePlayer,
2085
2874
  NativePlayoutAdapter,
2875
+ RENDER_QUANTUM_FRAMES,
2086
2876
  SampleTimeline,
2087
2877
  Scheduler,
2088
2878
  TempoMap,
2089
2879
  Timer,
2090
2880
  TrackNode,
2091
- Transport
2881
+ Transport,
2882
+ quantizeTick
2092
2883
  });
2093
2884
  //# sourceMappingURL=index.js.map