@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.mjs
CHANGED
|
@@ -1,53 +1,211 @@
|
|
|
1
1
|
// src/core/clock.ts
|
|
2
|
+
var RENDER_QUANTUM_FRAMES = 128;
|
|
3
|
+
var LATTICE_SNAP_FRAMES = 1e-3;
|
|
2
4
|
var Clock = class {
|
|
3
5
|
constructor(audioContext) {
|
|
4
6
|
this._running = false;
|
|
5
|
-
|
|
6
|
-
this.
|
|
7
|
+
/** Snapped context frame when the current run was anchored. */
|
|
8
|
+
this._contextFrameAtAnchor = 0;
|
|
9
|
+
/** Position at the last seek, in frames (fractional after a seconds seek). */
|
|
10
|
+
this._seekFrames = 0;
|
|
11
|
+
/** The same position in seconds — bit-exactly what seekTo(seconds) got. */
|
|
12
|
+
this._seekSeconds = 0;
|
|
13
|
+
/** Whole frames elapsed in earlier runs since the last seek. */
|
|
14
|
+
this._elapsedBeforeAnchor = 0;
|
|
15
|
+
/** The PREVIOUS snapped context reading (not a high-water mark): a lower
|
|
16
|
+
* reading than this one, while running, is a re-base. */
|
|
17
|
+
this._lastContextFrame = -Infinity;
|
|
18
|
+
this._rebaseCount = 0;
|
|
19
|
+
this._lastRebaseFrames = 0;
|
|
20
|
+
const rate = audioContext.sampleRate;
|
|
21
|
+
if (!(Number.isFinite(rate) && rate > 0)) {
|
|
22
|
+
throw new Error(
|
|
23
|
+
"[waveform-playlist] Clock: audioContext.sampleRate must be a positive finite number, got " + rate
|
|
24
|
+
);
|
|
25
|
+
}
|
|
7
26
|
this._audioContext = audioContext;
|
|
27
|
+
this._sampleRate = rate;
|
|
28
|
+
}
|
|
29
|
+
/** The rate frames are counted in: the AudioContext's. */
|
|
30
|
+
get sampleRate() {
|
|
31
|
+
return this._sampleRate;
|
|
32
|
+
}
|
|
33
|
+
/** How many backward context readings were absorbed while running. The
|
|
34
|
+
* Transport diffs this against its own cursor each tick to re-create
|
|
35
|
+
* sources armed in the old time base; observers may read it freely. */
|
|
36
|
+
get rebaseCount() {
|
|
37
|
+
return this._rebaseCount;
|
|
38
|
+
}
|
|
39
|
+
/** Size (frames) of the most recently absorbed backward reading. */
|
|
40
|
+
get lastRebaseFrames() {
|
|
41
|
+
return this._lastRebaseFrames;
|
|
42
|
+
}
|
|
43
|
+
/** Seconds → whole context frames, rounded once here. */
|
|
44
|
+
secondsToFrame(seconds) {
|
|
45
|
+
return Math.round(seconds * this._sampleRate);
|
|
46
|
+
}
|
|
47
|
+
/** Whole context frames → seconds (the inverse view). */
|
|
48
|
+
frameToSeconds(frame) {
|
|
49
|
+
return frame / this._sampleRate;
|
|
8
50
|
}
|
|
9
51
|
start() {
|
|
10
52
|
if (this._running) return;
|
|
11
|
-
this.
|
|
53
|
+
this._contextFrameAtAnchor = this._readContextFrame();
|
|
12
54
|
this._running = true;
|
|
13
55
|
}
|
|
14
56
|
stop() {
|
|
15
57
|
if (!this._running) return;
|
|
16
|
-
this.
|
|
58
|
+
this._elapsedBeforeAnchor += this._elapsedFrames();
|
|
17
59
|
this._running = false;
|
|
18
60
|
}
|
|
19
61
|
reset() {
|
|
20
62
|
this._running = false;
|
|
21
|
-
this.
|
|
22
|
-
this.
|
|
63
|
+
this._seekFrames = 0;
|
|
64
|
+
this._seekSeconds = 0;
|
|
65
|
+
this._elapsedBeforeAnchor = 0;
|
|
66
|
+
this._contextFrameAtAnchor = 0;
|
|
23
67
|
}
|
|
68
|
+
/** Position in seconds: the exact seek target plus whole elapsed frames. */
|
|
24
69
|
getTime() {
|
|
25
|
-
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
70
|
+
return this._seekSeconds + this._totalElapsedFrames() / this._sampleRate;
|
|
71
|
+
}
|
|
72
|
+
/** Position in whole context frames (rounded once, here). */
|
|
73
|
+
getFrame() {
|
|
74
|
+
return Math.round(this.getFrameExact());
|
|
75
|
+
}
|
|
76
|
+
/** Position in frames, keeping any sub-frame part a seconds seek introduced. */
|
|
77
|
+
getFrameExact() {
|
|
78
|
+
return this._seekFrames + this._totalElapsedFrames();
|
|
29
79
|
}
|
|
30
80
|
seekTo(time) {
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
81
|
+
assertFinite("seekTo", time);
|
|
82
|
+
this._seekToPosition(time * this._sampleRate, time);
|
|
83
|
+
}
|
|
84
|
+
/** A fractional frame is rounded here, at the API boundary. */
|
|
85
|
+
seekToFrame(frame) {
|
|
86
|
+
assertFinite("seekToFrame", frame);
|
|
87
|
+
const whole = Math.round(frame);
|
|
88
|
+
this._seekToPosition(whole, whole / this._sampleRate);
|
|
37
89
|
}
|
|
38
90
|
/**
|
|
39
|
-
* Convert transport time to AudioContext.currentTime space
|
|
40
|
-
*
|
|
91
|
+
* Convert transport time to AudioContext.currentTime space, for
|
|
92
|
+
* AudioBufferSourceNode.start(when). Anchor-based in both states: while
|
|
93
|
+
* running it never re-reads currentTime, so sub-quantum noise in a reading
|
|
94
|
+
* cannot shift scheduled events; stopped, the anchor is the same snapped
|
|
95
|
+
* "now" that start() is about to capture, so a `when` computed just before
|
|
96
|
+
* start() and one computed just after are identical.
|
|
41
97
|
*/
|
|
42
98
|
toAudioTime(transportTime) {
|
|
43
|
-
|
|
99
|
+
const positionFrames = transportTime * this._sampleRate;
|
|
100
|
+
const anchorFrame = this._running ? this._contextFrameAtAnchor : this._snappedContextFrame();
|
|
101
|
+
return (anchorFrame + (positionFrames - this._positionAtAnchorFrames())) / this._sampleRate;
|
|
44
102
|
}
|
|
45
103
|
isRunning() {
|
|
46
104
|
return this._running;
|
|
47
105
|
}
|
|
106
|
+
_seekToPosition(frames, seconds) {
|
|
107
|
+
this._seekFrames = frames;
|
|
108
|
+
this._seekSeconds = seconds;
|
|
109
|
+
this._elapsedBeforeAnchor = 0;
|
|
110
|
+
if (this._running) {
|
|
111
|
+
this._contextFrameAtAnchor = this._readContextFrame();
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
/** Position (frames) at the start of the current run. */
|
|
115
|
+
_positionAtAnchorFrames() {
|
|
116
|
+
return this._seekFrames + this._elapsedBeforeAnchor;
|
|
117
|
+
}
|
|
118
|
+
/** Whole frames elapsed since the last seek, across runs. */
|
|
119
|
+
_totalElapsedFrames() {
|
|
120
|
+
return this._elapsedBeforeAnchor + (this._running ? this._elapsedFrames() : 0);
|
|
121
|
+
}
|
|
122
|
+
/** Whole frames elapsed since the anchor (running only). */
|
|
123
|
+
_elapsedFrames() {
|
|
124
|
+
return this._readContextFrame() - this._contextFrameAtAnchor;
|
|
125
|
+
}
|
|
126
|
+
/** currentTime as an integer frame on the render-quantum lattice. Pure. */
|
|
127
|
+
_snappedContextFrame() {
|
|
128
|
+
const raw = this._audioContext.currentTime * this._sampleRate;
|
|
129
|
+
const onLattice = Math.round(raw / RENDER_QUANTUM_FRAMES) * RENDER_QUANTUM_FRAMES;
|
|
130
|
+
return Math.abs(raw - onLattice) < LATTICE_SNAP_FRAMES ? onLattice : Math.round(raw);
|
|
131
|
+
}
|
|
132
|
+
/** The snapped reading, with backward re-bases absorbed. Not pure: the
|
|
133
|
+
* first reader to see a backward reading shifts the anchor (idempotent —
|
|
134
|
+
* every later reader sees the already-held position). */
|
|
135
|
+
_readContextFrame() {
|
|
136
|
+
const frame = this._snappedContextFrame();
|
|
137
|
+
if (frame < this._lastContextFrame && this._running) {
|
|
138
|
+
const shift = this._lastContextFrame - frame;
|
|
139
|
+
this._contextFrameAtAnchor -= shift;
|
|
140
|
+
this._lastRebaseFrames = shift;
|
|
141
|
+
this._rebaseCount++;
|
|
142
|
+
}
|
|
143
|
+
this._lastContextFrame = frame;
|
|
144
|
+
return frame;
|
|
145
|
+
}
|
|
48
146
|
};
|
|
147
|
+
function assertFinite(method, value) {
|
|
148
|
+
if (!Number.isFinite(value)) {
|
|
149
|
+
throw new Error(
|
|
150
|
+
"[waveform-playlist] Clock." + method + ": position must be finite, got " + value
|
|
151
|
+
);
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// src/core/loop-range.ts
|
|
156
|
+
function assertValidLoopRange(source, enabled, start, end, unit) {
|
|
157
|
+
if (!enabled) return;
|
|
158
|
+
if (!Number.isFinite(start) || !Number.isFinite(end)) {
|
|
159
|
+
throw new Error(
|
|
160
|
+
"[waveform-playlist] " + source + ": non-finite " + unit + " values (" + start + ", " + end + ")"
|
|
161
|
+
);
|
|
162
|
+
}
|
|
163
|
+
if (unit === "tick" && (!Number.isInteger(start) || !Number.isInteger(end))) {
|
|
164
|
+
throw new Error(
|
|
165
|
+
"[waveform-playlist] " + source + ": ticks must be integers, got (" + start + ", " + end + ")"
|
|
166
|
+
);
|
|
167
|
+
}
|
|
168
|
+
if (start >= end) {
|
|
169
|
+
throw new Error(
|
|
170
|
+
"[waveform-playlist] " + source + ": start " + unit + " (" + start + ") must be less than end " + unit + " (" + end + ")"
|
|
171
|
+
);
|
|
172
|
+
}
|
|
173
|
+
}
|
|
174
|
+
function assertLoopRangeSpansATick(source, enabled, start, end, unit, startTick, endTick) {
|
|
175
|
+
if (!enabled || startTick < endTick) return;
|
|
176
|
+
throw new Error(
|
|
177
|
+
"[waveform-playlist] " + source + ": range (" + start + ", " + end + " " + unit + ") is shorter than one tick (both round to tick " + startTick + ")"
|
|
178
|
+
);
|
|
179
|
+
}
|
|
49
180
|
|
|
50
181
|
// src/core/scheduler.ts
|
|
182
|
+
function formatSchedulerListenerError(error) {
|
|
183
|
+
const where = error.phase === "consume" ? " at tick " + error.event.tick : error.phase === "generate" ? " for ticks [" + error.fromTick + ", " + error.toTick + ")" : " jumping to tick " + error.tick;
|
|
184
|
+
return "scheduler listener threw during " + error.phase + "()" + where + ": " + describeError(error.error);
|
|
185
|
+
}
|
|
186
|
+
function describeError(error) {
|
|
187
|
+
return error instanceof Error ? error.name + ": " + error.message : String(error);
|
|
188
|
+
}
|
|
189
|
+
var MAX_LOGGED_KINDS_PER_LISTENER = 16;
|
|
190
|
+
var ListenerErrorLog = class {
|
|
191
|
+
constructor(_prefix) {
|
|
192
|
+
this._prefix = _prefix;
|
|
193
|
+
this._seen = /* @__PURE__ */ new WeakMap();
|
|
194
|
+
}
|
|
195
|
+
warnOnce(error) {
|
|
196
|
+
let kinds = this._seen.get(error.listener);
|
|
197
|
+
if (!kinds) {
|
|
198
|
+
kinds = /* @__PURE__ */ new Set();
|
|
199
|
+
this._seen.set(error.listener, kinds);
|
|
200
|
+
}
|
|
201
|
+
const kind = error.phase + "|" + describeError(error.error);
|
|
202
|
+
if (kinds.has(kind) || kinds.size >= MAX_LOGGED_KINDS_PER_LISTENER) return;
|
|
203
|
+
kinds.add(kind);
|
|
204
|
+
console.warn(
|
|
205
|
+
this._prefix + formatSchedulerListenerError(error) + ' (further failures of this kind are not logged; subscribe to the "error" event to handle them)'
|
|
206
|
+
);
|
|
207
|
+
}
|
|
208
|
+
};
|
|
51
209
|
var Scheduler = class {
|
|
52
210
|
constructor(tempoMap, options = {}) {
|
|
53
211
|
this._rightEdge = 0;
|
|
@@ -59,9 +217,32 @@ var Scheduler = class {
|
|
|
59
217
|
this._loopEnd = 0;
|
|
60
218
|
// integer ticks
|
|
61
219
|
this._playEnd = null;
|
|
220
|
+
this._errorLog = new ListenerErrorLog("[waveform-playlist] Scheduler: ");
|
|
221
|
+
/** The map an advance() in progress started with; null between calls. */
|
|
222
|
+
this._advancingWith = null;
|
|
62
223
|
this._tempoMap = tempoMap;
|
|
63
224
|
this._lookahead = options.lookahead ?? 0.2;
|
|
64
225
|
this._onLoop = options.onLoop;
|
|
226
|
+
this._onError = options.onError;
|
|
227
|
+
}
|
|
228
|
+
/** Swap in a new (immutable) TempoMap. The scheduling cursor is re-anchored
|
|
229
|
+
* through seconds — the window already handed to listeners (in seconds)
|
|
230
|
+
* stays covered, so the next advance() neither regenerates it nor stalls
|
|
231
|
+
* until the clock catches up with the old edge's new tick value. If that
|
|
232
|
+
* puts the cursor at or past loopEnd (a faster tempo while looping) it is
|
|
233
|
+
* clamped to loopEnd and the next advance() wraps immediately. Loop bounds
|
|
234
|
+
* stay in ticks (they are musical positions); a seconds-defined play end
|
|
235
|
+
* is the Transport's to recompute. Called from inside advance() (a
|
|
236
|
+
* listener's generate()/consume() swapping the map directly) the swap is
|
|
237
|
+
* recorded and the re-anchor happens when that window completes — the
|
|
238
|
+
* window in progress keeps the TEMPO map it started with (loop bounds and
|
|
239
|
+
* the MeterMap are not snapshotted). Audio already scheduled in the
|
|
240
|
+
* lookahead keeps its old-tempo timing. */
|
|
241
|
+
setTempoMap(tempoMap) {
|
|
242
|
+
if (this._advancingWith === null) {
|
|
243
|
+
this._reanchorCursor(this._tempoMap, tempoMap);
|
|
244
|
+
}
|
|
245
|
+
this._tempoMap = tempoMap;
|
|
65
246
|
}
|
|
66
247
|
addListener(listener) {
|
|
67
248
|
this._listeners.add(listener);
|
|
@@ -69,28 +250,28 @@ var Scheduler = class {
|
|
|
69
250
|
removeListener(listener) {
|
|
70
251
|
this._listeners.delete(listener);
|
|
71
252
|
}
|
|
72
|
-
/** Primary API — ticks as source of truth
|
|
253
|
+
/** Primary API — ticks as source of truth. Throws on a non-finite or
|
|
254
|
+
* inverted/empty range when `enabled`; the previous loop stays in force. */
|
|
73
255
|
setLoop(enabled, startTick, endTick) {
|
|
74
|
-
|
|
75
|
-
console.warn(
|
|
76
|
-
"[waveform-playlist] Scheduler.setLoop: non-finite tick values (" + startTick + ", " + endTick + ")"
|
|
77
|
-
);
|
|
78
|
-
return;
|
|
79
|
-
}
|
|
80
|
-
if (enabled && startTick >= endTick) {
|
|
81
|
-
console.warn(
|
|
82
|
-
"[waveform-playlist] Scheduler.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
|
|
83
|
-
);
|
|
84
|
-
return;
|
|
85
|
-
}
|
|
256
|
+
assertValidLoopRange("Scheduler.setLoop", enabled, startTick, endTick, "tick");
|
|
86
257
|
this._loopEnabled = enabled;
|
|
87
258
|
this._loopStart = Math.round(startTick);
|
|
88
259
|
this._loopEnd = Math.round(endTick);
|
|
89
260
|
}
|
|
90
261
|
/** Convenience — converts seconds to ticks via TempoMap */
|
|
91
262
|
setLoopSeconds(enabled, startSec, endSec) {
|
|
263
|
+
assertValidLoopRange("Scheduler.setLoopSeconds", enabled, startSec, endSec, "second");
|
|
92
264
|
const startTick = this._tempoMap.secondsToTicks(startSec);
|
|
93
265
|
const endTick = this._tempoMap.secondsToTicks(endSec);
|
|
266
|
+
assertLoopRangeSpansATick(
|
|
267
|
+
"Scheduler.setLoopSeconds",
|
|
268
|
+
enabled,
|
|
269
|
+
startSec,
|
|
270
|
+
endSec,
|
|
271
|
+
"second",
|
|
272
|
+
startTick,
|
|
273
|
+
endTick
|
|
274
|
+
);
|
|
94
275
|
this.setLoop(enabled, startTick, endTick);
|
|
95
276
|
}
|
|
96
277
|
/** Hard end bound (ticks) for non-loop playback: the lookahead window never
|
|
@@ -101,35 +282,57 @@ var Scheduler = class {
|
|
|
101
282
|
setPlayEnd(endTick) {
|
|
102
283
|
this._playEnd = endTick == null ? null : Math.round(endTick);
|
|
103
284
|
}
|
|
104
|
-
/** Reset scheduling cursor. Takes seconds (from Clock), converts to
|
|
285
|
+
/** Reset scheduling cursor. Takes seconds (from Clock), converts to integer
|
|
286
|
+
* ticks — secondsToTicks rounds once here; the cursor is always whole ticks. */
|
|
105
287
|
reset(timeSeconds) {
|
|
106
288
|
this._rightEdge = this._tempoMap.secondsToTicks(timeSeconds);
|
|
107
289
|
}
|
|
108
290
|
/** Advance the scheduling window. Takes seconds (from Clock), converts to ticks. */
|
|
109
291
|
advance(currentTimeSeconds) {
|
|
110
|
-
const
|
|
292
|
+
const tempoMap = this._tempoMap;
|
|
293
|
+
this._advancingWith = tempoMap;
|
|
294
|
+
try {
|
|
295
|
+
this._advanceWith(tempoMap, currentTimeSeconds);
|
|
296
|
+
} finally {
|
|
297
|
+
this._advancingWith = null;
|
|
298
|
+
if (this._tempoMap !== tempoMap) {
|
|
299
|
+
this._reanchorCursor(tempoMap, this._tempoMap);
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
}
|
|
303
|
+
_advanceWith(tempoMap, currentTimeSeconds) {
|
|
304
|
+
const targetTick = tempoMap.secondsToTicks(currentTimeSeconds + this._lookahead);
|
|
111
305
|
if (this._loopEnabled && this._loopEnd > this._loopStart) {
|
|
112
|
-
const loopDuration = this._loopEnd - this._loopStart;
|
|
113
306
|
let remaining = targetTick - this._rightEdge;
|
|
114
307
|
while (remaining > 0) {
|
|
115
308
|
const distToEnd = this._loopEnd - this._rightEdge;
|
|
116
|
-
if (distToEnd
|
|
309
|
+
if (distToEnd > remaining) {
|
|
117
310
|
this._generateAndConsume(this._rightEdge, this._rightEdge + remaining);
|
|
118
311
|
this._rightEdge += remaining;
|
|
119
312
|
break;
|
|
120
313
|
}
|
|
121
|
-
|
|
122
|
-
|
|
314
|
+
if (distToEnd > 0) {
|
|
315
|
+
this._generateAndConsume(this._rightEdge, this._loopEnd);
|
|
316
|
+
remaining -= distToEnd;
|
|
317
|
+
}
|
|
123
318
|
for (const listener of this._listeners) {
|
|
124
|
-
|
|
319
|
+
try {
|
|
320
|
+
listener.onPositionJump(this._loopStart);
|
|
321
|
+
} catch (err) {
|
|
322
|
+
this._reportError({
|
|
323
|
+
phase: "positionJump",
|
|
324
|
+
listener,
|
|
325
|
+
tick: this._loopStart,
|
|
326
|
+
error: err
|
|
327
|
+
});
|
|
328
|
+
}
|
|
125
329
|
}
|
|
126
330
|
this._onLoop?.(
|
|
127
|
-
|
|
128
|
-
|
|
331
|
+
tempoMap.ticksToSeconds(this._loopStart),
|
|
332
|
+
tempoMap.ticksToSeconds(this._loopEnd),
|
|
129
333
|
currentTimeSeconds
|
|
130
334
|
);
|
|
131
335
|
this._rightEdge = this._loopStart;
|
|
132
|
-
if (loopDuration <= 0) break;
|
|
133
336
|
}
|
|
134
337
|
return;
|
|
135
338
|
}
|
|
@@ -139,55 +342,204 @@ var Scheduler = class {
|
|
|
139
342
|
this._rightEdge = bound;
|
|
140
343
|
}
|
|
141
344
|
}
|
|
345
|
+
/** Move the cursor from `previous`-map ticks to `next`-map ticks through
|
|
346
|
+
* seconds, clamped to loopEnd so a faster tempo cannot strand it past the
|
|
347
|
+
* loop (the next advance() then wraps). */
|
|
348
|
+
_reanchorCursor(previous, next) {
|
|
349
|
+
if (previous === next) return;
|
|
350
|
+
const edgeSeconds = previous.ticksToSeconds(this._rightEdge);
|
|
351
|
+
let edge = next.secondsToTicks(edgeSeconds);
|
|
352
|
+
if (this._loopEnabled && this._loopEnd > this._loopStart && edge > this._loopEnd) {
|
|
353
|
+
edge = this._loopEnd;
|
|
354
|
+
}
|
|
355
|
+
this._rightEdge = edge;
|
|
356
|
+
}
|
|
142
357
|
_generateAndConsume(fromTick, toTick) {
|
|
143
358
|
for (const listener of this._listeners) {
|
|
359
|
+
let events;
|
|
144
360
|
try {
|
|
145
|
-
|
|
146
|
-
for (const event of events) {
|
|
147
|
-
try {
|
|
148
|
-
listener.consume(event);
|
|
149
|
-
} catch (err) {
|
|
150
|
-
console.warn("[waveform-playlist] Scheduler: error consuming event:", String(err));
|
|
151
|
-
}
|
|
152
|
-
}
|
|
361
|
+
events = listener.generate(fromTick, toTick);
|
|
153
362
|
} catch (err) {
|
|
154
|
-
|
|
363
|
+
this._reportError({
|
|
364
|
+
phase: "generate",
|
|
365
|
+
listener,
|
|
366
|
+
fromTick,
|
|
367
|
+
toTick,
|
|
368
|
+
error: err
|
|
369
|
+
});
|
|
370
|
+
continue;
|
|
371
|
+
}
|
|
372
|
+
for (const event of events) {
|
|
373
|
+
try {
|
|
374
|
+
listener.consume(event);
|
|
375
|
+
} catch (err) {
|
|
376
|
+
this._reportError({ phase: "consume", listener, event, error: err });
|
|
377
|
+
}
|
|
155
378
|
}
|
|
156
379
|
}
|
|
157
380
|
}
|
|
381
|
+
_reportError(error) {
|
|
382
|
+
if (this._onError) {
|
|
383
|
+
this._onError(error);
|
|
384
|
+
return;
|
|
385
|
+
}
|
|
386
|
+
this._errorLog.warnOnce(error);
|
|
387
|
+
}
|
|
158
388
|
};
|
|
159
389
|
|
|
160
390
|
// src/core/timer.ts
|
|
391
|
+
var DEFAULT_TIMER_INTERVAL_MS = 25;
|
|
392
|
+
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";
|
|
393
|
+
var WATCHDOG_INTERVALS = 4;
|
|
394
|
+
var workerRefusedOnThisPage = false;
|
|
395
|
+
function describeWorkerError(event) {
|
|
396
|
+
const e = event;
|
|
397
|
+
const where = e.filename ? " at " + e.filename + ":" + (e.lineno ?? "?") : "";
|
|
398
|
+
return "worker " + (e.type ?? "error") + ": " + (e.message ?? String(event)) + where;
|
|
399
|
+
}
|
|
400
|
+
function hasWorkerPlatform() {
|
|
401
|
+
return typeof Worker !== "undefined" && typeof Blob !== "undefined" && typeof URL !== "undefined" && typeof URL.createObjectURL === "function";
|
|
402
|
+
}
|
|
161
403
|
var Timer = class {
|
|
162
|
-
constructor(onTick) {
|
|
163
|
-
this._rafId = null;
|
|
404
|
+
constructor(onTick, options = {}) {
|
|
164
405
|
this._running = false;
|
|
406
|
+
this._disposed = false;
|
|
407
|
+
this._warnedDisposed = false;
|
|
408
|
+
this._worker = null;
|
|
409
|
+
this._workerUrl = null;
|
|
410
|
+
/** Set once the Worker path has been ruled out for this Timer. */
|
|
411
|
+
this._useTimeoutFallback = false;
|
|
412
|
+
this._timeoutId = null;
|
|
413
|
+
/** Armed when `start` is posted to the Worker; cleared by its first tick. */
|
|
414
|
+
this._watchdogId = null;
|
|
415
|
+
const intervalMs = options.intervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
|
|
416
|
+
if (!Number.isFinite(intervalMs) || intervalMs <= 0) {
|
|
417
|
+
throw new Error(
|
|
418
|
+
"[waveform-playlist] Timer: intervalMs must be a positive number, got " + intervalMs
|
|
419
|
+
);
|
|
420
|
+
}
|
|
165
421
|
this._onTick = onTick;
|
|
422
|
+
this._intervalMs = intervalMs;
|
|
166
423
|
}
|
|
167
424
|
start() {
|
|
425
|
+
if (this._disposed) {
|
|
426
|
+
if (!this._warnedDisposed) {
|
|
427
|
+
this._warnedDisposed = true;
|
|
428
|
+
console.warn("[waveform-playlist] Timer: start() on a disposed Timer is ignored");
|
|
429
|
+
}
|
|
430
|
+
return;
|
|
431
|
+
}
|
|
168
432
|
if (this._running) return;
|
|
169
433
|
this._running = true;
|
|
170
|
-
this.
|
|
434
|
+
const worker = this._ensureWorker();
|
|
435
|
+
if (worker) {
|
|
436
|
+
worker.postMessage({ type: "start", intervalMs: this._intervalMs });
|
|
437
|
+
this._armWatchdog();
|
|
438
|
+
} else if (this._timeoutId === null) {
|
|
439
|
+
this._scheduleTimeout();
|
|
440
|
+
}
|
|
171
441
|
}
|
|
172
442
|
stop() {
|
|
443
|
+
if (!this._running) return;
|
|
173
444
|
this._running = false;
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
this.
|
|
445
|
+
this._clearWatchdog();
|
|
446
|
+
if (this._worker) {
|
|
447
|
+
this._worker.postMessage({ type: "stop" });
|
|
448
|
+
}
|
|
449
|
+
if (this._timeoutId !== null) {
|
|
450
|
+
clearTimeout(this._timeoutId);
|
|
451
|
+
this._timeoutId = null;
|
|
177
452
|
}
|
|
178
453
|
}
|
|
179
|
-
|
|
180
|
-
|
|
181
|
-
|
|
182
|
-
|
|
183
|
-
|
|
184
|
-
|
|
185
|
-
|
|
186
|
-
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
454
|
+
/** Stop and release the Worker. A disposed Timer cannot be restarted —
|
|
455
|
+
* start() becomes a warned no-op, so a late play() on a disposed transport
|
|
456
|
+
* cannot leak a fresh Worker. */
|
|
457
|
+
dispose() {
|
|
458
|
+
this.stop();
|
|
459
|
+
this._disposed = true;
|
|
460
|
+
this._releaseWorker();
|
|
461
|
+
}
|
|
462
|
+
_handleTick() {
|
|
463
|
+
if (!this._running) return;
|
|
464
|
+
this._clearWatchdog();
|
|
465
|
+
try {
|
|
466
|
+
this._onTick();
|
|
467
|
+
} catch (err) {
|
|
468
|
+
console.warn("[waveform-playlist] Timer tick error: " + String(err));
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
_scheduleTimeout() {
|
|
472
|
+
this._timeoutId = setTimeout(() => {
|
|
473
|
+
this._timeoutId = null;
|
|
474
|
+
this._handleTick();
|
|
475
|
+
if (this._running && this._timeoutId === null) this._scheduleTimeout();
|
|
476
|
+
}, this._intervalMs);
|
|
477
|
+
}
|
|
478
|
+
_releaseWorker() {
|
|
479
|
+
if (this._worker) {
|
|
480
|
+
this._worker.onmessage = null;
|
|
481
|
+
this._worker.onerror = null;
|
|
482
|
+
this._worker.onmessageerror = null;
|
|
483
|
+
this._worker.terminate();
|
|
484
|
+
this._worker = null;
|
|
485
|
+
}
|
|
486
|
+
if (this._workerUrl !== null) {
|
|
487
|
+
URL.revokeObjectURL(this._workerUrl);
|
|
488
|
+
this._workerUrl = null;
|
|
489
|
+
}
|
|
490
|
+
}
|
|
491
|
+
_armWatchdog() {
|
|
492
|
+
this._clearWatchdog();
|
|
493
|
+
this._watchdogId = setTimeout(() => {
|
|
494
|
+
this._watchdogId = null;
|
|
495
|
+
this._fallBackFromWorker(
|
|
496
|
+
"no tick received within " + WATCHDOG_INTERVALS * this._intervalMs + " ms of start",
|
|
497
|
+
false
|
|
498
|
+
);
|
|
499
|
+
}, WATCHDOG_INTERVALS * this._intervalMs);
|
|
500
|
+
}
|
|
501
|
+
_clearWatchdog() {
|
|
502
|
+
if (this._watchdogId !== null) {
|
|
503
|
+
clearTimeout(this._watchdogId);
|
|
504
|
+
this._watchdogId = null;
|
|
505
|
+
}
|
|
506
|
+
}
|
|
507
|
+
/** The Worker path failed: release it and keep ticking on setTimeout. A
|
|
508
|
+
* constructor refusal is an environment fact remembered (and warned) once
|
|
509
|
+
* per page; a Worker that errored or went silent later is this Timer's
|
|
510
|
+
* own event and is warned every time. */
|
|
511
|
+
_fallBackFromWorker(reason, constructorRefused) {
|
|
512
|
+
this._useTimeoutFallback = true;
|
|
513
|
+
this._clearWatchdog();
|
|
514
|
+
this._releaseWorker();
|
|
515
|
+
const silenced = constructorRefused && workerRefusedOnThisPage;
|
|
516
|
+
if (constructorRefused) workerRefusedOnThisPage = true;
|
|
517
|
+
if (!silenced) {
|
|
518
|
+
console.warn(
|
|
519
|
+
"[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"
|
|
520
|
+
);
|
|
521
|
+
}
|
|
522
|
+
if (this._running && this._timeoutId === null) this._scheduleTimeout();
|
|
523
|
+
}
|
|
524
|
+
_ensureWorker() {
|
|
525
|
+
if (this._worker) return this._worker;
|
|
526
|
+
if (this._useTimeoutFallback || workerRefusedOnThisPage || !hasWorkerPlatform()) {
|
|
527
|
+
this._useTimeoutFallback = true;
|
|
528
|
+
return null;
|
|
529
|
+
}
|
|
530
|
+
try {
|
|
531
|
+
const url = URL.createObjectURL(new Blob([TIMER_WORKER_SCRIPT], { type: "text/javascript" }));
|
|
532
|
+
const worker = new Worker(url);
|
|
533
|
+
worker.onmessage = () => this._handleTick();
|
|
534
|
+
worker.onerror = (event) => this._fallBackFromWorker(describeWorkerError(event), false);
|
|
535
|
+
worker.onmessageerror = () => this._fallBackFromWorker("worker message error", false);
|
|
536
|
+
this._worker = worker;
|
|
537
|
+
this._workerUrl = url;
|
|
538
|
+
return worker;
|
|
539
|
+
} catch (err) {
|
|
540
|
+
this._fallBackFromWorker(String(err), true);
|
|
541
|
+
return null;
|
|
542
|
+
}
|
|
191
543
|
}
|
|
192
544
|
};
|
|
193
545
|
|
|
@@ -210,36 +562,100 @@ var SampleTimeline = class {
|
|
|
210
562
|
return Math.round(seconds * this._sampleRate);
|
|
211
563
|
}
|
|
212
564
|
ticksToSamples(ticks) {
|
|
213
|
-
|
|
214
|
-
throw new Error(
|
|
215
|
-
"[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
|
|
216
|
-
);
|
|
217
|
-
}
|
|
218
|
-
return Math.round(this._tempoMap.ticksToSeconds(ticks) * this._sampleRate);
|
|
565
|
+
return Math.round(this._requireTempoMap().ticksToSeconds(ticks) * this._sampleRate);
|
|
219
566
|
}
|
|
567
|
+
/** Samples → integer ticks. The integer `Tick` contract belongs to THIS
|
|
568
|
+
* boundary: exactly one rounding, applied to the fractional position. */
|
|
220
569
|
samplesToTicks(samples) {
|
|
570
|
+
return Math.round(this.samplesToTicksExact(samples));
|
|
571
|
+
}
|
|
572
|
+
/** Samples → fractional tick position (unrounded), for sub-tick placement. */
|
|
573
|
+
samplesToTicksExact(samples) {
|
|
574
|
+
return this._requireTempoMap().secondsToTicksExact(samples / this._sampleRate);
|
|
575
|
+
}
|
|
576
|
+
_requireTempoMap() {
|
|
221
577
|
if (!this._tempoMap) {
|
|
222
578
|
throw new Error(
|
|
223
579
|
"[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
|
|
224
580
|
);
|
|
225
581
|
}
|
|
226
|
-
return
|
|
582
|
+
return this._tempoMap;
|
|
227
583
|
}
|
|
228
584
|
};
|
|
229
585
|
|
|
230
586
|
// src/timeline/tempo-map.ts
|
|
231
587
|
var CURVE_EPSILON = 1e-15;
|
|
232
|
-
var
|
|
233
|
-
function
|
|
234
|
-
|
|
588
|
+
var CURVE_LINEAR_SLOPE_EPSILON = 1e-12;
|
|
589
|
+
function isNearLinearSlope(slope) {
|
|
590
|
+
return Math.abs(slope - 0.5) < CURVE_LINEAR_SLOPE_EPSILON;
|
|
591
|
+
}
|
|
592
|
+
function curveCoefficients(slope) {
|
|
235
593
|
const p = Math.max(CURVE_EPSILON, Math.min(1 - CURVE_EPSILON, slope));
|
|
236
|
-
|
|
594
|
+
const d = 1 - 2 * p;
|
|
595
|
+
const c = 2 * Math.log1p(d / p);
|
|
596
|
+
return { c, cB: c * p * p / d };
|
|
597
|
+
}
|
|
598
|
+
function log1pOverY(y) {
|
|
599
|
+
return y === 0 ? 1 : Math.log1p(y) / y;
|
|
600
|
+
}
|
|
601
|
+
function expm1NegOverK(k) {
|
|
602
|
+
return k === 0 ? 1 : -Math.expm1(-k) / k;
|
|
603
|
+
}
|
|
604
|
+
function curveNormalizedAt(x, slope) {
|
|
605
|
+
if (isNearLinearSlope(slope)) return x;
|
|
606
|
+
const { c, cB } = curveCoefficients(slope);
|
|
607
|
+
return cB / c * Math.expm1(c * x);
|
|
608
|
+
}
|
|
609
|
+
function assertFiniteInput(what, value) {
|
|
610
|
+
if (!Number.isFinite(value)) {
|
|
611
|
+
throw new Error("[waveform-playlist] TempoMap: " + what + " must be finite, got " + value);
|
|
612
|
+
}
|
|
613
|
+
}
|
|
614
|
+
function assertFiniteResult(input, value) {
|
|
615
|
+
if (!Number.isFinite(value)) {
|
|
616
|
+
throw new Error(
|
|
617
|
+
"[waveform-playlist] TempoMap: " + input + " is outside the domain of the tempo map (result not finite)"
|
|
618
|
+
);
|
|
619
|
+
}
|
|
620
|
+
return value;
|
|
621
|
+
}
|
|
622
|
+
var INTERNAL = /* @__PURE__ */ Symbol("TempoMap.internal");
|
|
623
|
+
function freezeInterpolation(interpolation) {
|
|
624
|
+
return typeof interpolation === "object" ? Object.freeze({ type: "curve", slope: interpolation.slope }) : interpolation;
|
|
625
|
+
}
|
|
626
|
+
function sealEntries(entries) {
|
|
627
|
+
return Object.freeze(
|
|
628
|
+
entries.map(
|
|
629
|
+
(e) => Object.isFrozen(e) && Object.isFrozen(e.interpolation) ? e : Object.freeze({ ...e, interpolation: freezeInterpolation(e.interpolation) })
|
|
630
|
+
)
|
|
631
|
+
);
|
|
632
|
+
}
|
|
633
|
+
function validateTick(what, tick) {
|
|
634
|
+
if (!Number.isFinite(tick) || tick < 0 || !Number.isInteger(tick)) {
|
|
635
|
+
throw new Error(
|
|
636
|
+
"[waveform-playlist] TempoMap: " + what + " tick must be a non-negative integer, got " + tick
|
|
637
|
+
);
|
|
638
|
+
}
|
|
237
639
|
}
|
|
238
640
|
var TempoMap = class _TempoMap {
|
|
239
|
-
constructor(ppqn = 960,
|
|
240
|
-
|
|
641
|
+
constructor(ppqn = 960, init = 120, token) {
|
|
642
|
+
if (!Number.isInteger(ppqn) || ppqn <= 0) {
|
|
643
|
+
throw new Error("[waveform-playlist] TempoMap: ppqn must be a positive integer, got " + ppqn);
|
|
644
|
+
}
|
|
241
645
|
this._ppqn = ppqn;
|
|
242
|
-
|
|
646
|
+
if (typeof init === "number") {
|
|
647
|
+
_TempoMap._validateBpm(init);
|
|
648
|
+
this._entries = sealEntries([
|
|
649
|
+
{ tick: 0, bpm: init, interpolation: "step", secondsAtTick: 0 }
|
|
650
|
+
]);
|
|
651
|
+
} else {
|
|
652
|
+
if (token !== INTERNAL) {
|
|
653
|
+
throw new Error(
|
|
654
|
+
"[waveform-playlist] TempoMap: the entries constructor is internal \u2014 use new TempoMap(ppqn, bpm) and withTempo()"
|
|
655
|
+
);
|
|
656
|
+
}
|
|
657
|
+
this._entries = init;
|
|
658
|
+
}
|
|
243
659
|
}
|
|
244
660
|
/** A non-finite or non-positive BPM silently corrupts the secondsAtTick
|
|
245
661
|
* cache (Infinity, or non-monotonic values that break the binary search
|
|
@@ -259,37 +675,110 @@ var TempoMap = class _TempoMap {
|
|
|
259
675
|
get entryCount() {
|
|
260
676
|
return this._entries.length;
|
|
261
677
|
}
|
|
262
|
-
|
|
678
|
+
/** The entries, in tick order, frozen. `secondsAtTick` is the cumulative
|
|
679
|
+
* seconds up to each entry. */
|
|
680
|
+
get entries() {
|
|
681
|
+
return this._entries;
|
|
682
|
+
}
|
|
683
|
+
/** Return a new map with `bpm` at `atTick` (replacing an existing entry
|
|
684
|
+
* there). Tick 0 is always 'step'. Throws on an invalid BPM, curve slope
|
|
685
|
+
* or atTick (non-negative integer); this map is never modified. */
|
|
686
|
+
withTempo(bpm, atTick = 0, options) {
|
|
263
687
|
_TempoMap._validateBpm(bpm);
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
688
|
+
validateTick("atTick", atTick);
|
|
689
|
+
const requested = options?.interpolation ?? "step";
|
|
690
|
+
if (typeof requested === "object" && requested.type === "curve") {
|
|
691
|
+
const s = requested.slope;
|
|
267
692
|
if (!Number.isFinite(s) || s <= 0 || s >= 1) {
|
|
268
693
|
throw new Error(
|
|
269
694
|
"[waveform-playlist] TempoMap: curve slope must be between 0 and 1 (exclusive), got " + s
|
|
270
695
|
);
|
|
271
696
|
}
|
|
272
697
|
}
|
|
698
|
+
const interpolation = freezeInterpolation(requested);
|
|
699
|
+
const entries = [...this._entries];
|
|
273
700
|
if (atTick === 0) {
|
|
274
|
-
|
|
275
|
-
this.
|
|
276
|
-
return;
|
|
701
|
+
entries[0] = { ...entries[0], bpm, interpolation: "step" };
|
|
702
|
+
return this._derive(entries, 0);
|
|
277
703
|
}
|
|
278
|
-
let i = this.
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
this._entries[i] = { ...this._entries[i], bpm, interpolation };
|
|
704
|
+
let i = this._entryIndexAt(atTick);
|
|
705
|
+
if (entries[i].tick === atTick) {
|
|
706
|
+
entries[i] = { ...entries[i], bpm, interpolation };
|
|
282
707
|
} else {
|
|
283
|
-
|
|
284
|
-
this._entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick });
|
|
708
|
+
entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick: 0 });
|
|
285
709
|
i = i + 1;
|
|
286
710
|
}
|
|
287
|
-
this.
|
|
711
|
+
return this._derive(entries, i);
|
|
288
712
|
}
|
|
713
|
+
/** Return a new map without the entry at exactly `atTick`. The tick-0 entry
|
|
714
|
+
* is permanent (a map must always have a tempo), and a tick with no entry
|
|
715
|
+
* is a no-op — both return this same map. An invalid tick throws. */
|
|
716
|
+
withoutTempo(atTick) {
|
|
717
|
+
validateTick("atTick", atTick);
|
|
718
|
+
if (atTick === 0) return this;
|
|
719
|
+
const i = this._entries.findIndex((e) => e.tick === atTick);
|
|
720
|
+
if (i === -1) return this;
|
|
721
|
+
return this._derive([...this._entries.slice(0, i), ...this._entries.slice(i + 1)], i);
|
|
722
|
+
}
|
|
723
|
+
/** Return a new single-entry map keeping only the tick-0 tempo. */
|
|
724
|
+
withoutTempos() {
|
|
725
|
+
return new _TempoMap(this._ppqn, this._entries[0].bpm);
|
|
726
|
+
}
|
|
727
|
+
/** Build the successor map: recompute cumulative seconds from `fromIndex`
|
|
728
|
+
* into a fresh, sealed entry list. Entries before `fromIndex` are the
|
|
729
|
+
* previous map's frozen objects, reused by reference. Nothing on `this`
|
|
730
|
+
* is written. */
|
|
731
|
+
_derive(entries, fromIndex) {
|
|
732
|
+
for (let i = Math.max(1, fromIndex); i < entries.length; i++) {
|
|
733
|
+
const prev = entries[i - 1];
|
|
734
|
+
entries[i] = {
|
|
735
|
+
...entries[i],
|
|
736
|
+
secondsAtTick: prev.secondsAtTick + this._segmentSeconds(prev, entries[i])
|
|
737
|
+
};
|
|
738
|
+
}
|
|
739
|
+
return new _TempoMap(this._ppqn, sealEntries(entries), INTERNAL);
|
|
740
|
+
}
|
|
741
|
+
/** Seconds spanned from `prev` to `entry` under `entry`'s interpolation. */
|
|
742
|
+
_segmentSeconds(prev, entry) {
|
|
743
|
+
const tickDelta = entry.tick - prev.tick;
|
|
744
|
+
if (entry.interpolation === "linear") {
|
|
745
|
+
return this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
|
|
746
|
+
}
|
|
747
|
+
if (typeof entry.interpolation === "object") {
|
|
748
|
+
return this._ticksToSecondsCurve(
|
|
749
|
+
tickDelta,
|
|
750
|
+
prev.bpm,
|
|
751
|
+
entry.bpm,
|
|
752
|
+
tickDelta,
|
|
753
|
+
entry.interpolation.slope
|
|
754
|
+
);
|
|
755
|
+
}
|
|
756
|
+
return tickDelta * (60 / (prev.bpm * this._ppqn));
|
|
757
|
+
}
|
|
758
|
+
/** Tick position → seconds. Accepts a fractional position (e.g. the value
|
|
759
|
+
* secondsToTicksExact returned) as well as an integer Tick. */
|
|
289
760
|
ticksToSeconds(ticks) {
|
|
290
|
-
|
|
761
|
+
assertFiniteInput("ticks", ticks);
|
|
762
|
+
return assertFiniteResult("ticks " + ticks, this._ticksToSecondsInternal(ticks));
|
|
291
763
|
}
|
|
764
|
+
/** Seconds → integer ticks, rounded once here at the `Tick` boundary.
|
|
765
|
+
* Use secondsToTicksExact() for sub-tick placement. */
|
|
292
766
|
secondsToTicks(seconds) {
|
|
767
|
+
return Math.round(this.secondsToTicksExact(seconds));
|
|
768
|
+
}
|
|
769
|
+
/** Seconds → fractional tick position (unrounded). The integer producers
|
|
770
|
+
* round this once at their own boundary (secondsToTicks,
|
|
771
|
+
* SampleTimeline.samplesToTicks); sub-tick consumers (placing a recorded
|
|
772
|
+
* note between ticks before quantising, continuous beat positions) use it
|
|
773
|
+
* directly. Not clamped: negative seconds convert at the constant initial
|
|
774
|
+
* tempo to negative ticks (whatever the first segment's interpolation),
|
|
775
|
+
* and seconds past the last entry extrapolate the last tempo forwards. */
|
|
776
|
+
secondsToTicksExact(seconds) {
|
|
777
|
+
assertFiniteInput("seconds", seconds);
|
|
778
|
+
return assertFiniteResult("seconds " + seconds, this._secondsToTicksRaw(seconds));
|
|
779
|
+
}
|
|
780
|
+
_secondsToTicksRaw(seconds) {
|
|
781
|
+
if (seconds < 0) return seconds * this._entries[0].bpm * this._ppqn / 60;
|
|
293
782
|
let lo = 0;
|
|
294
783
|
let hi = this._entries.length - 1;
|
|
295
784
|
while (lo < hi) {
|
|
@@ -304,50 +793,31 @@ var TempoMap = class _TempoMap {
|
|
|
304
793
|
const secondsIntoSegment = seconds - entry.secondsAtTick;
|
|
305
794
|
const nextEntry = lo < this._entries.length - 1 ? this._entries[lo + 1] : null;
|
|
306
795
|
if (nextEntry && nextEntry.interpolation === "linear") {
|
|
307
|
-
return
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
nextEntry.tick - entry.tick
|
|
313
|
-
)
|
|
796
|
+
return entry.tick + this._secondsToTicksLinear(
|
|
797
|
+
secondsIntoSegment,
|
|
798
|
+
entry.bpm,
|
|
799
|
+
nextEntry.bpm,
|
|
800
|
+
nextEntry.tick - entry.tick
|
|
314
801
|
);
|
|
315
802
|
}
|
|
316
803
|
if (nextEntry && typeof nextEntry.interpolation === "object") {
|
|
317
|
-
return
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
nextEntry.interpolation.slope
|
|
324
|
-
)
|
|
804
|
+
return entry.tick + this._secondsToTicksCurve(
|
|
805
|
+
secondsIntoSegment,
|
|
806
|
+
entry.bpm,
|
|
807
|
+
nextEntry.bpm,
|
|
808
|
+
nextEntry.tick - entry.tick,
|
|
809
|
+
nextEntry.interpolation.slope
|
|
325
810
|
);
|
|
326
811
|
}
|
|
327
812
|
const ticksPerSecond = entry.bpm / 60 * this._ppqn;
|
|
328
|
-
return
|
|
813
|
+
return entry.tick + secondsIntoSegment * ticksPerSecond;
|
|
329
814
|
}
|
|
330
815
|
beatsToSeconds(beats) {
|
|
331
816
|
return this.ticksToSeconds(beats * this._ppqn);
|
|
332
817
|
}
|
|
818
|
+
/** Continuous beat position (fractional) — not quantised to whole ticks. */
|
|
333
819
|
secondsToBeats(seconds) {
|
|
334
|
-
return this.
|
|
335
|
-
}
|
|
336
|
-
clearTempos() {
|
|
337
|
-
const first = this._entries[0];
|
|
338
|
-
this._entries = [{ tick: 0, bpm: first.bpm, interpolation: "step", secondsAtTick: 0 }];
|
|
339
|
-
}
|
|
340
|
-
/** Remove the tempo entry at exactly `atTick`, if one exists. The tick-0
|
|
341
|
-
* entry is permanent (a map must always have a tempo) — removing it is a
|
|
342
|
-
* no-op, matching removeMeter's treatment of the initial meter. The
|
|
343
|
-
* seconds cache is recomputed from the removal point, the same partial
|
|
344
|
-
* update setTempo uses. */
|
|
345
|
-
removeTempo(atTick) {
|
|
346
|
-
if (atTick === 0) return;
|
|
347
|
-
const i = this._entries.findIndex((e) => e.tick === atTick);
|
|
348
|
-
if (i === -1) return;
|
|
349
|
-
this._entries = [...this._entries.slice(0, i), ...this._entries.slice(i + 1)];
|
|
350
|
-
this._recomputeCache(i);
|
|
820
|
+
return this.secondsToTicksExact(seconds) / this._ppqn;
|
|
351
821
|
}
|
|
352
822
|
/** Get the interpolated BPM at a tick position */
|
|
353
823
|
_getTempoAt(atTick) {
|
|
@@ -369,6 +839,7 @@ var TempoMap = class _TempoMap {
|
|
|
369
839
|
return entry.bpm;
|
|
370
840
|
}
|
|
371
841
|
_ticksToSecondsInternal(ticks) {
|
|
842
|
+
if (ticks < 0) return ticks * 60 / (this._entries[0].bpm * this._ppqn);
|
|
372
843
|
const entryIndex = this._entryIndexAt(ticks);
|
|
373
844
|
const entry = this._entries[entryIndex];
|
|
374
845
|
const ticksIntoSegment = ticks - entry.tick;
|
|
@@ -409,10 +880,9 @@ var TempoMap = class _TempoMap {
|
|
|
409
880
|
* Closed-form via exponential: bpmAtTick = bpm0 * exp(seconds * deltaBpm * ppqn / (60 * T))
|
|
410
881
|
* then ticks = (bpmAtTick - bpm0) * T / deltaBpm
|
|
411
882
|
*
|
|
412
|
-
* Note: exp(log(x)) has ~1 ULP floating-point error, so round-trips
|
|
413
|
-
*
|
|
414
|
-
* BPM ranges (10–300 BPM)
|
|
415
|
-
* trapezoidal/quadratic approach was.
|
|
883
|
+
* Note: exp(log(x)) has ~1 ULP floating-point error, so integer round-trips
|
|
884
|
+
* rely on the rounding in secondsToTicks; secondsToTicksExact returns the
|
|
885
|
+
* raw value. Sufficient for all tested BPM ranges (10–300 BPM).
|
|
416
886
|
*/
|
|
417
887
|
_secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks) {
|
|
418
888
|
if (totalSegmentTicks === 0 || seconds === 0) return 0;
|
|
@@ -424,43 +894,71 @@ var TempoMap = class _TempoMap {
|
|
|
424
894
|
return (bpmAtTick - bpm0) / deltaBpm * totalSegmentTicks;
|
|
425
895
|
}
|
|
426
896
|
/**
|
|
427
|
-
*
|
|
428
|
-
*
|
|
429
|
-
*
|
|
897
|
+
* Exact integration for a Möbius-Ease tempo curve.
|
|
898
|
+
* With x = ticks / T the BPM is bpm0 + Δ·(p²/(1 − 2p))·(e^(c·x) − 1), i.e.
|
|
899
|
+
* A + B·e^(c·x) for B = Δ·p²/(1 − 2p), A = bpm0 − B. Its reciprocal has the
|
|
900
|
+
* antiderivative u/A − ln(A + B·e^(c·u))/(c·A), so
|
|
901
|
+
* seconds = base · (c·x − ln(bpm(x)/bpm0)) / (c·A), base = T·60/ppqn.
|
|
902
|
+
* Everything is carried as c·A and c·B so the slope → 0.5 limit (B → ∞,
|
|
903
|
+
* c → 0) stays finite. Two algebraically equal forms are used, chosen per
|
|
904
|
+
* call so neither one cancels:
|
|
905
|
+
* - log1p form: base · (1 − e^(−c·x))/(c·bpm0) · log1p(y)/y with
|
|
906
|
+
* y = (A/bpm0)·(e^(−c·x) − 1). Exact as A → 0 (the plain form is 0/0
|
|
907
|
+
* there) and as c → 0. Used while 1 + y = bpm(x)·e^(−c·x)/bpm0 > 0.5.
|
|
908
|
+
* - plain form, when 1 + y ≤ 0.5 (steep concave ramps near their end, or
|
|
909
|
+
* convex descending ramps, where forming 1 + y loses digits). There the
|
|
910
|
+
* numerator −ln(1 + y) is at least ln 2 in magnitude, and A ≠ 0 (A = 0
|
|
911
|
+
* forces 1 + y = 1), so nothing cancels.
|
|
912
|
+
* Error is floating-point only (≈1e-15 relative), independent of segment
|
|
913
|
+
* length — the previous 64-step trapezoid drifted by up to ~2e-3 relative
|
|
914
|
+
* (2.8 ms per bar, 0.7 s over a 256-bar ramp at steep slopes).
|
|
430
915
|
*/
|
|
431
916
|
_ticksToSecondsCurve(ticks, bpm0, bpm1, totalSegmentTicks, slope) {
|
|
432
917
|
if (totalSegmentTicks === 0 || ticks === 0) return 0;
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
}
|
|
443
|
-
|
|
918
|
+
if (isNearLinearSlope(slope)) {
|
|
919
|
+
return this._ticksToSecondsLinear(ticks, bpm0, bpm1, totalSegmentTicks);
|
|
920
|
+
}
|
|
921
|
+
const { c, cB, cA, base } = this._curveSegment(bpm0, bpm1, totalSegmentTicks, slope);
|
|
922
|
+
const x = ticks / totalSegmentTicks;
|
|
923
|
+
const expm1NegCx = Math.expm1(-c * x);
|
|
924
|
+
const y = cA / (c * bpm0) * expm1NegCx;
|
|
925
|
+
if (1 + y > 0.5) {
|
|
926
|
+
return base * (-expm1NegCx / (c * bpm0)) * log1pOverY(y);
|
|
927
|
+
}
|
|
928
|
+
const logRatio = Math.log1p(cB / (c * bpm0) * Math.expm1(c * x));
|
|
929
|
+
return base * (c * x - logRatio) / cA;
|
|
444
930
|
}
|
|
445
931
|
/**
|
|
446
|
-
*
|
|
447
|
-
*
|
|
932
|
+
* Closed-form inverse of _ticksToSecondsCurve. Solving the log1p form for x:
|
|
933
|
+
* K = seconds·c·A/base
|
|
934
|
+
* z = e^(−c·x) − 1 = −(bpm0·seconds·c/base) · (1 − e^(−K))/K
|
|
935
|
+
* x = −log1p(z)/c
|
|
936
|
+
* (1 − e^(−K))/K → 1 as K → 0 makes A → 0 exact; c → 0 is exact because
|
|
937
|
+
* z ∝ c and log1p(z)/c keeps the ratio. When e^(−c·x) is small (z ≤ −0.5: a
|
|
938
|
+
* steep concave ramp near its end) and |B| < |A|/2, forming it as 1 + z
|
|
939
|
+
* loses digits; there the equal product form
|
|
940
|
+
* e^(−c·x) = (c·bpm0·e^(−K) − c·B)/(c·A) is used — its digit loss is
|
|
941
|
+
* |B|/|A| times the 1 + z form's, so the guard makes it the better choice by
|
|
942
|
+
* at least 2×. Returns fractional ticks; callers round at their unit boundary.
|
|
448
943
|
*/
|
|
449
944
|
_secondsToTicksCurve(seconds, bpm0, bpm1, totalSegmentTicks, slope) {
|
|
450
945
|
if (totalSegmentTicks === 0 || seconds === 0) return 0;
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
} else {
|
|
460
|
-
hi = mid;
|
|
461
|
-
}
|
|
946
|
+
if (isNearLinearSlope(slope)) {
|
|
947
|
+
return this._secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks);
|
|
948
|
+
}
|
|
949
|
+
const { c, cB, cA, base } = this._curveSegment(bpm0, bpm1, totalSegmentTicks, slope);
|
|
950
|
+
const k = seconds * cA / base;
|
|
951
|
+
const z = -(bpm0 * seconds * c / base) * expm1NegOverK(k);
|
|
952
|
+
if (z > -0.5 || Math.abs(cB) >= 0.5 * Math.abs(cA)) {
|
|
953
|
+
return -Math.log1p(z) / c * totalSegmentTicks;
|
|
462
954
|
}
|
|
463
|
-
|
|
955
|
+
const expNegCx = (c * bpm0 * Math.exp(-k) - cB) / cA;
|
|
956
|
+
return -Math.log(expNegCx) / c * totalSegmentTicks;
|
|
957
|
+
}
|
|
958
|
+
_curveSegment(bpm0, bpm1, totalSegmentTicks, slope) {
|
|
959
|
+
const { c, cB: cBNormalized } = curveCoefficients(slope);
|
|
960
|
+
const cB = cBNormalized * (bpm1 - bpm0);
|
|
961
|
+
return { c, cB, cA: c * bpm0 - cB, base: totalSegmentTicks * 60 / this._ppqn };
|
|
464
962
|
}
|
|
465
963
|
_entryIndexAt(tick) {
|
|
466
964
|
let lo = 0;
|
|
@@ -475,32 +973,6 @@ var TempoMap = class _TempoMap {
|
|
|
475
973
|
}
|
|
476
974
|
return lo;
|
|
477
975
|
}
|
|
478
|
-
_recomputeCache(fromIndex) {
|
|
479
|
-
for (let i = Math.max(1, fromIndex); i < this._entries.length; i++) {
|
|
480
|
-
const prev = this._entries[i - 1];
|
|
481
|
-
const tickDelta = this._entries[i].tick - prev.tick;
|
|
482
|
-
const entry = this._entries[i];
|
|
483
|
-
let segmentSeconds;
|
|
484
|
-
if (entry.interpolation === "linear") {
|
|
485
|
-
segmentSeconds = this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
|
|
486
|
-
} else if (typeof entry.interpolation === "object") {
|
|
487
|
-
segmentSeconds = this._ticksToSecondsCurve(
|
|
488
|
-
tickDelta,
|
|
489
|
-
prev.bpm,
|
|
490
|
-
entry.bpm,
|
|
491
|
-
tickDelta,
|
|
492
|
-
entry.interpolation.slope
|
|
493
|
-
);
|
|
494
|
-
} else {
|
|
495
|
-
const secondsPerTick = 60 / (prev.bpm * this._ppqn);
|
|
496
|
-
segmentSeconds = tickDelta * secondsPerTick;
|
|
497
|
-
}
|
|
498
|
-
this._entries[i] = {
|
|
499
|
-
...entry,
|
|
500
|
-
secondsAtTick: prev.secondsAtTick + segmentSeconds
|
|
501
|
-
};
|
|
502
|
-
}
|
|
503
|
-
}
|
|
504
976
|
};
|
|
505
977
|
|
|
506
978
|
// src/timeline/meter-map.ts
|
|
@@ -556,6 +1028,7 @@ var MeterMap = class {
|
|
|
556
1028
|
const idx = this._entries.findIndex((e) => e.tick === atTick);
|
|
557
1029
|
if (idx > 0) {
|
|
558
1030
|
this._entries.splice(idx, 1);
|
|
1031
|
+
this._resnapDownstreamEntries(idx - 1);
|
|
559
1032
|
this._recomputeCache(idx);
|
|
560
1033
|
} else if (idx === -1) {
|
|
561
1034
|
console.warn("[waveform-playlist] MeterMap.removeMeter: no entry at tick " + atTick);
|
|
@@ -682,6 +1155,80 @@ var MeterMap = class {
|
|
|
682
1155
|
}
|
|
683
1156
|
};
|
|
684
1157
|
|
|
1158
|
+
// src/timeline/quantize.ts
|
|
1159
|
+
var MODES = ["nearest", "next", "previous"];
|
|
1160
|
+
var ON_LINE_EPSILON = 1e-6;
|
|
1161
|
+
function quantizeTick(meterMap, tick, subdivision, options = {}) {
|
|
1162
|
+
const mode = options.mode ?? "nearest";
|
|
1163
|
+
const strength = options.strength ?? 1;
|
|
1164
|
+
validateQuantizeInput(tick, subdivision, mode, strength);
|
|
1165
|
+
const entry = meterMap.getEntryAt(tick);
|
|
1166
|
+
const ticksPerBar = meterMap.ticksPerBar(entry.tick);
|
|
1167
|
+
const barStart = entry.tick + Math.floor((tick - entry.tick) / ticksPerBar) * ticksPerBar;
|
|
1168
|
+
const nextBarStart = barStart + ticksPerBar;
|
|
1169
|
+
const step = resolveStep(meterMap, subdivision, ticksPerBar, meterMap.ticksPerBeat(entry.tick));
|
|
1170
|
+
const previous = barStart + Math.floor((tick - barStart) / step) * step;
|
|
1171
|
+
const candidateNext = Math.min(previous + step, nextBarStart);
|
|
1172
|
+
const onLine = Math.abs(tick - previous) < ON_LINE_EPSILON || Math.abs(tick - candidateNext) < ON_LINE_EPSILON;
|
|
1173
|
+
if (onLine) {
|
|
1174
|
+
const line = Math.abs(tick - previous) < ON_LINE_EPSILON ? previous : candidateNext;
|
|
1175
|
+
return Math.round(tick + (line - tick) * strength);
|
|
1176
|
+
}
|
|
1177
|
+
const target = pickLine(mode, tick, previous, candidateNext);
|
|
1178
|
+
return Math.round(tick + (target - tick) * strength);
|
|
1179
|
+
}
|
|
1180
|
+
function resolveStep(meterMap, subdivision, ticksPerBar, ticksPerBeat) {
|
|
1181
|
+
if (subdivision === "bar") return ticksPerBar;
|
|
1182
|
+
if (subdivision === "beat") return ticksPerBeat;
|
|
1183
|
+
if ("ticks" in subdivision) return subdivision.ticks;
|
|
1184
|
+
let step = meterMap.ppqn * 4 / subdivision.note;
|
|
1185
|
+
if (subdivision.dotted) step = step * 3 / 2;
|
|
1186
|
+
if (subdivision.triplet) step = step * 2 / 3;
|
|
1187
|
+
return step;
|
|
1188
|
+
}
|
|
1189
|
+
var NOTE_VALUES = [1, 2, 4, 8, 16, 32, 64];
|
|
1190
|
+
function isValidSubdivision(subdivision) {
|
|
1191
|
+
if (subdivision === "bar" || subdivision === "beat") return true;
|
|
1192
|
+
if (typeof subdivision !== "object" || subdivision === null) return false;
|
|
1193
|
+
if ("ticks" in subdivision) {
|
|
1194
|
+
return Number.isInteger(subdivision.ticks) && subdivision.ticks > 0;
|
|
1195
|
+
}
|
|
1196
|
+
return "note" in subdivision && NOTE_VALUES.includes(subdivision.note);
|
|
1197
|
+
}
|
|
1198
|
+
function describeSubdivision(subdivision) {
|
|
1199
|
+
if (typeof subdivision === "object" && subdivision !== null) {
|
|
1200
|
+
return JSON.stringify(subdivision);
|
|
1201
|
+
}
|
|
1202
|
+
return String(subdivision);
|
|
1203
|
+
}
|
|
1204
|
+
function pickLine(mode, tick, previous, next) {
|
|
1205
|
+
if (mode === "previous") return previous;
|
|
1206
|
+
if (mode === "next") return next;
|
|
1207
|
+
return tick - previous < next - tick ? previous : next;
|
|
1208
|
+
}
|
|
1209
|
+
function validateQuantizeInput(tick, subdivision, mode, strength) {
|
|
1210
|
+
if (!Number.isFinite(tick) || tick < 0) {
|
|
1211
|
+
throw new Error(
|
|
1212
|
+
"[waveform-playlist] quantizeTick: tick must be a finite number >= 0, got " + tick
|
|
1213
|
+
);
|
|
1214
|
+
}
|
|
1215
|
+
if (!isValidSubdivision(subdivision)) {
|
|
1216
|
+
throw new Error(
|
|
1217
|
+
"[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)
|
|
1218
|
+
);
|
|
1219
|
+
}
|
|
1220
|
+
if (!MODES.includes(mode)) {
|
|
1221
|
+
throw new Error(
|
|
1222
|
+
"[waveform-playlist] quantizeTick: mode must be 'nearest', 'next' or 'previous', got " + String(mode)
|
|
1223
|
+
);
|
|
1224
|
+
}
|
|
1225
|
+
if (!Number.isFinite(strength) || strength < 0 || strength > 1) {
|
|
1226
|
+
throw new Error(
|
|
1227
|
+
"[waveform-playlist] quantizeTick: strength must be between 0 and 1, got " + strength
|
|
1228
|
+
);
|
|
1229
|
+
}
|
|
1230
|
+
}
|
|
1231
|
+
|
|
685
1232
|
// src/audio/master-node.ts
|
|
686
1233
|
var MasterNode = class {
|
|
687
1234
|
constructor(audioContext) {
|
|
@@ -741,62 +1288,92 @@ var MasterNode = class {
|
|
|
741
1288
|
};
|
|
742
1289
|
|
|
743
1290
|
// src/audio/track-node.ts
|
|
1291
|
+
import { createPanStage } from "@waveform-playlist/core";
|
|
1292
|
+
var PREFIX = "[waveform-playlist] ";
|
|
744
1293
|
var TrackNode = class {
|
|
745
|
-
constructor(id, audioContext) {
|
|
746
|
-
this.
|
|
747
|
-
this._effectsInput = null;
|
|
1294
|
+
constructor(id, audioContext, sourceChannelCount = 1) {
|
|
1295
|
+
this._effects = null;
|
|
748
1296
|
this.id = id;
|
|
1297
|
+
this._inputNode = audioContext.createGain();
|
|
749
1298
|
this._volumeNode = audioContext.createGain();
|
|
750
|
-
this.
|
|
751
|
-
this._panNode.channelCount = 2;
|
|
1299
|
+
this._panStage = createPanStage(audioContext, 0, sourceChannelCount);
|
|
752
1300
|
this._muteNode = audioContext.createGain();
|
|
753
|
-
this.
|
|
754
|
-
this.
|
|
1301
|
+
this._inputNode.connect(this._volumeNode);
|
|
1302
|
+
this._volumeNode.connect(this._panStage.input);
|
|
1303
|
+
this._panStage.output.connect(this._muteNode);
|
|
755
1304
|
}
|
|
756
|
-
/** Where clip sources connect */
|
|
1305
|
+
/** Where clip sources connect (pre-fader, pre-effects). */
|
|
757
1306
|
get input() {
|
|
758
|
-
return this.
|
|
1307
|
+
return this._inputNode;
|
|
759
1308
|
}
|
|
760
1309
|
/** Connect this track's output to a destination (master node) */
|
|
761
1310
|
connectOutput(destination) {
|
|
762
|
-
this._destination = destination;
|
|
763
1311
|
this._muteNode.connect(destination);
|
|
764
1312
|
}
|
|
765
1313
|
setVolume(value) {
|
|
766
1314
|
this._volumeNode.gain.value = value;
|
|
767
1315
|
}
|
|
768
1316
|
setPan(value) {
|
|
769
|
-
this.
|
|
1317
|
+
this._panStage.setPan(value);
|
|
1318
|
+
}
|
|
1319
|
+
/** Select the pan law from the track's source material: 1 = mono law
|
|
1320
|
+
* (−3 dB per side at centre), 2+ = stereo law (unity at centre). */
|
|
1321
|
+
setSourceChannelCount(sourceChannelCount) {
|
|
1322
|
+
this._panStage.setSourceChannelCount(sourceChannelCount);
|
|
770
1323
|
}
|
|
771
1324
|
setMute(muted) {
|
|
772
1325
|
this._muteNode.gain.value = muted ? 0 : 1;
|
|
773
1326
|
}
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
1327
|
+
/**
|
|
1328
|
+
* Insert an effects chain between the track input and the fader:
|
|
1329
|
+
* `input → effectsInput … effectsOutput → volume`. The transport owns
|
|
1330
|
+
* BOTH edges — the caller only builds what lies between the two nodes
|
|
1331
|
+
* (pass the same node twice for a single-node effect). Replaces any
|
|
1332
|
+
* chain connected earlier.
|
|
1333
|
+
*/
|
|
1334
|
+
connectEffects(effectsInput, effectsOutput) {
|
|
1335
|
+
this.disconnectEffects();
|
|
1336
|
+
this._inputNode.disconnect();
|
|
1337
|
+
this._inputNode.connect(effectsInput);
|
|
1338
|
+
effectsOutput.connect(this._volumeNode);
|
|
1339
|
+
this._effects = { input: effectsInput, output: effectsOutput };
|
|
1340
|
+
}
|
|
1341
|
+
/** Remove the effects chain and restore `input → volume`. No-op without one. */
|
|
782
1342
|
disconnectEffects() {
|
|
783
|
-
if (this.
|
|
784
|
-
|
|
785
|
-
this._muteNode.connect(this._destination);
|
|
786
|
-
this._effectsInput = null;
|
|
1343
|
+
if (!this._effects) {
|
|
1344
|
+
return;
|
|
787
1345
|
}
|
|
1346
|
+
this._releaseEffectsReturn();
|
|
1347
|
+
this._inputNode.disconnect();
|
|
1348
|
+
this._inputNode.connect(this._volumeNode);
|
|
1349
|
+
this._effects = null;
|
|
788
1350
|
}
|
|
789
1351
|
dispose() {
|
|
790
|
-
|
|
1352
|
+
this._releaseEffectsReturn();
|
|
1353
|
+
this._effects = null;
|
|
1354
|
+
for (const node of [this._inputNode, this._volumeNode, this._muteNode]) {
|
|
791
1355
|
try {
|
|
792
1356
|
node.disconnect();
|
|
793
1357
|
} catch (err) {
|
|
794
|
-
console.warn(
|
|
795
|
-
"[waveform-playlist] TrackNode.dispose: error disconnecting node:",
|
|
796
|
-
String(err)
|
|
797
|
-
);
|
|
1358
|
+
console.warn(PREFIX + "TrackNode.dispose: error disconnecting node:", String(err));
|
|
798
1359
|
}
|
|
799
1360
|
}
|
|
1361
|
+
this._panStage.dispose();
|
|
1362
|
+
}
|
|
1363
|
+
/** Targeted disconnect of `effectsOutput → volume` — other consumers of
|
|
1364
|
+
* the chain's output (analyser taps) keep their edges. */
|
|
1365
|
+
_releaseEffectsReturn() {
|
|
1366
|
+
if (!this._effects) {
|
|
1367
|
+
return;
|
|
1368
|
+
}
|
|
1369
|
+
try {
|
|
1370
|
+
this._effects.output.disconnect(this._volumeNode);
|
|
1371
|
+
} catch (err) {
|
|
1372
|
+
console.warn(
|
|
1373
|
+
PREFIX + 'TrackNode: effects chain was already disconnected from track "' + this.id + '": ',
|
|
1374
|
+
String(err)
|
|
1375
|
+
);
|
|
1376
|
+
}
|
|
800
1377
|
}
|
|
801
1378
|
};
|
|
802
1379
|
|
|
@@ -813,6 +1390,10 @@ var ClipPlayer = class {
|
|
|
813
1390
|
this._tempoMap = tempoMap;
|
|
814
1391
|
this._toAudioTime = toAudioTime;
|
|
815
1392
|
}
|
|
1393
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1394
|
+
setTempoMap(tempoMap) {
|
|
1395
|
+
this._tempoMap = tempoMap;
|
|
1396
|
+
}
|
|
816
1397
|
setTracks(tracks, trackNodes) {
|
|
817
1398
|
this._tracks.clear();
|
|
818
1399
|
this._trackNodes = trackNodes;
|
|
@@ -1026,6 +1607,10 @@ var MetronomePlayer = class {
|
|
|
1026
1607
|
this._destination = destination;
|
|
1027
1608
|
this._toAudioTime = toAudioTime;
|
|
1028
1609
|
}
|
|
1610
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1611
|
+
setTempoMap(tempoMap) {
|
|
1612
|
+
this._tempoMap = tempoMap;
|
|
1613
|
+
}
|
|
1029
1614
|
setEnabled(enabled) {
|
|
1030
1615
|
this._enabled = enabled;
|
|
1031
1616
|
if (!enabled) {
|
|
@@ -1107,6 +1692,9 @@ var MetronomePlayer = class {
|
|
|
1107
1692
|
}
|
|
1108
1693
|
};
|
|
1109
1694
|
|
|
1695
|
+
// src/transport.ts
|
|
1696
|
+
import { trackChannelCount } from "@waveform-playlist/core";
|
|
1697
|
+
|
|
1110
1698
|
// src/audio/count-in-player.ts
|
|
1111
1699
|
var CountInPlayer = class {
|
|
1112
1700
|
constructor(audioContext, tempoMap, destination, toAudioTime) {
|
|
@@ -1181,12 +1769,9 @@ var CountInPlayer = class {
|
|
|
1181
1769
|
});
|
|
1182
1770
|
const transportTime = this._tempoMap.ticksToSeconds(event.tick);
|
|
1183
1771
|
source.start(this._toAudioTime(transportTime));
|
|
1184
|
-
}
|
|
1185
|
-
|
|
1186
|
-
"[waveform-playlist] CountInPlayer.consume: failed to schedule beat " + event.beat + "/" + event.totalBeats + ": " + String(err)
|
|
1187
|
-
);
|
|
1772
|
+
} finally {
|
|
1773
|
+
this._onBeat?.(event.beat, event.totalBeats);
|
|
1188
1774
|
}
|
|
1189
|
-
this._onBeat?.(event.beat, event.totalBeats);
|
|
1190
1775
|
}
|
|
1191
1776
|
onPositionJump(_newTick) {
|
|
1192
1777
|
}
|
|
@@ -1252,6 +1837,11 @@ var _Transport = class _Transport {
|
|
|
1252
1837
|
this._soloedTrackIds = /* @__PURE__ */ new Set();
|
|
1253
1838
|
this._mutedTrackIds = /* @__PURE__ */ new Set();
|
|
1254
1839
|
this._playing = false;
|
|
1840
|
+
this._disposed = false;
|
|
1841
|
+
/** `Clock.rebaseCount` as of the last resync; a higher count means sources
|
|
1842
|
+
* armed in the old time base are still scheduled. */
|
|
1843
|
+
this._rebasesHandled = 0;
|
|
1844
|
+
this._warnedDiscontinuity = false;
|
|
1255
1845
|
this._loopEnabled = false;
|
|
1256
1846
|
this._loopStartTick = 0;
|
|
1257
1847
|
this._loopStartSeconds = 0;
|
|
@@ -1270,17 +1860,32 @@ var _Transport = class _Transport {
|
|
|
1270
1860
|
this._accentBuffer = null;
|
|
1271
1861
|
this._normalBuffer = null;
|
|
1272
1862
|
this._schedulerLookahead = 0.2;
|
|
1863
|
+
this._errorLog = new ListenerErrorLog("[waveform-playlist] Transport: ");
|
|
1273
1864
|
this._ppqn = 960;
|
|
1274
1865
|
this._audioContext = audioContext;
|
|
1866
|
+
if (!(Number.isFinite(audioContext.sampleRate) && audioContext.sampleRate > 0)) {
|
|
1867
|
+
throw new Error(
|
|
1868
|
+
"[waveform-playlist] Transport: the AudioContext must report a positive finite sampleRate, got " + audioContext.sampleRate
|
|
1869
|
+
);
|
|
1870
|
+
}
|
|
1275
1871
|
const sampleRate = options.sampleRate ?? audioContext.sampleRate;
|
|
1276
1872
|
const ppqn = options.ppqn ?? 960;
|
|
1277
1873
|
const tempo = options.tempo ?? 120;
|
|
1278
1874
|
const numerator = options.numerator ?? 4;
|
|
1279
1875
|
const denominator = options.denominator ?? 4;
|
|
1280
1876
|
const lookahead = options.schedulerLookahead ?? 0.2;
|
|
1877
|
+
const timerIntervalMs = options.timerIntervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
|
|
1281
1878
|
this._ppqn = ppqn;
|
|
1282
1879
|
this._schedulerLookahead = lookahead;
|
|
1283
|
-
_Transport._validateOptions(
|
|
1880
|
+
_Transport._validateOptions(
|
|
1881
|
+
sampleRate,
|
|
1882
|
+
ppqn,
|
|
1883
|
+
tempo,
|
|
1884
|
+
numerator,
|
|
1885
|
+
denominator,
|
|
1886
|
+
lookahead,
|
|
1887
|
+
timerIntervalMs
|
|
1888
|
+
);
|
|
1284
1889
|
this._clock = new Clock(audioContext);
|
|
1285
1890
|
this._sampleTimeline = new SampleTimeline(sampleRate);
|
|
1286
1891
|
this._meterMap = new MeterMap(ppqn, numerator, denominator);
|
|
@@ -1290,13 +1895,33 @@ var _Transport = class _Transport {
|
|
|
1290
1895
|
onLoop: (loopStartSeconds, loopEndSeconds, currentTimeSeconds) => {
|
|
1291
1896
|
const timeToBoundary = loopEndSeconds - currentTimeSeconds;
|
|
1292
1897
|
this._clock.seekTo(loopStartSeconds - timeToBoundary);
|
|
1293
|
-
}
|
|
1898
|
+
},
|
|
1899
|
+
onError: (error) => this._emitError(error)
|
|
1294
1900
|
});
|
|
1295
1901
|
this._sampleTimeline.setTempoMap(this._tempoMap);
|
|
1296
1902
|
this._initAudioGraph(audioContext);
|
|
1297
1903
|
this._initCountIn(audioContext, options);
|
|
1298
|
-
this._timer = new Timer(
|
|
1904
|
+
this._timer = new Timer(
|
|
1905
|
+
() => {
|
|
1906
|
+
try {
|
|
1907
|
+
this._tick();
|
|
1908
|
+
} catch (err) {
|
|
1909
|
+
this._onTickFailure(err);
|
|
1910
|
+
}
|
|
1911
|
+
},
|
|
1912
|
+
{ intervalMs: timerIntervalMs }
|
|
1913
|
+
);
|
|
1914
|
+
}
|
|
1915
|
+
/** One scheduling tick. Anything thrown here is a transport-internal
|
|
1916
|
+
* fault (not a listener failure — those are caught by the scheduler); the
|
|
1917
|
+
* wrapper above stops the transport rather than retrying it 40×/s. */
|
|
1918
|
+
_tick() {
|
|
1919
|
+
{
|
|
1299
1920
|
const time = this._clock.getTime();
|
|
1921
|
+
if (this._clock.rebaseCount !== this._rebasesHandled) {
|
|
1922
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
1923
|
+
this._resyncAfterDiscontinuity(time);
|
|
1924
|
+
}
|
|
1300
1925
|
if (this._countingIn) {
|
|
1301
1926
|
this._countInScheduler?.advance(time);
|
|
1302
1927
|
if (time >= this._countInDuration) {
|
|
@@ -1306,10 +1931,65 @@ var _Transport = class _Transport {
|
|
|
1306
1931
|
}
|
|
1307
1932
|
if (this._endTime !== void 0 && time >= this._endTime) {
|
|
1308
1933
|
this.stop();
|
|
1934
|
+
this._emit("ended");
|
|
1309
1935
|
return;
|
|
1310
1936
|
}
|
|
1311
1937
|
this._scheduler.advance(time);
|
|
1312
|
-
|
|
1938
|
+
this._emit("tick", { seconds: this.getCurrentTime() });
|
|
1939
|
+
}
|
|
1940
|
+
}
|
|
1941
|
+
/** The clock absorbed a backward context re-base since the last resync:
|
|
1942
|
+
* sources armed through the old anchor's toAudioTime() hold ABSOLUTE
|
|
1943
|
+
* context times and would now fire late by the shift. Outside a count-in,
|
|
1944
|
+
* re-create them from the held position (the seek-while-playing path minus
|
|
1945
|
+
* the move), clamped to loopStart like getCurrentTime() — right after a
|
|
1946
|
+
* wrap the clock sits behind loopStart and a resync from there would play
|
|
1947
|
+
* pre-loop material. During a count-in the clicks already armed are
|
|
1948
|
+
* dropped rather than regenerated (CountInPlayer counts beats, so a
|
|
1949
|
+
* regenerate would double-fire); the count-in→play transition is
|
|
1950
|
+
* clock-driven and still lands on the held clock. */
|
|
1951
|
+
_resyncAfterDiscontinuity(time) {
|
|
1952
|
+
const shiftSeconds = this._clock.frameToSeconds(this._clock.lastRebaseFrames);
|
|
1953
|
+
let seconds;
|
|
1954
|
+
if (this._countingIn) {
|
|
1955
|
+
this._countInPlayer.silence();
|
|
1956
|
+
seconds = this._countInStartPosition;
|
|
1957
|
+
} else {
|
|
1958
|
+
seconds = this._loopEnabled && time < this._loopStartSeconds ? this._loopStartSeconds : time;
|
|
1959
|
+
this._silenceAll();
|
|
1960
|
+
this._scheduler.reset(seconds);
|
|
1961
|
+
this._clipPlayer.onPositionJump(this._tempoMap.secondsToTicks(seconds));
|
|
1962
|
+
}
|
|
1963
|
+
const listeners = this._listeners.get("discontinuity");
|
|
1964
|
+
if (listeners && listeners.size > 0) {
|
|
1965
|
+
this._emit("discontinuity", { seconds, shiftSeconds });
|
|
1966
|
+
} else if (!this._warnedDiscontinuity) {
|
|
1967
|
+
this._warnedDiscontinuity = true;
|
|
1968
|
+
console.warn(
|
|
1969
|
+
"[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.'
|
|
1970
|
+
);
|
|
1971
|
+
}
|
|
1972
|
+
}
|
|
1973
|
+
/** Sources are (re)created from the current anchor here: any re-base
|
|
1974
|
+
* absorbed before this point concerns audio that no longer exists. */
|
|
1975
|
+
_markRebasesHandled() {
|
|
1976
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
1977
|
+
}
|
|
1978
|
+
/** A tick threw: warn once and stop, so the engine sees a `stop` and no
|
|
1979
|
+
* one is left looking at a "playing" transport that renders silence. */
|
|
1980
|
+
_onTickFailure(err) {
|
|
1981
|
+
console.warn(
|
|
1982
|
+
"[waveform-playlist] Transport: stopping \u2014 the scheduling tick threw: " + (err instanceof Error ? err.name + ": " + err.message + (err.stack ? "\n" + err.stack : "") : String(err))
|
|
1983
|
+
);
|
|
1984
|
+
try {
|
|
1985
|
+
this.stop();
|
|
1986
|
+
} catch (stopErr) {
|
|
1987
|
+
console.warn(
|
|
1988
|
+
"[waveform-playlist] Transport: stop() after a tick failure also threw: " + String(stopErr)
|
|
1989
|
+
);
|
|
1990
|
+
this._timer.stop();
|
|
1991
|
+
this._playing = false;
|
|
1992
|
+
}
|
|
1313
1993
|
}
|
|
1314
1994
|
get audioContext() {
|
|
1315
1995
|
return this._audioContext;
|
|
@@ -1317,8 +1997,16 @@ var _Transport = class _Transport {
|
|
|
1317
1997
|
get ppqn() {
|
|
1318
1998
|
return this._ppqn;
|
|
1319
1999
|
}
|
|
2000
|
+
/** The current tempo map. Immutable: every tempo edit swaps in a new map,
|
|
2001
|
+
* so a reference you hold keeps converting with the tempo it had. */
|
|
2002
|
+
get tempoMap() {
|
|
2003
|
+
return this._tempoMap;
|
|
2004
|
+
}
|
|
1320
2005
|
// --- Playback ---
|
|
1321
2006
|
play(startTime, endTime) {
|
|
2007
|
+
if (this._refuseIfDisposed("play")) return;
|
|
2008
|
+
if (startTime !== void 0) assertFiniteSeconds("play", "startTime", startTime);
|
|
2009
|
+
if (endTime !== void 0) assertFiniteSeconds("play", "endTime", endTime);
|
|
1322
2010
|
if (this._playing) return;
|
|
1323
2011
|
if (startTime !== void 0) {
|
|
1324
2012
|
this._clock.seekTo(startTime);
|
|
@@ -1333,6 +2021,7 @@ var _Transport = class _Transport {
|
|
|
1333
2021
|
this._scheduler.setPlayEnd(
|
|
1334
2022
|
endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
|
|
1335
2023
|
);
|
|
2024
|
+
this._markRebasesHandled();
|
|
1336
2025
|
this._clock.start();
|
|
1337
2026
|
const currentTick = this._tempoMap.secondsToTicks(currentTime);
|
|
1338
2027
|
this._clipPlayer.onPositionJump(currentTick);
|
|
@@ -1372,6 +2061,8 @@ var _Transport = class _Transport {
|
|
|
1372
2061
|
}
|
|
1373
2062
|
}
|
|
1374
2063
|
seek(time) {
|
|
2064
|
+
if (this._refuseIfDisposed("seek")) return;
|
|
2065
|
+
assertFiniteSeconds("seek", "time", time);
|
|
1375
2066
|
const wasPlaying = this._playing;
|
|
1376
2067
|
const wasCountingIn = this._countingIn;
|
|
1377
2068
|
if (wasCountingIn) {
|
|
@@ -1383,6 +2074,7 @@ var _Transport = class _Transport {
|
|
|
1383
2074
|
}
|
|
1384
2075
|
this._silenceAll();
|
|
1385
2076
|
this._clock.seekTo(time);
|
|
2077
|
+
this._markRebasesHandled();
|
|
1386
2078
|
this._scheduler.reset(time);
|
|
1387
2079
|
this._endTime = void 0;
|
|
1388
2080
|
this._scheduler.setPlayEnd(null);
|
|
@@ -1404,6 +2096,32 @@ var _Transport = class _Transport {
|
|
|
1404
2096
|
}
|
|
1405
2097
|
return t;
|
|
1406
2098
|
}
|
|
2099
|
+
/** Current position in whole AudioContext frames (the clock's native unit
|
|
2100
|
+
* for elapsed time). Same loop-wrap clamp and count-in hold as
|
|
2101
|
+
* getCurrentTime(). CONTEXT-rate frames — `getCurrentSample()` is the
|
|
2102
|
+
* timeline-rate view. */
|
|
2103
|
+
getCurrentFrame() {
|
|
2104
|
+
if (this._countingIn) {
|
|
2105
|
+
return this._clock.secondsToFrame(this._countInStartPosition);
|
|
2106
|
+
}
|
|
2107
|
+
const frame = this._clock.getFrame();
|
|
2108
|
+
const loopStartFrame = this._clock.secondsToFrame(this._loopStartSeconds);
|
|
2109
|
+
if (this._loopEnabled && frame < loopStartFrame) {
|
|
2110
|
+
return loopStartFrame;
|
|
2111
|
+
}
|
|
2112
|
+
return frame;
|
|
2113
|
+
}
|
|
2114
|
+
/** Current position in SampleTimeline samples (the `sampleRate` option's
|
|
2115
|
+
* rate; equal to getCurrentFrame() only when that matches the context).
|
|
2116
|
+
* Rounded once, at the Sample boundary. */
|
|
2117
|
+
getCurrentSample() {
|
|
2118
|
+
return this._sampleTimeline.secondsToSamples(this.getCurrentTime());
|
|
2119
|
+
}
|
|
2120
|
+
/** How many backward AudioContext clock readings the transport has absorbed
|
|
2121
|
+
* (see the `discontinuity` event). Diagnostics. */
|
|
2122
|
+
get rebaseCount() {
|
|
2123
|
+
return this._clock.rebaseCount;
|
|
2124
|
+
}
|
|
1407
2125
|
isPlaying() {
|
|
1408
2126
|
return this._playing;
|
|
1409
2127
|
}
|
|
@@ -1417,7 +2135,7 @@ var _Transport = class _Transport {
|
|
|
1417
2135
|
this._mutedTrackIds.clear();
|
|
1418
2136
|
this._tracks = tracks;
|
|
1419
2137
|
for (const track of tracks) {
|
|
1420
|
-
const trackNode = new TrackNode(track.id, this._audioContext);
|
|
2138
|
+
const trackNode = new TrackNode(track.id, this._audioContext, trackChannelCount(track));
|
|
1421
2139
|
trackNode.setVolume(track.volume);
|
|
1422
2140
|
trackNode.setPan(track.pan);
|
|
1423
2141
|
trackNode.connectOutput(this._masterNode.input);
|
|
@@ -1433,7 +2151,7 @@ var _Transport = class _Transport {
|
|
|
1433
2151
|
this._clipPlayer.setTracks(tracks, this._trackNodes);
|
|
1434
2152
|
}
|
|
1435
2153
|
addTrack(track) {
|
|
1436
|
-
const trackNode = new TrackNode(track.id, this._audioContext);
|
|
2154
|
+
const trackNode = new TrackNode(track.id, this._audioContext, trackChannelCount(track));
|
|
1437
2155
|
trackNode.setVolume(track.volume);
|
|
1438
2156
|
trackNode.setPan(track.pan);
|
|
1439
2157
|
trackNode.connectOutput(this._masterNode.input);
|
|
@@ -1466,6 +2184,7 @@ var _Transport = class _Transport {
|
|
|
1466
2184
|
if (node) {
|
|
1467
2185
|
node.setVolume(track.volume);
|
|
1468
2186
|
node.setPan(track.pan);
|
|
2187
|
+
node.setSourceChannelCount(trackChannelCount(track));
|
|
1469
2188
|
}
|
|
1470
2189
|
if (track.muted) {
|
|
1471
2190
|
this._mutedTrackIds.add(trackId);
|
|
@@ -1518,14 +2237,12 @@ var _Transport = class _Transport {
|
|
|
1518
2237
|
this._masterNode.setVolume(volume);
|
|
1519
2238
|
}
|
|
1520
2239
|
// --- Loop ---
|
|
1521
|
-
/** Primary loop API — ticks as source of truth
|
|
2240
|
+
/** Primary loop API — ticks as source of truth. Throws when `enabled` and
|
|
2241
|
+
* the range is non-finite, empty or inverted; nothing is changed and no
|
|
2242
|
+
* `loop` event fires. (NativePlayoutAdapter translates the engine's
|
|
2243
|
+
* default empty region to a disabled loop before reaching here.) */
|
|
1522
2244
|
setLoop(enabled, startTick, endTick) {
|
|
1523
|
-
|
|
1524
|
-
console.warn(
|
|
1525
|
-
"[waveform-playlist] Transport.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
|
|
1526
|
-
);
|
|
1527
|
-
return;
|
|
1528
|
-
}
|
|
2245
|
+
assertValidLoopRange("Transport.setLoop", enabled, startTick, endTick, "tick");
|
|
1529
2246
|
this._loopEnabled = enabled;
|
|
1530
2247
|
this._loopStartTick = startTick;
|
|
1531
2248
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1533,28 +2250,37 @@ var _Transport = class _Transport {
|
|
|
1533
2250
|
this._clipPlayer.setLoop(enabled, startTick, endTick);
|
|
1534
2251
|
this._emit("loop");
|
|
1535
2252
|
}
|
|
1536
|
-
/** Convenience — converts seconds to ticks
|
|
2253
|
+
/** Convenience — converts seconds to ticks. Same validation as setLoop,
|
|
2254
|
+
* applied in seconds so the error names the caller's unit. */
|
|
1537
2255
|
setLoopSeconds(enabled, startSec, endSec) {
|
|
2256
|
+
assertValidLoopRange("Transport.setLoopSeconds", enabled, startSec, endSec, "second");
|
|
1538
2257
|
const startTick = this._tempoMap.secondsToTicks(startSec);
|
|
1539
2258
|
const endTick = this._tempoMap.secondsToTicks(endSec);
|
|
2259
|
+
assertLoopRangeSpansATick(
|
|
2260
|
+
"Transport.setLoopSeconds",
|
|
2261
|
+
enabled,
|
|
2262
|
+
startSec,
|
|
2263
|
+
endSec,
|
|
2264
|
+
"second",
|
|
2265
|
+
startTick,
|
|
2266
|
+
endTick
|
|
2267
|
+
);
|
|
1540
2268
|
this.setLoop(enabled, startTick, endTick);
|
|
1541
2269
|
}
|
|
1542
|
-
/** Convenience — sets loop in samples */
|
|
2270
|
+
/** Convenience — sets loop in samples. Same validation as setLoop. */
|
|
1543
2271
|
setLoopSamples(enabled, startSample, endSample) {
|
|
1544
|
-
|
|
1545
|
-
console.warn(
|
|
1546
|
-
"[waveform-playlist] Transport.setLoopSamples: non-finite sample values (" + startSample + ", " + endSample + ")"
|
|
1547
|
-
);
|
|
1548
|
-
return;
|
|
1549
|
-
}
|
|
1550
|
-
if (enabled && startSample >= endSample) {
|
|
1551
|
-
console.warn(
|
|
1552
|
-
"[waveform-playlist] Transport.setLoopSamples: startSample (" + startSample + ") must be less than endSample (" + endSample + ")"
|
|
1553
|
-
);
|
|
1554
|
-
return;
|
|
1555
|
-
}
|
|
2272
|
+
assertValidLoopRange("Transport.setLoopSamples", enabled, startSample, endSample, "sample");
|
|
1556
2273
|
const startTick = this._sampleTimeline.samplesToTicks(startSample);
|
|
1557
2274
|
const endTick = this._sampleTimeline.samplesToTicks(endSample);
|
|
2275
|
+
assertLoopRangeSpansATick(
|
|
2276
|
+
"Transport.setLoopSamples",
|
|
2277
|
+
enabled,
|
|
2278
|
+
startSample,
|
|
2279
|
+
endSample,
|
|
2280
|
+
"sample",
|
|
2281
|
+
startTick,
|
|
2282
|
+
endTick
|
|
2283
|
+
);
|
|
1558
2284
|
this._loopEnabled = enabled;
|
|
1559
2285
|
this._loopStartTick = startTick;
|
|
1560
2286
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1573,7 +2299,7 @@ var _Transport = class _Transport {
|
|
|
1573
2299
|
);
|
|
1574
2300
|
return false;
|
|
1575
2301
|
}
|
|
1576
|
-
this._tempoMap.
|
|
2302
|
+
this._replaceTempoMap(this._tempoMap.withTempo(bpm, atTick, options));
|
|
1577
2303
|
if (this._loopEnabled) {
|
|
1578
2304
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1579
2305
|
}
|
|
@@ -1610,7 +2336,7 @@ var _Transport = class _Transport {
|
|
|
1610
2336
|
});
|
|
1611
2337
|
}
|
|
1612
2338
|
clearTempos() {
|
|
1613
|
-
this._tempoMap.
|
|
2339
|
+
this._replaceTempoMap(this._tempoMap.withoutTempos());
|
|
1614
2340
|
if (this._loopEnabled) {
|
|
1615
2341
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1616
2342
|
}
|
|
@@ -1621,7 +2347,7 @@ var _Transport = class _Transport {
|
|
|
1621
2347
|
* invalidation and event; the emitted bpm is the tempo now in force at
|
|
1622
2348
|
* the removed position. */
|
|
1623
2349
|
removeTempo(atTick) {
|
|
1624
|
-
this._tempoMap.
|
|
2350
|
+
this._replaceTempoMap(this._tempoMap.withoutTempo(atTick));
|
|
1625
2351
|
if (this._loopEnabled) {
|
|
1626
2352
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1627
2353
|
}
|
|
@@ -1630,14 +2356,28 @@ var _Transport = class _Transport {
|
|
|
1630
2356
|
barToTick(bar) {
|
|
1631
2357
|
return this._meterMap.barToTick(bar);
|
|
1632
2358
|
}
|
|
2359
|
+
/** Snap a (possibly fractional) tick to the meter grid: `subdivision` is
|
|
2360
|
+
* `{ ticks }`, `{ note, dotted?, triplet? }`, 'bar' or 'beat'; `mode` is
|
|
2361
|
+
* 'nearest' (default) | 'next' | 'previous'; `strength` 0–1 scales the
|
|
2362
|
+
* move. Grid lines restart at each bar line, so odd meters stay aligned.
|
|
2363
|
+
* Pure function over the (live) MeterMap. */
|
|
2364
|
+
quantizeTick(tick, subdivision, options) {
|
|
2365
|
+
return quantizeTick(this._meterMap, tick, subdivision, options);
|
|
2366
|
+
}
|
|
1633
2367
|
tickToBar(tick) {
|
|
1634
2368
|
return this._meterMap.tickToBar(tick);
|
|
1635
2369
|
}
|
|
1636
|
-
/** Convert transport time (seconds) to tick position, using the tempo map. */
|
|
2370
|
+
/** Convert transport time (seconds) to an integer tick position, using the tempo map. */
|
|
1637
2371
|
timeToTick(seconds) {
|
|
1638
2372
|
return this._tempoMap.secondsToTicks(seconds);
|
|
1639
2373
|
}
|
|
1640
|
-
/** Convert
|
|
2374
|
+
/** Convert transport time (seconds) to a fractional tick position — for
|
|
2375
|
+
* sub-tick placement (e.g. a recorded note between ticks, before quantising). */
|
|
2376
|
+
timeToTickExact(seconds) {
|
|
2377
|
+
return this._tempoMap.secondsToTicksExact(seconds);
|
|
2378
|
+
}
|
|
2379
|
+
/** Convert a tick position (integer Tick or the fractional value
|
|
2380
|
+
* timeToTickExact returned) to transport time (seconds). */
|
|
1641
2381
|
tickToTime(tick) {
|
|
1642
2382
|
return this._tempoMap.ticksToSeconds(tick);
|
|
1643
2383
|
}
|
|
@@ -1681,18 +2421,30 @@ var _Transport = class _Transport {
|
|
|
1681
2421
|
return this._countingIn;
|
|
1682
2422
|
}
|
|
1683
2423
|
// --- Effects Hook ---
|
|
1684
|
-
|
|
2424
|
+
/**
|
|
2425
|
+
* Insert an effects chain on a track, PRE-FADER: clip sources → `input` …
|
|
2426
|
+
* `output` → volume → pan → mute → master. Accepts any AudioNode chain
|
|
2427
|
+
* (native nodes, WAM plugins, Tone.js effects) — pass the same node twice
|
|
2428
|
+
* for a single-node effect. The transport owns both edges; do NOT connect
|
|
2429
|
+
* `output` to the master bus yourself (that would bypass the fader, pan
|
|
2430
|
+
* and mute). Calling again replaces the previous chain.
|
|
2431
|
+
*
|
|
2432
|
+
* `setTracks()` rebuilds every track node, dropping these hookups —
|
|
2433
|
+
* reconnect afterwards.
|
|
2434
|
+
*/
|
|
2435
|
+
connectTrackEffects(trackId, input, output) {
|
|
1685
2436
|
const trackNode = this._trackNodes.get(trackId);
|
|
1686
2437
|
if (!trackNode) {
|
|
1687
|
-
console.warn('[waveform-playlist]
|
|
2438
|
+
console.warn('[waveform-playlist] connectTrackEffects: unknown trackId "' + trackId + '"');
|
|
1688
2439
|
return;
|
|
1689
2440
|
}
|
|
1690
|
-
trackNode.connectEffects(
|
|
2441
|
+
trackNode.connectEffects(input, output);
|
|
1691
2442
|
}
|
|
1692
|
-
|
|
2443
|
+
/** Remove a track's effects chain and restore its direct routing. */
|
|
2444
|
+
disconnectTrackEffects(trackId) {
|
|
1693
2445
|
const trackNode = this._trackNodes.get(trackId);
|
|
1694
2446
|
if (!trackNode) {
|
|
1695
|
-
console.warn('[waveform-playlist]
|
|
2447
|
+
console.warn('[waveform-playlist] disconnectTrackEffects: unknown trackId "' + trackId + '"');
|
|
1696
2448
|
return;
|
|
1697
2449
|
}
|
|
1698
2450
|
trackNode.disconnectEffects();
|
|
@@ -1729,18 +2481,20 @@ var _Transport = class _Transport {
|
|
|
1729
2481
|
// --- Dispose ---
|
|
1730
2482
|
dispose() {
|
|
1731
2483
|
this.stop();
|
|
2484
|
+
this._disposed = true;
|
|
1732
2485
|
for (const node of this._trackNodes.values()) {
|
|
1733
2486
|
node.dispose();
|
|
1734
2487
|
}
|
|
1735
2488
|
this._trackNodes.clear();
|
|
1736
2489
|
this._masterNode.dispose();
|
|
2490
|
+
this._timer.dispose();
|
|
1737
2491
|
this._listeners.clear();
|
|
1738
2492
|
}
|
|
1739
2493
|
// --- Private ---
|
|
1740
|
-
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead) {
|
|
1741
|
-
if (sampleRate
|
|
2494
|
+
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead, timerIntervalMs) {
|
|
2495
|
+
if (!(Number.isFinite(sampleRate) && sampleRate > 0)) {
|
|
1742
2496
|
throw new Error(
|
|
1743
|
-
"[waveform-playlist] Transport: sampleRate must be positive, got " + sampleRate
|
|
2497
|
+
"[waveform-playlist] Transport: options.sampleRate must be a positive finite number, got " + sampleRate
|
|
1744
2498
|
);
|
|
1745
2499
|
}
|
|
1746
2500
|
if (ppqn <= 0 || !Number.isInteger(ppqn)) {
|
|
@@ -1766,6 +2520,11 @@ var _Transport = class _Transport {
|
|
|
1766
2520
|
"[waveform-playlist] Transport: schedulerLookahead must be positive, got " + lookahead
|
|
1767
2521
|
);
|
|
1768
2522
|
}
|
|
2523
|
+
if (!(timerIntervalMs > 0) || timerIntervalMs >= lookahead * 1e3) {
|
|
2524
|
+
throw new Error(
|
|
2525
|
+
"[waveform-playlist] Transport: timerIntervalMs must be positive and shorter than the lookahead (" + lookahead * 1e3 + " ms), got " + timerIntervalMs
|
|
2526
|
+
);
|
|
2527
|
+
}
|
|
1769
2528
|
}
|
|
1770
2529
|
_initAudioGraph(audioContext) {
|
|
1771
2530
|
this._masterNode = new MasterNode(audioContext);
|
|
@@ -1837,7 +2596,8 @@ var _Transport = class _Transport {
|
|
|
1837
2596
|
const countInMeterMap = new MeterMap(this._ppqn, meter.numerator, meter.denominator);
|
|
1838
2597
|
this._countInDuration = countInTempoMap.ticksToSeconds(countInTicks);
|
|
1839
2598
|
this._countInScheduler = new Scheduler(countInTempoMap, {
|
|
1840
|
-
lookahead: this._schedulerLookahead
|
|
2599
|
+
lookahead: this._schedulerLookahead,
|
|
2600
|
+
onError: (error) => this._emitError(error)
|
|
1841
2601
|
});
|
|
1842
2602
|
this._countInPlayer.configure({
|
|
1843
2603
|
totalBeats,
|
|
@@ -1852,6 +2612,7 @@ var _Transport = class _Transport {
|
|
|
1852
2612
|
this._countInScheduler.addListener(this._countInPlayer);
|
|
1853
2613
|
this._countInScheduler.reset(0);
|
|
1854
2614
|
this._clock.seekTo(0);
|
|
2615
|
+
this._markRebasesHandled();
|
|
1855
2616
|
this._clock.start();
|
|
1856
2617
|
this._timer.start();
|
|
1857
2618
|
}
|
|
@@ -1874,6 +2635,28 @@ var _Transport = class _Transport {
|
|
|
1874
2635
|
this._countingIn = false;
|
|
1875
2636
|
this._timer.stop();
|
|
1876
2637
|
}
|
|
2638
|
+
/** Install a new immutable TempoMap everywhere one is held. The count-in
|
|
2639
|
+
* player is configured with its own dedicated map at each count-in start,
|
|
2640
|
+
* so it is not on this list. */
|
|
2641
|
+
_replaceTempoMap(next) {
|
|
2642
|
+
this._tempoMap = next;
|
|
2643
|
+
this._scheduler.setTempoMap(next);
|
|
2644
|
+
this._sampleTimeline.setTempoMap(next);
|
|
2645
|
+
this._clipPlayer.setTempoMap(next);
|
|
2646
|
+
this._metronomePlayer.setTempoMap(next);
|
|
2647
|
+
if (this._endTime !== void 0) {
|
|
2648
|
+
this._scheduler.setPlayEnd(next.secondsToTicks(this._endTime));
|
|
2649
|
+
}
|
|
2650
|
+
}
|
|
2651
|
+
/** A disposed transport has no timer or audio graph; a late play()/seek()
|
|
2652
|
+
* must not report "playing" with nothing ticking. */
|
|
2653
|
+
_refuseIfDisposed(what) {
|
|
2654
|
+
if (!this._disposed) return false;
|
|
2655
|
+
console.warn(
|
|
2656
|
+
"[waveform-playlist] Transport: " + what + "() on a disposed transport is ignored"
|
|
2657
|
+
);
|
|
2658
|
+
return true;
|
|
2659
|
+
}
|
|
1877
2660
|
_silenceAll() {
|
|
1878
2661
|
this._clipPlayer.silence();
|
|
1879
2662
|
this._metronomePlayer.silence();
|
|
@@ -1887,6 +2670,22 @@ var _Transport = class _Transport {
|
|
|
1887
2670
|
node.setMute(isExplicitlyMuted || isSoloMuted);
|
|
1888
2671
|
}
|
|
1889
2672
|
}
|
|
2673
|
+
/** Route a scheduler listener failure to `error` subscribers, or to
|
|
2674
|
+
* console.warn (once per listener and failure kind) when nobody is listening —
|
|
2675
|
+
* the failure must stay visible either way. Subscribers are called on a
|
|
2676
|
+
* microtask, after the scheduler window that produced the failure has
|
|
2677
|
+
* completed: a handler that reacts with stop()/setTracks()/off() must not
|
|
2678
|
+
* re-enter the listener iteration that is still running. */
|
|
2679
|
+
_emitError(error) {
|
|
2680
|
+
queueMicrotask(() => {
|
|
2681
|
+
const listeners = this._listeners.get("error");
|
|
2682
|
+
if (listeners && listeners.size > 0) {
|
|
2683
|
+
this._emit("error", error);
|
|
2684
|
+
} else {
|
|
2685
|
+
this._errorLog.warnOnce(error);
|
|
2686
|
+
}
|
|
2687
|
+
});
|
|
2688
|
+
}
|
|
1890
2689
|
_emit(event, ...args) {
|
|
1891
2690
|
const listeners = this._listeners.get(event);
|
|
1892
2691
|
if (listeners) {
|
|
@@ -1907,12 +2706,21 @@ var _Transport = class _Transport {
|
|
|
1907
2706
|
_Transport.MIN_COUNT_IN_BARS = 1;
|
|
1908
2707
|
_Transport.MAX_COUNT_IN_BARS = 8;
|
|
1909
2708
|
var Transport = _Transport;
|
|
2709
|
+
function assertFiniteSeconds(method, name, value) {
|
|
2710
|
+
if (!Number.isFinite(value)) {
|
|
2711
|
+
throw new Error(
|
|
2712
|
+
"[waveform-playlist] Transport." + method + ": " + name + " must be finite, got " + value
|
|
2713
|
+
);
|
|
2714
|
+
}
|
|
2715
|
+
}
|
|
1910
2716
|
|
|
1911
2717
|
// src/adapter.ts
|
|
1912
2718
|
var NativePlayoutAdapter = class {
|
|
1913
2719
|
constructor(audioContext, options) {
|
|
2720
|
+
this._onPlaybackEnded = null;
|
|
1914
2721
|
this._audioContext = audioContext;
|
|
1915
2722
|
this._transport = new Transport(audioContext, options);
|
|
2723
|
+
this._transport.on("ended", () => this._onPlaybackEnded?.());
|
|
1916
2724
|
}
|
|
1917
2725
|
get audioContext() {
|
|
1918
2726
|
return this._audioContext;
|
|
@@ -1933,21 +2741,26 @@ var NativePlayoutAdapter = class {
|
|
|
1933
2741
|
const warmupTarget = Math.max(MIN_WARMUP, this._audioContext.outputLatency ?? MIN_WARMUP);
|
|
1934
2742
|
if (this._audioContext.currentTime < warmupTarget) {
|
|
1935
2743
|
const MAX_WARMUP_MS = 2e3;
|
|
1936
|
-
|
|
2744
|
+
const WARMUP_POLL_MS = 16;
|
|
2745
|
+
await new Promise((resolve, reject) => {
|
|
1937
2746
|
const startMs = performance.now();
|
|
1938
2747
|
const check = () => {
|
|
1939
2748
|
if (this._audioContext.currentTime >= warmupTarget) {
|
|
1940
2749
|
resolve();
|
|
1941
|
-
} else if (this._audioContext.state === "closed"
|
|
2750
|
+
} else if (this._audioContext.state === "closed") {
|
|
2751
|
+
reject(
|
|
2752
|
+
new Error("[waveform-playlist] Cannot init: AudioContext closed during warmup")
|
|
2753
|
+
);
|
|
2754
|
+
} else if (performance.now() - startMs > MAX_WARMUP_MS) {
|
|
1942
2755
|
console.warn(
|
|
1943
2756
|
"[waveform-playlist] AudioContext warmup timed out (currentTime=" + this._audioContext.currentTime + ", target=" + warmupTarget + ", state=" + this._audioContext.state + "). Proceeding without warmup."
|
|
1944
2757
|
);
|
|
1945
2758
|
resolve();
|
|
1946
2759
|
} else {
|
|
1947
|
-
|
|
2760
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1948
2761
|
}
|
|
1949
2762
|
};
|
|
1950
|
-
|
|
2763
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1951
2764
|
});
|
|
1952
2765
|
}
|
|
1953
2766
|
}
|
|
@@ -1973,6 +2786,13 @@ var NativePlayoutAdapter = class {
|
|
|
1973
2786
|
stop() {
|
|
1974
2787
|
this._transport.stop();
|
|
1975
2788
|
}
|
|
2789
|
+
/** Engine hook: adapter-initiated completion of a bounded play(start, end)
|
|
2790
|
+
* (the transport's `ended` event). Never fired for a consumer
|
|
2791
|
+
* stop()/pause()/seek()/dispose(), whether issued through this adapter or
|
|
2792
|
+
* directly on `adapter.transport`. */
|
|
2793
|
+
onPlaybackEnded(callback) {
|
|
2794
|
+
this._onPlaybackEnded = callback;
|
|
2795
|
+
}
|
|
1976
2796
|
seek(time) {
|
|
1977
2797
|
this._transport.seek(time);
|
|
1978
2798
|
}
|
|
@@ -1998,7 +2818,13 @@ var NativePlayoutAdapter = class {
|
|
|
1998
2818
|
this._transport.setTrackPan(trackId, pan);
|
|
1999
2819
|
}
|
|
2000
2820
|
setLoop(enabled, start, end) {
|
|
2001
|
-
|
|
2821
|
+
const finite = Number.isFinite(start) && Number.isFinite(end);
|
|
2822
|
+
const degenerate = enabled && finite && this._transport.timeToTick(start) >= this._transport.timeToTick(end);
|
|
2823
|
+
if (degenerate && !(start === 0 && end === 0)) {
|
|
2824
|
+
const why = start > end ? "inverted loop region (" + start + " > " + end + ")" : start === end ? "empty loop region (" + start + ")" : "loop region (" + start + ", " + end + ") is shorter than one tick";
|
|
2825
|
+
console.warn("[waveform-playlist] NativePlayoutAdapter.setLoop: " + why + " \u2014 loop disabled");
|
|
2826
|
+
}
|
|
2827
|
+
this._transport.setLoopSeconds(enabled && !degenerate, start, end);
|
|
2002
2828
|
}
|
|
2003
2829
|
setCountIn(enabled) {
|
|
2004
2830
|
this._transport.setCountIn(enabled);
|
|
@@ -2031,25 +2857,33 @@ var NativePlayoutAdapter = class {
|
|
|
2031
2857
|
secondsToTicks(seconds) {
|
|
2032
2858
|
return this._transport.timeToTick(seconds);
|
|
2033
2859
|
}
|
|
2860
|
+
/** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
|
|
2861
|
+
secondsToTicksExact(seconds) {
|
|
2862
|
+
return this._transport.timeToTickExact(seconds);
|
|
2863
|
+
}
|
|
2034
2864
|
get masterOutputNode() {
|
|
2035
2865
|
return this._transport.masterOutputNode;
|
|
2036
2866
|
}
|
|
2037
2867
|
dispose() {
|
|
2868
|
+
this._onPlaybackEnded = null;
|
|
2038
2869
|
this._transport.dispose();
|
|
2039
2870
|
}
|
|
2040
2871
|
};
|
|
2041
2872
|
export {
|
|
2042
2873
|
ClipPlayer,
|
|
2043
2874
|
Clock,
|
|
2875
|
+
DEFAULT_TIMER_INTERVAL_MS,
|
|
2044
2876
|
MasterNode,
|
|
2045
2877
|
MeterMap,
|
|
2046
2878
|
MetronomePlayer,
|
|
2047
2879
|
NativePlayoutAdapter,
|
|
2880
|
+
RENDER_QUANTUM_FRAMES,
|
|
2048
2881
|
SampleTimeline,
|
|
2049
2882
|
Scheduler,
|
|
2050
2883
|
TempoMap,
|
|
2051
2884
|
Timer,
|
|
2052
2885
|
TrackNode,
|
|
2053
|
-
Transport
|
|
2886
|
+
Transport,
|
|
2887
|
+
quantizeTick
|
|
2054
2888
|
};
|
|
2055
2889
|
//# sourceMappingURL=index.mjs.map
|