@dawcore/transport 0.0.14 → 0.0.16-next.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +68 -23
- package/dist/index.d.mts +548 -51
- package/dist/index.d.ts +548 -51
- package/dist/index.js +1107 -270
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1103 -269
- package/dist/index.mjs.map +1 -1
- package/package.json +6 -4
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
|
-
|
|
43
|
-
this.
|
|
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.
|
|
93
|
+
this._contextFrameAtAnchor = this._readContextFrame();
|
|
49
94
|
this._running = true;
|
|
50
95
|
}
|
|
51
96
|
stop() {
|
|
52
97
|
if (!this._running) return;
|
|
53
|
-
this.
|
|
98
|
+
this._elapsedBeforeAnchor += this._elapsedFrames();
|
|
54
99
|
this._running = false;
|
|
55
100
|
}
|
|
56
101
|
reset() {
|
|
57
102
|
this._running = false;
|
|
58
|
-
this.
|
|
59
|
-
this.
|
|
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
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
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
|
-
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
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
|
-
*
|
|
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
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
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
|
|
349
|
+
if (distToEnd > remaining) {
|
|
154
350
|
this._generateAndConsume(this._rightEdge, this._rightEdge + remaining);
|
|
155
351
|
this._rightEdge += remaining;
|
|
156
352
|
break;
|
|
157
353
|
}
|
|
158
|
-
|
|
159
|
-
|
|
354
|
+
if (distToEnd > 0) {
|
|
355
|
+
this._generateAndConsume(this._rightEdge, this._loopEnd);
|
|
356
|
+
remaining -= distToEnd;
|
|
357
|
+
}
|
|
160
358
|
for (const listener of this._listeners) {
|
|
161
|
-
|
|
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
|
-
|
|
165
|
-
|
|
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
|
-
|
|
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
|
-
|
|
403
|
+
this._reportError({
|
|
404
|
+
phase: "generate",
|
|
405
|
+
listener,
|
|
406
|
+
fromTick,
|
|
407
|
+
toTick,
|
|
408
|
+
error: err
|
|
409
|
+
});
|
|
410
|
+
continue;
|
|
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
|
+
}
|
|
192
418
|
}
|
|
193
419
|
}
|
|
194
420
|
}
|
|
421
|
+
_reportError(error) {
|
|
422
|
+
if (this._onError) {
|
|
423
|
+
this._onError(error);
|
|
424
|
+
return;
|
|
425
|
+
}
|
|
426
|
+
this._errorLog.warnOnce(error);
|
|
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.
|
|
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
|
-
|
|
212
|
-
|
|
213
|
-
this.
|
|
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
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
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
|
-
|
|
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
|
|
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
|
|
270
|
-
function
|
|
271
|
-
|
|
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
|
-
|
|
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,
|
|
277
|
-
|
|
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
|
-
|
|
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
|
-
|
|
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
|
-
|
|
302
|
-
|
|
303
|
-
|
|
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
|
-
|
|
312
|
-
this.
|
|
313
|
-
return;
|
|
741
|
+
entries[0] = { ...entries[0], bpm, interpolation: "step" };
|
|
742
|
+
return this._derive(entries, 0);
|
|
314
743
|
}
|
|
315
|
-
let i = this.
|
|
316
|
-
|
|
317
|
-
|
|
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
|
-
|
|
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.
|
|
751
|
+
return this._derive(entries, i);
|
|
325
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));
|
|
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
|
-
|
|
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
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
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
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
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
|
|
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.
|
|
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
|
|
450
|
-
*
|
|
451
|
-
* BPM ranges (10–300 BPM)
|
|
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
|
-
*
|
|
465
|
-
*
|
|
466
|
-
*
|
|
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
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
}
|
|
480
|
-
|
|
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
|
-
*
|
|
484
|
-
*
|
|
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
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
} else {
|
|
497
|
-
hi = mid;
|
|
498
|
-
}
|
|
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;
|
|
499
994
|
}
|
|
500
|
-
|
|
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) {
|
|
@@ -778,62 +1328,92 @@ var MasterNode = class {
|
|
|
778
1328
|
};
|
|
779
1329
|
|
|
780
1330
|
// src/audio/track-node.ts
|
|
1331
|
+
var import_core = require("@waveform-playlist/core");
|
|
1332
|
+
var PREFIX = "[waveform-playlist] ";
|
|
781
1333
|
var TrackNode = class {
|
|
782
|
-
constructor(id, audioContext) {
|
|
783
|
-
this.
|
|
784
|
-
this._effectsInput = null;
|
|
1334
|
+
constructor(id, audioContext, sourceChannelCount = 1) {
|
|
1335
|
+
this._effects = null;
|
|
785
1336
|
this.id = id;
|
|
1337
|
+
this._inputNode = audioContext.createGain();
|
|
786
1338
|
this._volumeNode = audioContext.createGain();
|
|
787
|
-
this.
|
|
788
|
-
this._panNode.channelCount = 2;
|
|
1339
|
+
this._panStage = (0, import_core.createPanStage)(audioContext, 0, sourceChannelCount);
|
|
789
1340
|
this._muteNode = audioContext.createGain();
|
|
790
|
-
this.
|
|
791
|
-
this.
|
|
1341
|
+
this._inputNode.connect(this._volumeNode);
|
|
1342
|
+
this._volumeNode.connect(this._panStage.input);
|
|
1343
|
+
this._panStage.output.connect(this._muteNode);
|
|
792
1344
|
}
|
|
793
|
-
/** Where clip sources connect */
|
|
1345
|
+
/** Where clip sources connect (pre-fader, pre-effects). */
|
|
794
1346
|
get input() {
|
|
795
|
-
return this.
|
|
1347
|
+
return this._inputNode;
|
|
796
1348
|
}
|
|
797
1349
|
/** Connect this track's output to a destination (master node) */
|
|
798
1350
|
connectOutput(destination) {
|
|
799
|
-
this._destination = destination;
|
|
800
1351
|
this._muteNode.connect(destination);
|
|
801
1352
|
}
|
|
802
1353
|
setVolume(value) {
|
|
803
1354
|
this._volumeNode.gain.value = value;
|
|
804
1355
|
}
|
|
805
1356
|
setPan(value) {
|
|
806
|
-
this.
|
|
1357
|
+
this._panStage.setPan(value);
|
|
1358
|
+
}
|
|
1359
|
+
/** Select the pan law from the track's source material: 1 = mono law
|
|
1360
|
+
* (−3 dB per side at centre), 2+ = stereo law (unity at centre). */
|
|
1361
|
+
setSourceChannelCount(sourceChannelCount) {
|
|
1362
|
+
this._panStage.setSourceChannelCount(sourceChannelCount);
|
|
807
1363
|
}
|
|
808
1364
|
setMute(muted) {
|
|
809
1365
|
this._muteNode.gain.value = muted ? 0 : 1;
|
|
810
1366
|
}
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
1367
|
+
/**
|
|
1368
|
+
* Insert an effects chain between the track input and the fader:
|
|
1369
|
+
* `input → effectsInput … effectsOutput → volume`. The transport owns
|
|
1370
|
+
* BOTH edges — the caller only builds what lies between the two nodes
|
|
1371
|
+
* (pass the same node twice for a single-node effect). Replaces any
|
|
1372
|
+
* chain connected earlier.
|
|
1373
|
+
*/
|
|
1374
|
+
connectEffects(effectsInput, effectsOutput) {
|
|
1375
|
+
this.disconnectEffects();
|
|
1376
|
+
this._inputNode.disconnect();
|
|
1377
|
+
this._inputNode.connect(effectsInput);
|
|
1378
|
+
effectsOutput.connect(this._volumeNode);
|
|
1379
|
+
this._effects = { input: effectsInput, output: effectsOutput };
|
|
1380
|
+
}
|
|
1381
|
+
/** Remove the effects chain and restore `input → volume`. No-op without one. */
|
|
819
1382
|
disconnectEffects() {
|
|
820
|
-
if (this.
|
|
821
|
-
|
|
822
|
-
this._muteNode.connect(this._destination);
|
|
823
|
-
this._effectsInput = null;
|
|
1383
|
+
if (!this._effects) {
|
|
1384
|
+
return;
|
|
824
1385
|
}
|
|
1386
|
+
this._releaseEffectsReturn();
|
|
1387
|
+
this._inputNode.disconnect();
|
|
1388
|
+
this._inputNode.connect(this._volumeNode);
|
|
1389
|
+
this._effects = null;
|
|
825
1390
|
}
|
|
826
1391
|
dispose() {
|
|
827
|
-
|
|
1392
|
+
this._releaseEffectsReturn();
|
|
1393
|
+
this._effects = null;
|
|
1394
|
+
for (const node of [this._inputNode, this._volumeNode, this._muteNode]) {
|
|
828
1395
|
try {
|
|
829
1396
|
node.disconnect();
|
|
830
1397
|
} catch (err) {
|
|
831
|
-
console.warn(
|
|
832
|
-
"[waveform-playlist] TrackNode.dispose: error disconnecting node:",
|
|
833
|
-
String(err)
|
|
834
|
-
);
|
|
1398
|
+
console.warn(PREFIX + "TrackNode.dispose: error disconnecting node:", String(err));
|
|
835
1399
|
}
|
|
836
1400
|
}
|
|
1401
|
+
this._panStage.dispose();
|
|
1402
|
+
}
|
|
1403
|
+
/** Targeted disconnect of `effectsOutput → volume` — other consumers of
|
|
1404
|
+
* the chain's output (analyser taps) keep their edges. */
|
|
1405
|
+
_releaseEffectsReturn() {
|
|
1406
|
+
if (!this._effects) {
|
|
1407
|
+
return;
|
|
1408
|
+
}
|
|
1409
|
+
try {
|
|
1410
|
+
this._effects.output.disconnect(this._volumeNode);
|
|
1411
|
+
} catch (err) {
|
|
1412
|
+
console.warn(
|
|
1413
|
+
PREFIX + 'TrackNode: effects chain was already disconnected from track "' + this.id + '": ',
|
|
1414
|
+
String(err)
|
|
1415
|
+
);
|
|
1416
|
+
}
|
|
837
1417
|
}
|
|
838
1418
|
};
|
|
839
1419
|
|
|
@@ -850,6 +1430,10 @@ var ClipPlayer = class {
|
|
|
850
1430
|
this._tempoMap = tempoMap;
|
|
851
1431
|
this._toAudioTime = toAudioTime;
|
|
852
1432
|
}
|
|
1433
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1434
|
+
setTempoMap(tempoMap) {
|
|
1435
|
+
this._tempoMap = tempoMap;
|
|
1436
|
+
}
|
|
853
1437
|
setTracks(tracks, trackNodes) {
|
|
854
1438
|
this._tracks.clear();
|
|
855
1439
|
this._trackNodes = trackNodes;
|
|
@@ -1063,6 +1647,10 @@ var MetronomePlayer = class {
|
|
|
1063
1647
|
this._destination = destination;
|
|
1064
1648
|
this._toAudioTime = toAudioTime;
|
|
1065
1649
|
}
|
|
1650
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1651
|
+
setTempoMap(tempoMap) {
|
|
1652
|
+
this._tempoMap = tempoMap;
|
|
1653
|
+
}
|
|
1066
1654
|
setEnabled(enabled) {
|
|
1067
1655
|
this._enabled = enabled;
|
|
1068
1656
|
if (!enabled) {
|
|
@@ -1144,6 +1732,9 @@ var MetronomePlayer = class {
|
|
|
1144
1732
|
}
|
|
1145
1733
|
};
|
|
1146
1734
|
|
|
1735
|
+
// src/transport.ts
|
|
1736
|
+
var import_core2 = require("@waveform-playlist/core");
|
|
1737
|
+
|
|
1147
1738
|
// src/audio/count-in-player.ts
|
|
1148
1739
|
var CountInPlayer = class {
|
|
1149
1740
|
constructor(audioContext, tempoMap, destination, toAudioTime) {
|
|
@@ -1218,12 +1809,9 @@ var CountInPlayer = class {
|
|
|
1218
1809
|
});
|
|
1219
1810
|
const transportTime = this._tempoMap.ticksToSeconds(event.tick);
|
|
1220
1811
|
source.start(this._toAudioTime(transportTime));
|
|
1221
|
-
}
|
|
1222
|
-
|
|
1223
|
-
"[waveform-playlist] CountInPlayer.consume: failed to schedule beat " + event.beat + "/" + event.totalBeats + ": " + String(err)
|
|
1224
|
-
);
|
|
1812
|
+
} finally {
|
|
1813
|
+
this._onBeat?.(event.beat, event.totalBeats);
|
|
1225
1814
|
}
|
|
1226
|
-
this._onBeat?.(event.beat, event.totalBeats);
|
|
1227
1815
|
}
|
|
1228
1816
|
onPositionJump(_newTick) {
|
|
1229
1817
|
}
|
|
@@ -1289,6 +1877,11 @@ var _Transport = class _Transport {
|
|
|
1289
1877
|
this._soloedTrackIds = /* @__PURE__ */ new Set();
|
|
1290
1878
|
this._mutedTrackIds = /* @__PURE__ */ new Set();
|
|
1291
1879
|
this._playing = false;
|
|
1880
|
+
this._disposed = false;
|
|
1881
|
+
/** `Clock.rebaseCount` as of the last resync; a higher count means sources
|
|
1882
|
+
* armed in the old time base are still scheduled. */
|
|
1883
|
+
this._rebasesHandled = 0;
|
|
1884
|
+
this._warnedDiscontinuity = false;
|
|
1292
1885
|
this._loopEnabled = false;
|
|
1293
1886
|
this._loopStartTick = 0;
|
|
1294
1887
|
this._loopStartSeconds = 0;
|
|
@@ -1307,17 +1900,32 @@ var _Transport = class _Transport {
|
|
|
1307
1900
|
this._accentBuffer = null;
|
|
1308
1901
|
this._normalBuffer = null;
|
|
1309
1902
|
this._schedulerLookahead = 0.2;
|
|
1903
|
+
this._errorLog = new ListenerErrorLog("[waveform-playlist] Transport: ");
|
|
1310
1904
|
this._ppqn = 960;
|
|
1311
1905
|
this._audioContext = audioContext;
|
|
1906
|
+
if (!(Number.isFinite(audioContext.sampleRate) && audioContext.sampleRate > 0)) {
|
|
1907
|
+
throw new Error(
|
|
1908
|
+
"[waveform-playlist] Transport: the AudioContext must report a positive finite sampleRate, got " + audioContext.sampleRate
|
|
1909
|
+
);
|
|
1910
|
+
}
|
|
1312
1911
|
const sampleRate = options.sampleRate ?? audioContext.sampleRate;
|
|
1313
1912
|
const ppqn = options.ppqn ?? 960;
|
|
1314
1913
|
const tempo = options.tempo ?? 120;
|
|
1315
1914
|
const numerator = options.numerator ?? 4;
|
|
1316
1915
|
const denominator = options.denominator ?? 4;
|
|
1317
1916
|
const lookahead = options.schedulerLookahead ?? 0.2;
|
|
1917
|
+
const timerIntervalMs = options.timerIntervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
|
|
1318
1918
|
this._ppqn = ppqn;
|
|
1319
1919
|
this._schedulerLookahead = lookahead;
|
|
1320
|
-
_Transport._validateOptions(
|
|
1920
|
+
_Transport._validateOptions(
|
|
1921
|
+
sampleRate,
|
|
1922
|
+
ppqn,
|
|
1923
|
+
tempo,
|
|
1924
|
+
numerator,
|
|
1925
|
+
denominator,
|
|
1926
|
+
lookahead,
|
|
1927
|
+
timerIntervalMs
|
|
1928
|
+
);
|
|
1321
1929
|
this._clock = new Clock(audioContext);
|
|
1322
1930
|
this._sampleTimeline = new SampleTimeline(sampleRate);
|
|
1323
1931
|
this._meterMap = new MeterMap(ppqn, numerator, denominator);
|
|
@@ -1327,13 +1935,33 @@ var _Transport = class _Transport {
|
|
|
1327
1935
|
onLoop: (loopStartSeconds, loopEndSeconds, currentTimeSeconds) => {
|
|
1328
1936
|
const timeToBoundary = loopEndSeconds - currentTimeSeconds;
|
|
1329
1937
|
this._clock.seekTo(loopStartSeconds - timeToBoundary);
|
|
1330
|
-
}
|
|
1938
|
+
},
|
|
1939
|
+
onError: (error) => this._emitError(error)
|
|
1331
1940
|
});
|
|
1332
1941
|
this._sampleTimeline.setTempoMap(this._tempoMap);
|
|
1333
1942
|
this._initAudioGraph(audioContext);
|
|
1334
1943
|
this._initCountIn(audioContext, options);
|
|
1335
|
-
this._timer = new Timer(
|
|
1944
|
+
this._timer = new Timer(
|
|
1945
|
+
() => {
|
|
1946
|
+
try {
|
|
1947
|
+
this._tick();
|
|
1948
|
+
} catch (err) {
|
|
1949
|
+
this._onTickFailure(err);
|
|
1950
|
+
}
|
|
1951
|
+
},
|
|
1952
|
+
{ intervalMs: timerIntervalMs }
|
|
1953
|
+
);
|
|
1954
|
+
}
|
|
1955
|
+
/** One scheduling tick. Anything thrown here is a transport-internal
|
|
1956
|
+
* fault (not a listener failure — those are caught by the scheduler); the
|
|
1957
|
+
* wrapper above stops the transport rather than retrying it 40×/s. */
|
|
1958
|
+
_tick() {
|
|
1959
|
+
{
|
|
1336
1960
|
const time = this._clock.getTime();
|
|
1961
|
+
if (this._clock.rebaseCount !== this._rebasesHandled) {
|
|
1962
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
1963
|
+
this._resyncAfterDiscontinuity(time);
|
|
1964
|
+
}
|
|
1337
1965
|
if (this._countingIn) {
|
|
1338
1966
|
this._countInScheduler?.advance(time);
|
|
1339
1967
|
if (time >= this._countInDuration) {
|
|
@@ -1343,10 +1971,65 @@ var _Transport = class _Transport {
|
|
|
1343
1971
|
}
|
|
1344
1972
|
if (this._endTime !== void 0 && time >= this._endTime) {
|
|
1345
1973
|
this.stop();
|
|
1974
|
+
this._emit("ended");
|
|
1346
1975
|
return;
|
|
1347
1976
|
}
|
|
1348
1977
|
this._scheduler.advance(time);
|
|
1349
|
-
|
|
1978
|
+
this._emit("tick", { seconds: this.getCurrentTime() });
|
|
1979
|
+
}
|
|
1980
|
+
}
|
|
1981
|
+
/** The clock absorbed a backward context re-base since the last resync:
|
|
1982
|
+
* sources armed through the old anchor's toAudioTime() hold ABSOLUTE
|
|
1983
|
+
* context times and would now fire late by the shift. Outside a count-in,
|
|
1984
|
+
* re-create them from the held position (the seek-while-playing path minus
|
|
1985
|
+
* the move), clamped to loopStart like getCurrentTime() — right after a
|
|
1986
|
+
* wrap the clock sits behind loopStart and a resync from there would play
|
|
1987
|
+
* pre-loop material. During a count-in the clicks already armed are
|
|
1988
|
+
* dropped rather than regenerated (CountInPlayer counts beats, so a
|
|
1989
|
+
* regenerate would double-fire); the count-in→play transition is
|
|
1990
|
+
* clock-driven and still lands on the held clock. */
|
|
1991
|
+
_resyncAfterDiscontinuity(time) {
|
|
1992
|
+
const shiftSeconds = this._clock.frameToSeconds(this._clock.lastRebaseFrames);
|
|
1993
|
+
let seconds;
|
|
1994
|
+
if (this._countingIn) {
|
|
1995
|
+
this._countInPlayer.silence();
|
|
1996
|
+
seconds = this._countInStartPosition;
|
|
1997
|
+
} else {
|
|
1998
|
+
seconds = this._loopEnabled && time < this._loopStartSeconds ? this._loopStartSeconds : time;
|
|
1999
|
+
this._silenceAll();
|
|
2000
|
+
this._scheduler.reset(seconds);
|
|
2001
|
+
this._clipPlayer.onPositionJump(this._tempoMap.secondsToTicks(seconds));
|
|
2002
|
+
}
|
|
2003
|
+
const listeners = this._listeners.get("discontinuity");
|
|
2004
|
+
if (listeners && listeners.size > 0) {
|
|
2005
|
+
this._emit("discontinuity", { seconds, shiftSeconds });
|
|
2006
|
+
} else if (!this._warnedDiscontinuity) {
|
|
2007
|
+
this._warnedDiscontinuity = true;
|
|
2008
|
+
console.warn(
|
|
2009
|
+
"[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.'
|
|
2010
|
+
);
|
|
2011
|
+
}
|
|
2012
|
+
}
|
|
2013
|
+
/** Sources are (re)created from the current anchor here: any re-base
|
|
2014
|
+
* absorbed before this point concerns audio that no longer exists. */
|
|
2015
|
+
_markRebasesHandled() {
|
|
2016
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
2017
|
+
}
|
|
2018
|
+
/** A tick threw: warn once and stop, so the engine sees a `stop` and no
|
|
2019
|
+
* one is left looking at a "playing" transport that renders silence. */
|
|
2020
|
+
_onTickFailure(err) {
|
|
2021
|
+
console.warn(
|
|
2022
|
+
"[waveform-playlist] Transport: stopping \u2014 the scheduling tick threw: " + (err instanceof Error ? err.name + ": " + err.message + (err.stack ? "\n" + err.stack : "") : String(err))
|
|
2023
|
+
);
|
|
2024
|
+
try {
|
|
2025
|
+
this.stop();
|
|
2026
|
+
} catch (stopErr) {
|
|
2027
|
+
console.warn(
|
|
2028
|
+
"[waveform-playlist] Transport: stop() after a tick failure also threw: " + String(stopErr)
|
|
2029
|
+
);
|
|
2030
|
+
this._timer.stop();
|
|
2031
|
+
this._playing = false;
|
|
2032
|
+
}
|
|
1350
2033
|
}
|
|
1351
2034
|
get audioContext() {
|
|
1352
2035
|
return this._audioContext;
|
|
@@ -1354,8 +2037,16 @@ var _Transport = class _Transport {
|
|
|
1354
2037
|
get ppqn() {
|
|
1355
2038
|
return this._ppqn;
|
|
1356
2039
|
}
|
|
2040
|
+
/** The current tempo map. Immutable: every tempo edit swaps in a new map,
|
|
2041
|
+
* so a reference you hold keeps converting with the tempo it had. */
|
|
2042
|
+
get tempoMap() {
|
|
2043
|
+
return this._tempoMap;
|
|
2044
|
+
}
|
|
1357
2045
|
// --- Playback ---
|
|
1358
2046
|
play(startTime, endTime) {
|
|
2047
|
+
if (this._refuseIfDisposed("play")) return;
|
|
2048
|
+
if (startTime !== void 0) assertFiniteSeconds("play", "startTime", startTime);
|
|
2049
|
+
if (endTime !== void 0) assertFiniteSeconds("play", "endTime", endTime);
|
|
1359
2050
|
if (this._playing) return;
|
|
1360
2051
|
if (startTime !== void 0) {
|
|
1361
2052
|
this._clock.seekTo(startTime);
|
|
@@ -1370,6 +2061,7 @@ var _Transport = class _Transport {
|
|
|
1370
2061
|
this._scheduler.setPlayEnd(
|
|
1371
2062
|
endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
|
|
1372
2063
|
);
|
|
2064
|
+
this._markRebasesHandled();
|
|
1373
2065
|
this._clock.start();
|
|
1374
2066
|
const currentTick = this._tempoMap.secondsToTicks(currentTime);
|
|
1375
2067
|
this._clipPlayer.onPositionJump(currentTick);
|
|
@@ -1409,6 +2101,8 @@ var _Transport = class _Transport {
|
|
|
1409
2101
|
}
|
|
1410
2102
|
}
|
|
1411
2103
|
seek(time) {
|
|
2104
|
+
if (this._refuseIfDisposed("seek")) return;
|
|
2105
|
+
assertFiniteSeconds("seek", "time", time);
|
|
1412
2106
|
const wasPlaying = this._playing;
|
|
1413
2107
|
const wasCountingIn = this._countingIn;
|
|
1414
2108
|
if (wasCountingIn) {
|
|
@@ -1420,6 +2114,7 @@ var _Transport = class _Transport {
|
|
|
1420
2114
|
}
|
|
1421
2115
|
this._silenceAll();
|
|
1422
2116
|
this._clock.seekTo(time);
|
|
2117
|
+
this._markRebasesHandled();
|
|
1423
2118
|
this._scheduler.reset(time);
|
|
1424
2119
|
this._endTime = void 0;
|
|
1425
2120
|
this._scheduler.setPlayEnd(null);
|
|
@@ -1441,6 +2136,32 @@ var _Transport = class _Transport {
|
|
|
1441
2136
|
}
|
|
1442
2137
|
return t;
|
|
1443
2138
|
}
|
|
2139
|
+
/** Current position in whole AudioContext frames (the clock's native unit
|
|
2140
|
+
* for elapsed time). Same loop-wrap clamp and count-in hold as
|
|
2141
|
+
* getCurrentTime(). CONTEXT-rate frames — `getCurrentSample()` is the
|
|
2142
|
+
* timeline-rate view. */
|
|
2143
|
+
getCurrentFrame() {
|
|
2144
|
+
if (this._countingIn) {
|
|
2145
|
+
return this._clock.secondsToFrame(this._countInStartPosition);
|
|
2146
|
+
}
|
|
2147
|
+
const frame = this._clock.getFrame();
|
|
2148
|
+
const loopStartFrame = this._clock.secondsToFrame(this._loopStartSeconds);
|
|
2149
|
+
if (this._loopEnabled && frame < loopStartFrame) {
|
|
2150
|
+
return loopStartFrame;
|
|
2151
|
+
}
|
|
2152
|
+
return frame;
|
|
2153
|
+
}
|
|
2154
|
+
/** Current position in SampleTimeline samples (the `sampleRate` option's
|
|
2155
|
+
* rate; equal to getCurrentFrame() only when that matches the context).
|
|
2156
|
+
* Rounded once, at the Sample boundary. */
|
|
2157
|
+
getCurrentSample() {
|
|
2158
|
+
return this._sampleTimeline.secondsToSamples(this.getCurrentTime());
|
|
2159
|
+
}
|
|
2160
|
+
/** How many backward AudioContext clock readings the transport has absorbed
|
|
2161
|
+
* (see the `discontinuity` event). Diagnostics. */
|
|
2162
|
+
get rebaseCount() {
|
|
2163
|
+
return this._clock.rebaseCount;
|
|
2164
|
+
}
|
|
1444
2165
|
isPlaying() {
|
|
1445
2166
|
return this._playing;
|
|
1446
2167
|
}
|
|
@@ -1454,7 +2175,7 @@ var _Transport = class _Transport {
|
|
|
1454
2175
|
this._mutedTrackIds.clear();
|
|
1455
2176
|
this._tracks = tracks;
|
|
1456
2177
|
for (const track of tracks) {
|
|
1457
|
-
const trackNode = new TrackNode(track.id, this._audioContext);
|
|
2178
|
+
const trackNode = new TrackNode(track.id, this._audioContext, (0, import_core2.trackChannelCount)(track));
|
|
1458
2179
|
trackNode.setVolume(track.volume);
|
|
1459
2180
|
trackNode.setPan(track.pan);
|
|
1460
2181
|
trackNode.connectOutput(this._masterNode.input);
|
|
@@ -1470,7 +2191,7 @@ var _Transport = class _Transport {
|
|
|
1470
2191
|
this._clipPlayer.setTracks(tracks, this._trackNodes);
|
|
1471
2192
|
}
|
|
1472
2193
|
addTrack(track) {
|
|
1473
|
-
const trackNode = new TrackNode(track.id, this._audioContext);
|
|
2194
|
+
const trackNode = new TrackNode(track.id, this._audioContext, (0, import_core2.trackChannelCount)(track));
|
|
1474
2195
|
trackNode.setVolume(track.volume);
|
|
1475
2196
|
trackNode.setPan(track.pan);
|
|
1476
2197
|
trackNode.connectOutput(this._masterNode.input);
|
|
@@ -1503,6 +2224,7 @@ var _Transport = class _Transport {
|
|
|
1503
2224
|
if (node) {
|
|
1504
2225
|
node.setVolume(track.volume);
|
|
1505
2226
|
node.setPan(track.pan);
|
|
2227
|
+
node.setSourceChannelCount((0, import_core2.trackChannelCount)(track));
|
|
1506
2228
|
}
|
|
1507
2229
|
if (track.muted) {
|
|
1508
2230
|
this._mutedTrackIds.add(trackId);
|
|
@@ -1555,14 +2277,12 @@ var _Transport = class _Transport {
|
|
|
1555
2277
|
this._masterNode.setVolume(volume);
|
|
1556
2278
|
}
|
|
1557
2279
|
// --- Loop ---
|
|
1558
|
-
/** Primary loop API — ticks as source of truth
|
|
2280
|
+
/** Primary loop API — ticks as source of truth. Throws when `enabled` and
|
|
2281
|
+
* the range is non-finite, empty or inverted; nothing is changed and no
|
|
2282
|
+
* `loop` event fires. (NativePlayoutAdapter translates the engine's
|
|
2283
|
+
* default empty region to a disabled loop before reaching here.) */
|
|
1559
2284
|
setLoop(enabled, startTick, endTick) {
|
|
1560
|
-
|
|
1561
|
-
console.warn(
|
|
1562
|
-
"[waveform-playlist] Transport.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
|
|
1563
|
-
);
|
|
1564
|
-
return;
|
|
1565
|
-
}
|
|
2285
|
+
assertValidLoopRange("Transport.setLoop", enabled, startTick, endTick, "tick");
|
|
1566
2286
|
this._loopEnabled = enabled;
|
|
1567
2287
|
this._loopStartTick = startTick;
|
|
1568
2288
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1570,28 +2290,37 @@ var _Transport = class _Transport {
|
|
|
1570
2290
|
this._clipPlayer.setLoop(enabled, startTick, endTick);
|
|
1571
2291
|
this._emit("loop");
|
|
1572
2292
|
}
|
|
1573
|
-
/** Convenience — converts seconds to ticks
|
|
2293
|
+
/** Convenience — converts seconds to ticks. Same validation as setLoop,
|
|
2294
|
+
* applied in seconds so the error names the caller's unit. */
|
|
1574
2295
|
setLoopSeconds(enabled, startSec, endSec) {
|
|
2296
|
+
assertValidLoopRange("Transport.setLoopSeconds", enabled, startSec, endSec, "second");
|
|
1575
2297
|
const startTick = this._tempoMap.secondsToTicks(startSec);
|
|
1576
2298
|
const endTick = this._tempoMap.secondsToTicks(endSec);
|
|
2299
|
+
assertLoopRangeSpansATick(
|
|
2300
|
+
"Transport.setLoopSeconds",
|
|
2301
|
+
enabled,
|
|
2302
|
+
startSec,
|
|
2303
|
+
endSec,
|
|
2304
|
+
"second",
|
|
2305
|
+
startTick,
|
|
2306
|
+
endTick
|
|
2307
|
+
);
|
|
1577
2308
|
this.setLoop(enabled, startTick, endTick);
|
|
1578
2309
|
}
|
|
1579
|
-
/** Convenience — sets loop in samples */
|
|
2310
|
+
/** Convenience — sets loop in samples. Same validation as setLoop. */
|
|
1580
2311
|
setLoopSamples(enabled, startSample, endSample) {
|
|
1581
|
-
|
|
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
|
-
}
|
|
2312
|
+
assertValidLoopRange("Transport.setLoopSamples", enabled, startSample, endSample, "sample");
|
|
1593
2313
|
const startTick = this._sampleTimeline.samplesToTicks(startSample);
|
|
1594
2314
|
const endTick = this._sampleTimeline.samplesToTicks(endSample);
|
|
2315
|
+
assertLoopRangeSpansATick(
|
|
2316
|
+
"Transport.setLoopSamples",
|
|
2317
|
+
enabled,
|
|
2318
|
+
startSample,
|
|
2319
|
+
endSample,
|
|
2320
|
+
"sample",
|
|
2321
|
+
startTick,
|
|
2322
|
+
endTick
|
|
2323
|
+
);
|
|
1595
2324
|
this._loopEnabled = enabled;
|
|
1596
2325
|
this._loopStartTick = startTick;
|
|
1597
2326
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1610,7 +2339,7 @@ var _Transport = class _Transport {
|
|
|
1610
2339
|
);
|
|
1611
2340
|
return false;
|
|
1612
2341
|
}
|
|
1613
|
-
this._tempoMap.
|
|
2342
|
+
this._replaceTempoMap(this._tempoMap.withTempo(bpm, atTick, options));
|
|
1614
2343
|
if (this._loopEnabled) {
|
|
1615
2344
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1616
2345
|
}
|
|
@@ -1647,7 +2376,7 @@ var _Transport = class _Transport {
|
|
|
1647
2376
|
});
|
|
1648
2377
|
}
|
|
1649
2378
|
clearTempos() {
|
|
1650
|
-
this._tempoMap.
|
|
2379
|
+
this._replaceTempoMap(this._tempoMap.withoutTempos());
|
|
1651
2380
|
if (this._loopEnabled) {
|
|
1652
2381
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1653
2382
|
}
|
|
@@ -1658,7 +2387,7 @@ var _Transport = class _Transport {
|
|
|
1658
2387
|
* invalidation and event; the emitted bpm is the tempo now in force at
|
|
1659
2388
|
* the removed position. */
|
|
1660
2389
|
removeTempo(atTick) {
|
|
1661
|
-
this._tempoMap.
|
|
2390
|
+
this._replaceTempoMap(this._tempoMap.withoutTempo(atTick));
|
|
1662
2391
|
if (this._loopEnabled) {
|
|
1663
2392
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1664
2393
|
}
|
|
@@ -1667,14 +2396,28 @@ var _Transport = class _Transport {
|
|
|
1667
2396
|
barToTick(bar) {
|
|
1668
2397
|
return this._meterMap.barToTick(bar);
|
|
1669
2398
|
}
|
|
2399
|
+
/** Snap a (possibly fractional) tick to the meter grid: `subdivision` is
|
|
2400
|
+
* `{ ticks }`, `{ note, dotted?, triplet? }`, 'bar' or 'beat'; `mode` is
|
|
2401
|
+
* 'nearest' (default) | 'next' | 'previous'; `strength` 0–1 scales the
|
|
2402
|
+
* move. Grid lines restart at each bar line, so odd meters stay aligned.
|
|
2403
|
+
* Pure function over the (live) MeterMap. */
|
|
2404
|
+
quantizeTick(tick, subdivision, options) {
|
|
2405
|
+
return quantizeTick(this._meterMap, tick, subdivision, options);
|
|
2406
|
+
}
|
|
1670
2407
|
tickToBar(tick) {
|
|
1671
2408
|
return this._meterMap.tickToBar(tick);
|
|
1672
2409
|
}
|
|
1673
|
-
/** Convert transport time (seconds) to tick position, using the tempo map. */
|
|
2410
|
+
/** Convert transport time (seconds) to an integer tick position, using the tempo map. */
|
|
1674
2411
|
timeToTick(seconds) {
|
|
1675
2412
|
return this._tempoMap.secondsToTicks(seconds);
|
|
1676
2413
|
}
|
|
1677
|
-
/** Convert
|
|
2414
|
+
/** Convert transport time (seconds) to a fractional tick position — for
|
|
2415
|
+
* sub-tick placement (e.g. a recorded note between ticks, before quantising). */
|
|
2416
|
+
timeToTickExact(seconds) {
|
|
2417
|
+
return this._tempoMap.secondsToTicksExact(seconds);
|
|
2418
|
+
}
|
|
2419
|
+
/** Convert a tick position (integer Tick or the fractional value
|
|
2420
|
+
* timeToTickExact returned) to transport time (seconds). */
|
|
1678
2421
|
tickToTime(tick) {
|
|
1679
2422
|
return this._tempoMap.ticksToSeconds(tick);
|
|
1680
2423
|
}
|
|
@@ -1718,18 +2461,30 @@ var _Transport = class _Transport {
|
|
|
1718
2461
|
return this._countingIn;
|
|
1719
2462
|
}
|
|
1720
2463
|
// --- Effects Hook ---
|
|
1721
|
-
|
|
2464
|
+
/**
|
|
2465
|
+
* Insert an effects chain on a track, PRE-FADER: clip sources → `input` …
|
|
2466
|
+
* `output` → volume → pan → mute → master. Accepts any AudioNode chain
|
|
2467
|
+
* (native nodes, WAM plugins, Tone.js effects) — pass the same node twice
|
|
2468
|
+
* for a single-node effect. The transport owns both edges; do NOT connect
|
|
2469
|
+
* `output` to the master bus yourself (that would bypass the fader, pan
|
|
2470
|
+
* and mute). Calling again replaces the previous chain.
|
|
2471
|
+
*
|
|
2472
|
+
* `setTracks()` rebuilds every track node, dropping these hookups —
|
|
2473
|
+
* reconnect afterwards.
|
|
2474
|
+
*/
|
|
2475
|
+
connectTrackEffects(trackId, input, output) {
|
|
1722
2476
|
const trackNode = this._trackNodes.get(trackId);
|
|
1723
2477
|
if (!trackNode) {
|
|
1724
|
-
console.warn('[waveform-playlist]
|
|
2478
|
+
console.warn('[waveform-playlist] connectTrackEffects: unknown trackId "' + trackId + '"');
|
|
1725
2479
|
return;
|
|
1726
2480
|
}
|
|
1727
|
-
trackNode.connectEffects(
|
|
2481
|
+
trackNode.connectEffects(input, output);
|
|
1728
2482
|
}
|
|
1729
|
-
|
|
2483
|
+
/** Remove a track's effects chain and restore its direct routing. */
|
|
2484
|
+
disconnectTrackEffects(trackId) {
|
|
1730
2485
|
const trackNode = this._trackNodes.get(trackId);
|
|
1731
2486
|
if (!trackNode) {
|
|
1732
|
-
console.warn('[waveform-playlist]
|
|
2487
|
+
console.warn('[waveform-playlist] disconnectTrackEffects: unknown trackId "' + trackId + '"');
|
|
1733
2488
|
return;
|
|
1734
2489
|
}
|
|
1735
2490
|
trackNode.disconnectEffects();
|
|
@@ -1766,18 +2521,20 @@ var _Transport = class _Transport {
|
|
|
1766
2521
|
// --- Dispose ---
|
|
1767
2522
|
dispose() {
|
|
1768
2523
|
this.stop();
|
|
2524
|
+
this._disposed = true;
|
|
1769
2525
|
for (const node of this._trackNodes.values()) {
|
|
1770
2526
|
node.dispose();
|
|
1771
2527
|
}
|
|
1772
2528
|
this._trackNodes.clear();
|
|
1773
2529
|
this._masterNode.dispose();
|
|
2530
|
+
this._timer.dispose();
|
|
1774
2531
|
this._listeners.clear();
|
|
1775
2532
|
}
|
|
1776
2533
|
// --- Private ---
|
|
1777
|
-
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead) {
|
|
1778
|
-
if (sampleRate
|
|
2534
|
+
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead, timerIntervalMs) {
|
|
2535
|
+
if (!(Number.isFinite(sampleRate) && sampleRate > 0)) {
|
|
1779
2536
|
throw new Error(
|
|
1780
|
-
"[waveform-playlist] Transport: sampleRate must be positive, got " + sampleRate
|
|
2537
|
+
"[waveform-playlist] Transport: options.sampleRate must be a positive finite number, got " + sampleRate
|
|
1781
2538
|
);
|
|
1782
2539
|
}
|
|
1783
2540
|
if (ppqn <= 0 || !Number.isInteger(ppqn)) {
|
|
@@ -1803,6 +2560,11 @@ var _Transport = class _Transport {
|
|
|
1803
2560
|
"[waveform-playlist] Transport: schedulerLookahead must be positive, got " + lookahead
|
|
1804
2561
|
);
|
|
1805
2562
|
}
|
|
2563
|
+
if (!(timerIntervalMs > 0) || timerIntervalMs >= lookahead * 1e3) {
|
|
2564
|
+
throw new Error(
|
|
2565
|
+
"[waveform-playlist] Transport: timerIntervalMs must be positive and shorter than the lookahead (" + lookahead * 1e3 + " ms), got " + timerIntervalMs
|
|
2566
|
+
);
|
|
2567
|
+
}
|
|
1806
2568
|
}
|
|
1807
2569
|
_initAudioGraph(audioContext) {
|
|
1808
2570
|
this._masterNode = new MasterNode(audioContext);
|
|
@@ -1874,7 +2636,8 @@ var _Transport = class _Transport {
|
|
|
1874
2636
|
const countInMeterMap = new MeterMap(this._ppqn, meter.numerator, meter.denominator);
|
|
1875
2637
|
this._countInDuration = countInTempoMap.ticksToSeconds(countInTicks);
|
|
1876
2638
|
this._countInScheduler = new Scheduler(countInTempoMap, {
|
|
1877
|
-
lookahead: this._schedulerLookahead
|
|
2639
|
+
lookahead: this._schedulerLookahead,
|
|
2640
|
+
onError: (error) => this._emitError(error)
|
|
1878
2641
|
});
|
|
1879
2642
|
this._countInPlayer.configure({
|
|
1880
2643
|
totalBeats,
|
|
@@ -1889,6 +2652,7 @@ var _Transport = class _Transport {
|
|
|
1889
2652
|
this._countInScheduler.addListener(this._countInPlayer);
|
|
1890
2653
|
this._countInScheduler.reset(0);
|
|
1891
2654
|
this._clock.seekTo(0);
|
|
2655
|
+
this._markRebasesHandled();
|
|
1892
2656
|
this._clock.start();
|
|
1893
2657
|
this._timer.start();
|
|
1894
2658
|
}
|
|
@@ -1911,6 +2675,28 @@ var _Transport = class _Transport {
|
|
|
1911
2675
|
this._countingIn = false;
|
|
1912
2676
|
this._timer.stop();
|
|
1913
2677
|
}
|
|
2678
|
+
/** Install a new immutable TempoMap everywhere one is held. The count-in
|
|
2679
|
+
* player is configured with its own dedicated map at each count-in start,
|
|
2680
|
+
* so it is not on this list. */
|
|
2681
|
+
_replaceTempoMap(next) {
|
|
2682
|
+
this._tempoMap = next;
|
|
2683
|
+
this._scheduler.setTempoMap(next);
|
|
2684
|
+
this._sampleTimeline.setTempoMap(next);
|
|
2685
|
+
this._clipPlayer.setTempoMap(next);
|
|
2686
|
+
this._metronomePlayer.setTempoMap(next);
|
|
2687
|
+
if (this._endTime !== void 0) {
|
|
2688
|
+
this._scheduler.setPlayEnd(next.secondsToTicks(this._endTime));
|
|
2689
|
+
}
|
|
2690
|
+
}
|
|
2691
|
+
/** A disposed transport has no timer or audio graph; a late play()/seek()
|
|
2692
|
+
* must not report "playing" with nothing ticking. */
|
|
2693
|
+
_refuseIfDisposed(what) {
|
|
2694
|
+
if (!this._disposed) return false;
|
|
2695
|
+
console.warn(
|
|
2696
|
+
"[waveform-playlist] Transport: " + what + "() on a disposed transport is ignored"
|
|
2697
|
+
);
|
|
2698
|
+
return true;
|
|
2699
|
+
}
|
|
1914
2700
|
_silenceAll() {
|
|
1915
2701
|
this._clipPlayer.silence();
|
|
1916
2702
|
this._metronomePlayer.silence();
|
|
@@ -1924,6 +2710,22 @@ var _Transport = class _Transport {
|
|
|
1924
2710
|
node.setMute(isExplicitlyMuted || isSoloMuted);
|
|
1925
2711
|
}
|
|
1926
2712
|
}
|
|
2713
|
+
/** Route a scheduler listener failure to `error` subscribers, or to
|
|
2714
|
+
* console.warn (once per listener and failure kind) when nobody is listening —
|
|
2715
|
+
* the failure must stay visible either way. Subscribers are called on a
|
|
2716
|
+
* microtask, after the scheduler window that produced the failure has
|
|
2717
|
+
* completed: a handler that reacts with stop()/setTracks()/off() must not
|
|
2718
|
+
* re-enter the listener iteration that is still running. */
|
|
2719
|
+
_emitError(error) {
|
|
2720
|
+
queueMicrotask(() => {
|
|
2721
|
+
const listeners = this._listeners.get("error");
|
|
2722
|
+
if (listeners && listeners.size > 0) {
|
|
2723
|
+
this._emit("error", error);
|
|
2724
|
+
} else {
|
|
2725
|
+
this._errorLog.warnOnce(error);
|
|
2726
|
+
}
|
|
2727
|
+
});
|
|
2728
|
+
}
|
|
1927
2729
|
_emit(event, ...args) {
|
|
1928
2730
|
const listeners = this._listeners.get(event);
|
|
1929
2731
|
if (listeners) {
|
|
@@ -1944,12 +2746,21 @@ var _Transport = class _Transport {
|
|
|
1944
2746
|
_Transport.MIN_COUNT_IN_BARS = 1;
|
|
1945
2747
|
_Transport.MAX_COUNT_IN_BARS = 8;
|
|
1946
2748
|
var Transport = _Transport;
|
|
2749
|
+
function assertFiniteSeconds(method, name, value) {
|
|
2750
|
+
if (!Number.isFinite(value)) {
|
|
2751
|
+
throw new Error(
|
|
2752
|
+
"[waveform-playlist] Transport." + method + ": " + name + " must be finite, got " + value
|
|
2753
|
+
);
|
|
2754
|
+
}
|
|
2755
|
+
}
|
|
1947
2756
|
|
|
1948
2757
|
// src/adapter.ts
|
|
1949
2758
|
var NativePlayoutAdapter = class {
|
|
1950
2759
|
constructor(audioContext, options) {
|
|
2760
|
+
this._onPlaybackEnded = null;
|
|
1951
2761
|
this._audioContext = audioContext;
|
|
1952
2762
|
this._transport = new Transport(audioContext, options);
|
|
2763
|
+
this._transport.on("ended", () => this._onPlaybackEnded?.());
|
|
1953
2764
|
}
|
|
1954
2765
|
get audioContext() {
|
|
1955
2766
|
return this._audioContext;
|
|
@@ -1970,21 +2781,26 @@ var NativePlayoutAdapter = class {
|
|
|
1970
2781
|
const warmupTarget = Math.max(MIN_WARMUP, this._audioContext.outputLatency ?? MIN_WARMUP);
|
|
1971
2782
|
if (this._audioContext.currentTime < warmupTarget) {
|
|
1972
2783
|
const MAX_WARMUP_MS = 2e3;
|
|
1973
|
-
|
|
2784
|
+
const WARMUP_POLL_MS = 16;
|
|
2785
|
+
await new Promise((resolve, reject) => {
|
|
1974
2786
|
const startMs = performance.now();
|
|
1975
2787
|
const check = () => {
|
|
1976
2788
|
if (this._audioContext.currentTime >= warmupTarget) {
|
|
1977
2789
|
resolve();
|
|
1978
|
-
} else if (this._audioContext.state === "closed"
|
|
2790
|
+
} else if (this._audioContext.state === "closed") {
|
|
2791
|
+
reject(
|
|
2792
|
+
new Error("[waveform-playlist] Cannot init: AudioContext closed during warmup")
|
|
2793
|
+
);
|
|
2794
|
+
} else if (performance.now() - startMs > MAX_WARMUP_MS) {
|
|
1979
2795
|
console.warn(
|
|
1980
2796
|
"[waveform-playlist] AudioContext warmup timed out (currentTime=" + this._audioContext.currentTime + ", target=" + warmupTarget + ", state=" + this._audioContext.state + "). Proceeding without warmup."
|
|
1981
2797
|
);
|
|
1982
2798
|
resolve();
|
|
1983
2799
|
} else {
|
|
1984
|
-
|
|
2800
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1985
2801
|
}
|
|
1986
2802
|
};
|
|
1987
|
-
|
|
2803
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1988
2804
|
});
|
|
1989
2805
|
}
|
|
1990
2806
|
}
|
|
@@ -2010,6 +2826,13 @@ var NativePlayoutAdapter = class {
|
|
|
2010
2826
|
stop() {
|
|
2011
2827
|
this._transport.stop();
|
|
2012
2828
|
}
|
|
2829
|
+
/** Engine hook: adapter-initiated completion of a bounded play(start, end)
|
|
2830
|
+
* (the transport's `ended` event). Never fired for a consumer
|
|
2831
|
+
* stop()/pause()/seek()/dispose(), whether issued through this adapter or
|
|
2832
|
+
* directly on `adapter.transport`. */
|
|
2833
|
+
onPlaybackEnded(callback) {
|
|
2834
|
+
this._onPlaybackEnded = callback;
|
|
2835
|
+
}
|
|
2013
2836
|
seek(time) {
|
|
2014
2837
|
this._transport.seek(time);
|
|
2015
2838
|
}
|
|
@@ -2035,7 +2858,13 @@ var NativePlayoutAdapter = class {
|
|
|
2035
2858
|
this._transport.setTrackPan(trackId, pan);
|
|
2036
2859
|
}
|
|
2037
2860
|
setLoop(enabled, start, end) {
|
|
2038
|
-
|
|
2861
|
+
const finite = Number.isFinite(start) && Number.isFinite(end);
|
|
2862
|
+
const degenerate = enabled && finite && this._transport.timeToTick(start) >= this._transport.timeToTick(end);
|
|
2863
|
+
if (degenerate && !(start === 0 && end === 0)) {
|
|
2864
|
+
const why = start > end ? "inverted loop region (" + start + " > " + end + ")" : start === end ? "empty loop region (" + start + ")" : "loop region (" + start + ", " + end + ") is shorter than one tick";
|
|
2865
|
+
console.warn("[waveform-playlist] NativePlayoutAdapter.setLoop: " + why + " \u2014 loop disabled");
|
|
2866
|
+
}
|
|
2867
|
+
this._transport.setLoopSeconds(enabled && !degenerate, start, end);
|
|
2039
2868
|
}
|
|
2040
2869
|
setCountIn(enabled) {
|
|
2041
2870
|
this._transport.setCountIn(enabled);
|
|
@@ -2068,10 +2897,15 @@ var NativePlayoutAdapter = class {
|
|
|
2068
2897
|
secondsToTicks(seconds) {
|
|
2069
2898
|
return this._transport.timeToTick(seconds);
|
|
2070
2899
|
}
|
|
2900
|
+
/** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
|
|
2901
|
+
secondsToTicksExact(seconds) {
|
|
2902
|
+
return this._transport.timeToTickExact(seconds);
|
|
2903
|
+
}
|
|
2071
2904
|
get masterOutputNode() {
|
|
2072
2905
|
return this._transport.masterOutputNode;
|
|
2073
2906
|
}
|
|
2074
2907
|
dispose() {
|
|
2908
|
+
this._onPlaybackEnded = null;
|
|
2075
2909
|
this._transport.dispose();
|
|
2076
2910
|
}
|
|
2077
2911
|
};
|
|
@@ -2079,15 +2913,18 @@ var NativePlayoutAdapter = class {
|
|
|
2079
2913
|
0 && (module.exports = {
|
|
2080
2914
|
ClipPlayer,
|
|
2081
2915
|
Clock,
|
|
2916
|
+
DEFAULT_TIMER_INTERVAL_MS,
|
|
2082
2917
|
MasterNode,
|
|
2083
2918
|
MeterMap,
|
|
2084
2919
|
MetronomePlayer,
|
|
2085
2920
|
NativePlayoutAdapter,
|
|
2921
|
+
RENDER_QUANTUM_FRAMES,
|
|
2086
2922
|
SampleTimeline,
|
|
2087
2923
|
Scheduler,
|
|
2088
2924
|
TempoMap,
|
|
2089
2925
|
Timer,
|
|
2090
2926
|
TrackNode,
|
|
2091
|
-
Transport
|
|
2927
|
+
Transport,
|
|
2928
|
+
quantizeTick
|
|
2092
2929
|
});
|
|
2093
2930
|
//# sourceMappingURL=index.js.map
|