@dawcore/transport 0.0.13 → 0.0.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +24 -8
- package/dist/index.d.mts +504 -43
- package/dist/index.d.ts +504 -43
- package/dist/index.js +1048 -238
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1044 -237
- package/dist/index.mjs.map +1 -1
- package/package.json +4 -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;
|
|
@@ -57,9 +215,34 @@ var Scheduler = class {
|
|
|
57
215
|
this._loopStart = 0;
|
|
58
216
|
// integer ticks
|
|
59
217
|
this._loopEnd = 0;
|
|
218
|
+
// integer ticks
|
|
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;
|
|
60
223
|
this._tempoMap = tempoMap;
|
|
61
224
|
this._lookahead = options.lookahead ?? 0.2;
|
|
62
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;
|
|
63
246
|
}
|
|
64
247
|
addListener(listener) {
|
|
65
248
|
this._listeners.add(listener);
|
|
@@ -67,116 +250,296 @@ var Scheduler = class {
|
|
|
67
250
|
removeListener(listener) {
|
|
68
251
|
this._listeners.delete(listener);
|
|
69
252
|
}
|
|
70
|
-
/** 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. */
|
|
71
255
|
setLoop(enabled, startTick, endTick) {
|
|
72
|
-
|
|
73
|
-
console.warn(
|
|
74
|
-
"[waveform-playlist] Scheduler.setLoop: non-finite tick values (" + startTick + ", " + endTick + ")"
|
|
75
|
-
);
|
|
76
|
-
return;
|
|
77
|
-
}
|
|
78
|
-
if (enabled && startTick >= endTick) {
|
|
79
|
-
console.warn(
|
|
80
|
-
"[waveform-playlist] Scheduler.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
|
|
81
|
-
);
|
|
82
|
-
return;
|
|
83
|
-
}
|
|
256
|
+
assertValidLoopRange("Scheduler.setLoop", enabled, startTick, endTick, "tick");
|
|
84
257
|
this._loopEnabled = enabled;
|
|
85
258
|
this._loopStart = Math.round(startTick);
|
|
86
259
|
this._loopEnd = Math.round(endTick);
|
|
87
260
|
}
|
|
88
261
|
/** Convenience — converts seconds to ticks via TempoMap */
|
|
89
262
|
setLoopSeconds(enabled, startSec, endSec) {
|
|
263
|
+
assertValidLoopRange("Scheduler.setLoopSeconds", enabled, startSec, endSec, "second");
|
|
90
264
|
const startTick = this._tempoMap.secondsToTicks(startSec);
|
|
91
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
|
+
);
|
|
92
275
|
this.setLoop(enabled, startTick, endTick);
|
|
93
276
|
}
|
|
94
|
-
/**
|
|
277
|
+
/** Hard end bound (ticks) for non-loop playback: the lookahead window never
|
|
278
|
+
* generates events at or beyond this tick, so audio (metronome clicks, clips)
|
|
279
|
+
* can't be scheduled past the playback end and sound a beat into the next
|
|
280
|
+
* (nonexistent) bar. Null = unbounded. Set from Transport.play()'s endTime; the
|
|
281
|
+
* loop path is unaffected (loopEnd already bounds it). */
|
|
282
|
+
setPlayEnd(endTick) {
|
|
283
|
+
this._playEnd = endTick == null ? null : Math.round(endTick);
|
|
284
|
+
}
|
|
285
|
+
/** Reset scheduling cursor. Takes seconds (from Clock), converts to integer
|
|
286
|
+
* ticks — secondsToTicks rounds once here; the cursor is always whole ticks. */
|
|
95
287
|
reset(timeSeconds) {
|
|
96
288
|
this._rightEdge = this._tempoMap.secondsToTicks(timeSeconds);
|
|
97
289
|
}
|
|
98
290
|
/** Advance the scheduling window. Takes seconds (from Clock), converts to ticks. */
|
|
99
291
|
advance(currentTimeSeconds) {
|
|
100
|
-
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);
|
|
101
305
|
if (this._loopEnabled && this._loopEnd > this._loopStart) {
|
|
102
|
-
const loopDuration = this._loopEnd - this._loopStart;
|
|
103
306
|
let remaining = targetTick - this._rightEdge;
|
|
104
307
|
while (remaining > 0) {
|
|
105
308
|
const distToEnd = this._loopEnd - this._rightEdge;
|
|
106
|
-
if (distToEnd
|
|
309
|
+
if (distToEnd > remaining) {
|
|
107
310
|
this._generateAndConsume(this._rightEdge, this._rightEdge + remaining);
|
|
108
311
|
this._rightEdge += remaining;
|
|
109
312
|
break;
|
|
110
313
|
}
|
|
111
|
-
|
|
112
|
-
|
|
314
|
+
if (distToEnd > 0) {
|
|
315
|
+
this._generateAndConsume(this._rightEdge, this._loopEnd);
|
|
316
|
+
remaining -= distToEnd;
|
|
317
|
+
}
|
|
113
318
|
for (const listener of this._listeners) {
|
|
114
|
-
|
|
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
|
+
}
|
|
115
329
|
}
|
|
116
330
|
this._onLoop?.(
|
|
117
|
-
|
|
118
|
-
|
|
331
|
+
tempoMap.ticksToSeconds(this._loopStart),
|
|
332
|
+
tempoMap.ticksToSeconds(this._loopEnd),
|
|
119
333
|
currentTimeSeconds
|
|
120
334
|
);
|
|
121
335
|
this._rightEdge = this._loopStart;
|
|
122
|
-
if (loopDuration <= 0) break;
|
|
123
336
|
}
|
|
124
337
|
return;
|
|
125
338
|
}
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
this._rightEdge
|
|
339
|
+
const bound = this._playEnd !== null && targetTick > this._playEnd ? this._playEnd : targetTick;
|
|
340
|
+
if (bound > this._rightEdge) {
|
|
341
|
+
this._generateAndConsume(this._rightEdge, bound);
|
|
342
|
+
this._rightEdge = bound;
|
|
129
343
|
}
|
|
130
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
|
+
}
|
|
131
357
|
_generateAndConsume(fromTick, toTick) {
|
|
132
358
|
for (const listener of this._listeners) {
|
|
359
|
+
let events;
|
|
133
360
|
try {
|
|
134
|
-
|
|
135
|
-
for (const event of events) {
|
|
136
|
-
try {
|
|
137
|
-
listener.consume(event);
|
|
138
|
-
} catch (err) {
|
|
139
|
-
console.warn("[waveform-playlist] Scheduler: error consuming event:", String(err));
|
|
140
|
-
}
|
|
141
|
-
}
|
|
361
|
+
events = listener.generate(fromTick, toTick);
|
|
142
362
|
} catch (err) {
|
|
143
|
-
|
|
363
|
+
this._reportError({
|
|
364
|
+
phase: "generate",
|
|
365
|
+
listener,
|
|
366
|
+
fromTick,
|
|
367
|
+
toTick,
|
|
368
|
+
error: err
|
|
369
|
+
});
|
|
370
|
+
continue;
|
|
144
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
|
+
}
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
}
|
|
381
|
+
_reportError(error) {
|
|
382
|
+
if (this._onError) {
|
|
383
|
+
this._onError(error);
|
|
384
|
+
return;
|
|
145
385
|
}
|
|
386
|
+
this._errorLog.warnOnce(error);
|
|
146
387
|
}
|
|
147
388
|
};
|
|
148
389
|
|
|
149
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
|
+
}
|
|
150
403
|
var Timer = class {
|
|
151
|
-
constructor(onTick) {
|
|
152
|
-
this._rafId = null;
|
|
404
|
+
constructor(onTick, options = {}) {
|
|
153
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
|
+
}
|
|
154
421
|
this._onTick = onTick;
|
|
422
|
+
this._intervalMs = intervalMs;
|
|
155
423
|
}
|
|
156
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
|
+
}
|
|
157
432
|
if (this._running) return;
|
|
158
433
|
this._running = true;
|
|
159
|
-
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
|
+
}
|
|
160
441
|
}
|
|
161
442
|
stop() {
|
|
443
|
+
if (!this._running) return;
|
|
162
444
|
this._running = false;
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
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;
|
|
166
452
|
}
|
|
167
453
|
}
|
|
168
|
-
|
|
169
|
-
|
|
170
|
-
|
|
171
|
-
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
|
|
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
|
+
}
|
|
180
543
|
}
|
|
181
544
|
};
|
|
182
545
|
|
|
@@ -199,36 +562,100 @@ var SampleTimeline = class {
|
|
|
199
562
|
return Math.round(seconds * this._sampleRate);
|
|
200
563
|
}
|
|
201
564
|
ticksToSamples(ticks) {
|
|
202
|
-
|
|
203
|
-
throw new Error(
|
|
204
|
-
"[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
|
|
205
|
-
);
|
|
206
|
-
}
|
|
207
|
-
return Math.round(this._tempoMap.ticksToSeconds(ticks) * this._sampleRate);
|
|
565
|
+
return Math.round(this._requireTempoMap().ticksToSeconds(ticks) * this._sampleRate);
|
|
208
566
|
}
|
|
567
|
+
/** Samples → integer ticks. The integer `Tick` contract belongs to THIS
|
|
568
|
+
* boundary: exactly one rounding, applied to the fractional position. */
|
|
209
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() {
|
|
210
577
|
if (!this._tempoMap) {
|
|
211
578
|
throw new Error(
|
|
212
579
|
"[waveform-playlist] SampleTimeline: tempoMap not set \u2014 call setTempoMap() first"
|
|
213
580
|
);
|
|
214
581
|
}
|
|
215
|
-
return
|
|
582
|
+
return this._tempoMap;
|
|
216
583
|
}
|
|
217
584
|
};
|
|
218
585
|
|
|
219
586
|
// src/timeline/tempo-map.ts
|
|
220
587
|
var CURVE_EPSILON = 1e-15;
|
|
221
|
-
var
|
|
222
|
-
function
|
|
223
|
-
|
|
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) {
|
|
224
593
|
const p = Math.max(CURVE_EPSILON, Math.min(1 - CURVE_EPSILON, slope));
|
|
225
|
-
|
|
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
|
+
}
|
|
226
639
|
}
|
|
227
640
|
var TempoMap = class _TempoMap {
|
|
228
|
-
constructor(ppqn = 960,
|
|
229
|
-
|
|
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
|
+
}
|
|
230
645
|
this._ppqn = ppqn;
|
|
231
|
-
|
|
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
|
+
}
|
|
232
659
|
}
|
|
233
660
|
/** A non-finite or non-positive BPM silently corrupts the secondsAtTick
|
|
234
661
|
* cache (Infinity, or non-monotonic values that break the binary search
|
|
@@ -248,37 +675,110 @@ var TempoMap = class _TempoMap {
|
|
|
248
675
|
get entryCount() {
|
|
249
676
|
return this._entries.length;
|
|
250
677
|
}
|
|
251
|
-
|
|
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) {
|
|
252
687
|
_TempoMap._validateBpm(bpm);
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
688
|
+
validateTick("atTick", atTick);
|
|
689
|
+
const requested = options?.interpolation ?? "step";
|
|
690
|
+
if (typeof requested === "object" && requested.type === "curve") {
|
|
691
|
+
const s = requested.slope;
|
|
256
692
|
if (!Number.isFinite(s) || s <= 0 || s >= 1) {
|
|
257
693
|
throw new Error(
|
|
258
694
|
"[waveform-playlist] TempoMap: curve slope must be between 0 and 1 (exclusive), got " + s
|
|
259
695
|
);
|
|
260
696
|
}
|
|
261
697
|
}
|
|
698
|
+
const interpolation = freezeInterpolation(requested);
|
|
699
|
+
const entries = [...this._entries];
|
|
262
700
|
if (atTick === 0) {
|
|
263
|
-
|
|
264
|
-
this.
|
|
265
|
-
return;
|
|
701
|
+
entries[0] = { ...entries[0], bpm, interpolation: "step" };
|
|
702
|
+
return this._derive(entries, 0);
|
|
266
703
|
}
|
|
267
|
-
let i = this.
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
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 };
|
|
271
707
|
} else {
|
|
272
|
-
|
|
273
|
-
this._entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick });
|
|
708
|
+
entries.splice(i + 1, 0, { tick: atTick, bpm, interpolation, secondsAtTick: 0 });
|
|
274
709
|
i = i + 1;
|
|
275
710
|
}
|
|
276
|
-
this.
|
|
711
|
+
return this._derive(entries, i);
|
|
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));
|
|
277
757
|
}
|
|
758
|
+
/** Tick position → seconds. Accepts a fractional position (e.g. the value
|
|
759
|
+
* secondsToTicksExact returned) as well as an integer Tick. */
|
|
278
760
|
ticksToSeconds(ticks) {
|
|
279
|
-
|
|
761
|
+
assertFiniteInput("ticks", ticks);
|
|
762
|
+
return assertFiniteResult("ticks " + ticks, this._ticksToSecondsInternal(ticks));
|
|
280
763
|
}
|
|
764
|
+
/** Seconds → integer ticks, rounded once here at the `Tick` boundary.
|
|
765
|
+
* Use secondsToTicksExact() for sub-tick placement. */
|
|
281
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;
|
|
282
782
|
let lo = 0;
|
|
283
783
|
let hi = this._entries.length - 1;
|
|
284
784
|
while (lo < hi) {
|
|
@@ -293,50 +793,31 @@ var TempoMap = class _TempoMap {
|
|
|
293
793
|
const secondsIntoSegment = seconds - entry.secondsAtTick;
|
|
294
794
|
const nextEntry = lo < this._entries.length - 1 ? this._entries[lo + 1] : null;
|
|
295
795
|
if (nextEntry && nextEntry.interpolation === "linear") {
|
|
296
|
-
return
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
nextEntry.tick - entry.tick
|
|
302
|
-
)
|
|
796
|
+
return entry.tick + this._secondsToTicksLinear(
|
|
797
|
+
secondsIntoSegment,
|
|
798
|
+
entry.bpm,
|
|
799
|
+
nextEntry.bpm,
|
|
800
|
+
nextEntry.tick - entry.tick
|
|
303
801
|
);
|
|
304
802
|
}
|
|
305
803
|
if (nextEntry && typeof nextEntry.interpolation === "object") {
|
|
306
|
-
return
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
nextEntry.interpolation.slope
|
|
313
|
-
)
|
|
804
|
+
return entry.tick + this._secondsToTicksCurve(
|
|
805
|
+
secondsIntoSegment,
|
|
806
|
+
entry.bpm,
|
|
807
|
+
nextEntry.bpm,
|
|
808
|
+
nextEntry.tick - entry.tick,
|
|
809
|
+
nextEntry.interpolation.slope
|
|
314
810
|
);
|
|
315
811
|
}
|
|
316
812
|
const ticksPerSecond = entry.bpm / 60 * this._ppqn;
|
|
317
|
-
return
|
|
813
|
+
return entry.tick + secondsIntoSegment * ticksPerSecond;
|
|
318
814
|
}
|
|
319
815
|
beatsToSeconds(beats) {
|
|
320
816
|
return this.ticksToSeconds(beats * this._ppqn);
|
|
321
817
|
}
|
|
818
|
+
/** Continuous beat position (fractional) — not quantised to whole ticks. */
|
|
322
819
|
secondsToBeats(seconds) {
|
|
323
|
-
return this.
|
|
324
|
-
}
|
|
325
|
-
clearTempos() {
|
|
326
|
-
const first = this._entries[0];
|
|
327
|
-
this._entries = [{ tick: 0, bpm: first.bpm, interpolation: "step", secondsAtTick: 0 }];
|
|
328
|
-
}
|
|
329
|
-
/** Remove the tempo entry at exactly `atTick`, if one exists. The tick-0
|
|
330
|
-
* entry is permanent (a map must always have a tempo) — removing it is a
|
|
331
|
-
* no-op, matching removeMeter's treatment of the initial meter. The
|
|
332
|
-
* seconds cache is recomputed from the removal point, the same partial
|
|
333
|
-
* update setTempo uses. */
|
|
334
|
-
removeTempo(atTick) {
|
|
335
|
-
if (atTick === 0) return;
|
|
336
|
-
const i = this._entries.findIndex((e) => e.tick === atTick);
|
|
337
|
-
if (i === -1) return;
|
|
338
|
-
this._entries = [...this._entries.slice(0, i), ...this._entries.slice(i + 1)];
|
|
339
|
-
this._recomputeCache(i);
|
|
820
|
+
return this.secondsToTicksExact(seconds) / this._ppqn;
|
|
340
821
|
}
|
|
341
822
|
/** Get the interpolated BPM at a tick position */
|
|
342
823
|
_getTempoAt(atTick) {
|
|
@@ -358,6 +839,7 @@ var TempoMap = class _TempoMap {
|
|
|
358
839
|
return entry.bpm;
|
|
359
840
|
}
|
|
360
841
|
_ticksToSecondsInternal(ticks) {
|
|
842
|
+
if (ticks < 0) return ticks * 60 / (this._entries[0].bpm * this._ppqn);
|
|
361
843
|
const entryIndex = this._entryIndexAt(ticks);
|
|
362
844
|
const entry = this._entries[entryIndex];
|
|
363
845
|
const ticksIntoSegment = ticks - entry.tick;
|
|
@@ -398,10 +880,9 @@ var TempoMap = class _TempoMap {
|
|
|
398
880
|
* Closed-form via exponential: bpmAtTick = bpm0 * exp(seconds * deltaBpm * ppqn / (60 * T))
|
|
399
881
|
* then ticks = (bpmAtTick - bpm0) * T / deltaBpm
|
|
400
882
|
*
|
|
401
|
-
* Note: exp(log(x)) has ~1 ULP floating-point error, so round-trips
|
|
402
|
-
*
|
|
403
|
-
* BPM ranges (10–300 BPM)
|
|
404
|
-
* 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).
|
|
405
886
|
*/
|
|
406
887
|
_secondsToTicksLinear(seconds, bpm0, bpm1, totalSegmentTicks) {
|
|
407
888
|
if (totalSegmentTicks === 0 || seconds === 0) return 0;
|
|
@@ -413,43 +894,71 @@ var TempoMap = class _TempoMap {
|
|
|
413
894
|
return (bpmAtTick - bpm0) / deltaBpm * totalSegmentTicks;
|
|
414
895
|
}
|
|
415
896
|
/**
|
|
416
|
-
*
|
|
417
|
-
*
|
|
418
|
-
*
|
|
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).
|
|
419
915
|
*/
|
|
420
916
|
_ticksToSecondsCurve(ticks, bpm0, bpm1, totalSegmentTicks, slope) {
|
|
421
917
|
if (totalSegmentTicks === 0 || ticks === 0) return 0;
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
}
|
|
432
|
-
|
|
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;
|
|
433
930
|
}
|
|
434
931
|
/**
|
|
435
|
-
*
|
|
436
|
-
*
|
|
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.
|
|
437
943
|
*/
|
|
438
944
|
_secondsToTicksCurve(seconds, bpm0, bpm1, totalSegmentTicks, slope) {
|
|
439
945
|
if (totalSegmentTicks === 0 || seconds === 0) return 0;
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
} else {
|
|
449
|
-
hi = mid;
|
|
450
|
-
}
|
|
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;
|
|
451
954
|
}
|
|
452
|
-
|
|
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 };
|
|
453
962
|
}
|
|
454
963
|
_entryIndexAt(tick) {
|
|
455
964
|
let lo = 0;
|
|
@@ -464,32 +973,6 @@ var TempoMap = class _TempoMap {
|
|
|
464
973
|
}
|
|
465
974
|
return lo;
|
|
466
975
|
}
|
|
467
|
-
_recomputeCache(fromIndex) {
|
|
468
|
-
for (let i = Math.max(1, fromIndex); i < this._entries.length; i++) {
|
|
469
|
-
const prev = this._entries[i - 1];
|
|
470
|
-
const tickDelta = this._entries[i].tick - prev.tick;
|
|
471
|
-
const entry = this._entries[i];
|
|
472
|
-
let segmentSeconds;
|
|
473
|
-
if (entry.interpolation === "linear") {
|
|
474
|
-
segmentSeconds = this._ticksToSecondsLinear(tickDelta, prev.bpm, entry.bpm, tickDelta);
|
|
475
|
-
} else if (typeof entry.interpolation === "object") {
|
|
476
|
-
segmentSeconds = this._ticksToSecondsCurve(
|
|
477
|
-
tickDelta,
|
|
478
|
-
prev.bpm,
|
|
479
|
-
entry.bpm,
|
|
480
|
-
tickDelta,
|
|
481
|
-
entry.interpolation.slope
|
|
482
|
-
);
|
|
483
|
-
} else {
|
|
484
|
-
const secondsPerTick = 60 / (prev.bpm * this._ppqn);
|
|
485
|
-
segmentSeconds = tickDelta * secondsPerTick;
|
|
486
|
-
}
|
|
487
|
-
this._entries[i] = {
|
|
488
|
-
...entry,
|
|
489
|
-
secondsAtTick: prev.secondsAtTick + segmentSeconds
|
|
490
|
-
};
|
|
491
|
-
}
|
|
492
|
-
}
|
|
493
976
|
};
|
|
494
977
|
|
|
495
978
|
// src/timeline/meter-map.ts
|
|
@@ -545,6 +1028,7 @@ var MeterMap = class {
|
|
|
545
1028
|
const idx = this._entries.findIndex((e) => e.tick === atTick);
|
|
546
1029
|
if (idx > 0) {
|
|
547
1030
|
this._entries.splice(idx, 1);
|
|
1031
|
+
this._resnapDownstreamEntries(idx - 1);
|
|
548
1032
|
this._recomputeCache(idx);
|
|
549
1033
|
} else if (idx === -1) {
|
|
550
1034
|
console.warn("[waveform-playlist] MeterMap.removeMeter: no entry at tick " + atTick);
|
|
@@ -671,6 +1155,80 @@ var MeterMap = class {
|
|
|
671
1155
|
}
|
|
672
1156
|
};
|
|
673
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
|
+
|
|
674
1232
|
// src/audio/master-node.ts
|
|
675
1233
|
var MasterNode = class {
|
|
676
1234
|
constructor(audioContext) {
|
|
@@ -802,6 +1360,10 @@ var ClipPlayer = class {
|
|
|
802
1360
|
this._tempoMap = tempoMap;
|
|
803
1361
|
this._toAudioTime = toAudioTime;
|
|
804
1362
|
}
|
|
1363
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1364
|
+
setTempoMap(tempoMap) {
|
|
1365
|
+
this._tempoMap = tempoMap;
|
|
1366
|
+
}
|
|
805
1367
|
setTracks(tracks, trackNodes) {
|
|
806
1368
|
this._tracks.clear();
|
|
807
1369
|
this._trackNodes = trackNodes;
|
|
@@ -1015,6 +1577,10 @@ var MetronomePlayer = class {
|
|
|
1015
1577
|
this._destination = destination;
|
|
1016
1578
|
this._toAudioTime = toAudioTime;
|
|
1017
1579
|
}
|
|
1580
|
+
/** Swap in a new (immutable) TempoMap (Transport does this on every tempo edit). */
|
|
1581
|
+
setTempoMap(tempoMap) {
|
|
1582
|
+
this._tempoMap = tempoMap;
|
|
1583
|
+
}
|
|
1018
1584
|
setEnabled(enabled) {
|
|
1019
1585
|
this._enabled = enabled;
|
|
1020
1586
|
if (!enabled) {
|
|
@@ -1170,12 +1736,9 @@ var CountInPlayer = class {
|
|
|
1170
1736
|
});
|
|
1171
1737
|
const transportTime = this._tempoMap.ticksToSeconds(event.tick);
|
|
1172
1738
|
source.start(this._toAudioTime(transportTime));
|
|
1173
|
-
}
|
|
1174
|
-
|
|
1175
|
-
"[waveform-playlist] CountInPlayer.consume: failed to schedule beat " + event.beat + "/" + event.totalBeats + ": " + String(err)
|
|
1176
|
-
);
|
|
1739
|
+
} finally {
|
|
1740
|
+
this._onBeat?.(event.beat, event.totalBeats);
|
|
1177
1741
|
}
|
|
1178
|
-
this._onBeat?.(event.beat, event.totalBeats);
|
|
1179
1742
|
}
|
|
1180
1743
|
onPositionJump(_newTick) {
|
|
1181
1744
|
}
|
|
@@ -1241,6 +1804,11 @@ var _Transport = class _Transport {
|
|
|
1241
1804
|
this._soloedTrackIds = /* @__PURE__ */ new Set();
|
|
1242
1805
|
this._mutedTrackIds = /* @__PURE__ */ new Set();
|
|
1243
1806
|
this._playing = false;
|
|
1807
|
+
this._disposed = false;
|
|
1808
|
+
/** `Clock.rebaseCount` as of the last resync; a higher count means sources
|
|
1809
|
+
* armed in the old time base are still scheduled. */
|
|
1810
|
+
this._rebasesHandled = 0;
|
|
1811
|
+
this._warnedDiscontinuity = false;
|
|
1244
1812
|
this._loopEnabled = false;
|
|
1245
1813
|
this._loopStartTick = 0;
|
|
1246
1814
|
this._loopStartSeconds = 0;
|
|
@@ -1259,17 +1827,32 @@ var _Transport = class _Transport {
|
|
|
1259
1827
|
this._accentBuffer = null;
|
|
1260
1828
|
this._normalBuffer = null;
|
|
1261
1829
|
this._schedulerLookahead = 0.2;
|
|
1830
|
+
this._errorLog = new ListenerErrorLog("[waveform-playlist] Transport: ");
|
|
1262
1831
|
this._ppqn = 960;
|
|
1263
1832
|
this._audioContext = audioContext;
|
|
1833
|
+
if (!(Number.isFinite(audioContext.sampleRate) && audioContext.sampleRate > 0)) {
|
|
1834
|
+
throw new Error(
|
|
1835
|
+
"[waveform-playlist] Transport: the AudioContext must report a positive finite sampleRate, got " + audioContext.sampleRate
|
|
1836
|
+
);
|
|
1837
|
+
}
|
|
1264
1838
|
const sampleRate = options.sampleRate ?? audioContext.sampleRate;
|
|
1265
1839
|
const ppqn = options.ppqn ?? 960;
|
|
1266
1840
|
const tempo = options.tempo ?? 120;
|
|
1267
1841
|
const numerator = options.numerator ?? 4;
|
|
1268
1842
|
const denominator = options.denominator ?? 4;
|
|
1269
1843
|
const lookahead = options.schedulerLookahead ?? 0.2;
|
|
1844
|
+
const timerIntervalMs = options.timerIntervalMs ?? DEFAULT_TIMER_INTERVAL_MS;
|
|
1270
1845
|
this._ppqn = ppqn;
|
|
1271
1846
|
this._schedulerLookahead = lookahead;
|
|
1272
|
-
_Transport._validateOptions(
|
|
1847
|
+
_Transport._validateOptions(
|
|
1848
|
+
sampleRate,
|
|
1849
|
+
ppqn,
|
|
1850
|
+
tempo,
|
|
1851
|
+
numerator,
|
|
1852
|
+
denominator,
|
|
1853
|
+
lookahead,
|
|
1854
|
+
timerIntervalMs
|
|
1855
|
+
);
|
|
1273
1856
|
this._clock = new Clock(audioContext);
|
|
1274
1857
|
this._sampleTimeline = new SampleTimeline(sampleRate);
|
|
1275
1858
|
this._meterMap = new MeterMap(ppqn, numerator, denominator);
|
|
@@ -1279,13 +1862,33 @@ var _Transport = class _Transport {
|
|
|
1279
1862
|
onLoop: (loopStartSeconds, loopEndSeconds, currentTimeSeconds) => {
|
|
1280
1863
|
const timeToBoundary = loopEndSeconds - currentTimeSeconds;
|
|
1281
1864
|
this._clock.seekTo(loopStartSeconds - timeToBoundary);
|
|
1282
|
-
}
|
|
1865
|
+
},
|
|
1866
|
+
onError: (error) => this._emitError(error)
|
|
1283
1867
|
});
|
|
1284
1868
|
this._sampleTimeline.setTempoMap(this._tempoMap);
|
|
1285
1869
|
this._initAudioGraph(audioContext);
|
|
1286
1870
|
this._initCountIn(audioContext, options);
|
|
1287
|
-
this._timer = new Timer(
|
|
1871
|
+
this._timer = new Timer(
|
|
1872
|
+
() => {
|
|
1873
|
+
try {
|
|
1874
|
+
this._tick();
|
|
1875
|
+
} catch (err) {
|
|
1876
|
+
this._onTickFailure(err);
|
|
1877
|
+
}
|
|
1878
|
+
},
|
|
1879
|
+
{ intervalMs: timerIntervalMs }
|
|
1880
|
+
);
|
|
1881
|
+
}
|
|
1882
|
+
/** One scheduling tick. Anything thrown here is a transport-internal
|
|
1883
|
+
* fault (not a listener failure — those are caught by the scheduler); the
|
|
1884
|
+
* wrapper above stops the transport rather than retrying it 40×/s. */
|
|
1885
|
+
_tick() {
|
|
1886
|
+
{
|
|
1288
1887
|
const time = this._clock.getTime();
|
|
1888
|
+
if (this._clock.rebaseCount !== this._rebasesHandled) {
|
|
1889
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
1890
|
+
this._resyncAfterDiscontinuity(time);
|
|
1891
|
+
}
|
|
1289
1892
|
if (this._countingIn) {
|
|
1290
1893
|
this._countInScheduler?.advance(time);
|
|
1291
1894
|
if (time >= this._countInDuration) {
|
|
@@ -1295,10 +1898,65 @@ var _Transport = class _Transport {
|
|
|
1295
1898
|
}
|
|
1296
1899
|
if (this._endTime !== void 0 && time >= this._endTime) {
|
|
1297
1900
|
this.stop();
|
|
1901
|
+
this._emit("ended");
|
|
1298
1902
|
return;
|
|
1299
1903
|
}
|
|
1300
1904
|
this._scheduler.advance(time);
|
|
1301
|
-
|
|
1905
|
+
this._emit("tick", { seconds: this.getCurrentTime() });
|
|
1906
|
+
}
|
|
1907
|
+
}
|
|
1908
|
+
/** The clock absorbed a backward context re-base since the last resync:
|
|
1909
|
+
* sources armed through the old anchor's toAudioTime() hold ABSOLUTE
|
|
1910
|
+
* context times and would now fire late by the shift. Outside a count-in,
|
|
1911
|
+
* re-create them from the held position (the seek-while-playing path minus
|
|
1912
|
+
* the move), clamped to loopStart like getCurrentTime() — right after a
|
|
1913
|
+
* wrap the clock sits behind loopStart and a resync from there would play
|
|
1914
|
+
* pre-loop material. During a count-in the clicks already armed are
|
|
1915
|
+
* dropped rather than regenerated (CountInPlayer counts beats, so a
|
|
1916
|
+
* regenerate would double-fire); the count-in→play transition is
|
|
1917
|
+
* clock-driven and still lands on the held clock. */
|
|
1918
|
+
_resyncAfterDiscontinuity(time) {
|
|
1919
|
+
const shiftSeconds = this._clock.frameToSeconds(this._clock.lastRebaseFrames);
|
|
1920
|
+
let seconds;
|
|
1921
|
+
if (this._countingIn) {
|
|
1922
|
+
this._countInPlayer.silence();
|
|
1923
|
+
seconds = this._countInStartPosition;
|
|
1924
|
+
} else {
|
|
1925
|
+
seconds = this._loopEnabled && time < this._loopStartSeconds ? this._loopStartSeconds : time;
|
|
1926
|
+
this._silenceAll();
|
|
1927
|
+
this._scheduler.reset(seconds);
|
|
1928
|
+
this._clipPlayer.onPositionJump(this._tempoMap.secondsToTicks(seconds));
|
|
1929
|
+
}
|
|
1930
|
+
const listeners = this._listeners.get("discontinuity");
|
|
1931
|
+
if (listeners && listeners.size > 0) {
|
|
1932
|
+
this._emit("discontinuity", { seconds, shiftSeconds });
|
|
1933
|
+
} else if (!this._warnedDiscontinuity) {
|
|
1934
|
+
this._warnedDiscontinuity = true;
|
|
1935
|
+
console.warn(
|
|
1936
|
+
"[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.'
|
|
1937
|
+
);
|
|
1938
|
+
}
|
|
1939
|
+
}
|
|
1940
|
+
/** Sources are (re)created from the current anchor here: any re-base
|
|
1941
|
+
* absorbed before this point concerns audio that no longer exists. */
|
|
1942
|
+
_markRebasesHandled() {
|
|
1943
|
+
this._rebasesHandled = this._clock.rebaseCount;
|
|
1944
|
+
}
|
|
1945
|
+
/** A tick threw: warn once and stop, so the engine sees a `stop` and no
|
|
1946
|
+
* one is left looking at a "playing" transport that renders silence. */
|
|
1947
|
+
_onTickFailure(err) {
|
|
1948
|
+
console.warn(
|
|
1949
|
+
"[waveform-playlist] Transport: stopping \u2014 the scheduling tick threw: " + (err instanceof Error ? err.name + ": " + err.message + (err.stack ? "\n" + err.stack : "") : String(err))
|
|
1950
|
+
);
|
|
1951
|
+
try {
|
|
1952
|
+
this.stop();
|
|
1953
|
+
} catch (stopErr) {
|
|
1954
|
+
console.warn(
|
|
1955
|
+
"[waveform-playlist] Transport: stop() after a tick failure also threw: " + String(stopErr)
|
|
1956
|
+
);
|
|
1957
|
+
this._timer.stop();
|
|
1958
|
+
this._playing = false;
|
|
1959
|
+
}
|
|
1302
1960
|
}
|
|
1303
1961
|
get audioContext() {
|
|
1304
1962
|
return this._audioContext;
|
|
@@ -1306,8 +1964,16 @@ var _Transport = class _Transport {
|
|
|
1306
1964
|
get ppqn() {
|
|
1307
1965
|
return this._ppqn;
|
|
1308
1966
|
}
|
|
1967
|
+
/** The current tempo map. Immutable: every tempo edit swaps in a new map,
|
|
1968
|
+
* so a reference you hold keeps converting with the tempo it had. */
|
|
1969
|
+
get tempoMap() {
|
|
1970
|
+
return this._tempoMap;
|
|
1971
|
+
}
|
|
1309
1972
|
// --- Playback ---
|
|
1310
1973
|
play(startTime, endTime) {
|
|
1974
|
+
if (this._refuseIfDisposed("play")) return;
|
|
1975
|
+
if (startTime !== void 0) assertFiniteSeconds("play", "startTime", startTime);
|
|
1976
|
+
if (endTime !== void 0) assertFiniteSeconds("play", "endTime", endTime);
|
|
1311
1977
|
if (this._playing) return;
|
|
1312
1978
|
if (startTime !== void 0) {
|
|
1313
1979
|
this._clock.seekTo(startTime);
|
|
@@ -1319,6 +1985,10 @@ var _Transport = class _Transport {
|
|
|
1319
1985
|
const currentTime = this._clock.getTime();
|
|
1320
1986
|
this._scheduler.reset(currentTime);
|
|
1321
1987
|
this._endTime = endTime;
|
|
1988
|
+
this._scheduler.setPlayEnd(
|
|
1989
|
+
endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
|
|
1990
|
+
);
|
|
1991
|
+
this._markRebasesHandled();
|
|
1322
1992
|
this._clock.start();
|
|
1323
1993
|
const currentTick = this._tempoMap.secondsToTicks(currentTime);
|
|
1324
1994
|
this._clipPlayer.onPositionJump(currentTick);
|
|
@@ -1352,11 +2022,14 @@ var _Transport = class _Transport {
|
|
|
1352
2022
|
this._silenceAll();
|
|
1353
2023
|
this._playing = false;
|
|
1354
2024
|
this._endTime = void 0;
|
|
2025
|
+
this._scheduler.setPlayEnd(null);
|
|
1355
2026
|
if (wasPlaying) {
|
|
1356
2027
|
this._emit("stop");
|
|
1357
2028
|
}
|
|
1358
2029
|
}
|
|
1359
2030
|
seek(time) {
|
|
2031
|
+
if (this._refuseIfDisposed("seek")) return;
|
|
2032
|
+
assertFiniteSeconds("seek", "time", time);
|
|
1360
2033
|
const wasPlaying = this._playing;
|
|
1361
2034
|
const wasCountingIn = this._countingIn;
|
|
1362
2035
|
if (wasCountingIn) {
|
|
@@ -1368,8 +2041,10 @@ var _Transport = class _Transport {
|
|
|
1368
2041
|
}
|
|
1369
2042
|
this._silenceAll();
|
|
1370
2043
|
this._clock.seekTo(time);
|
|
2044
|
+
this._markRebasesHandled();
|
|
1371
2045
|
this._scheduler.reset(time);
|
|
1372
2046
|
this._endTime = void 0;
|
|
2047
|
+
this._scheduler.setPlayEnd(null);
|
|
1373
2048
|
if (wasPlaying && !wasCountingIn) {
|
|
1374
2049
|
this._clock.start();
|
|
1375
2050
|
const seekTick = this._tempoMap.secondsToTicks(time);
|
|
@@ -1388,6 +2063,32 @@ var _Transport = class _Transport {
|
|
|
1388
2063
|
}
|
|
1389
2064
|
return t;
|
|
1390
2065
|
}
|
|
2066
|
+
/** Current position in whole AudioContext frames (the clock's native unit
|
|
2067
|
+
* for elapsed time). Same loop-wrap clamp and count-in hold as
|
|
2068
|
+
* getCurrentTime(). CONTEXT-rate frames — `getCurrentSample()` is the
|
|
2069
|
+
* timeline-rate view. */
|
|
2070
|
+
getCurrentFrame() {
|
|
2071
|
+
if (this._countingIn) {
|
|
2072
|
+
return this._clock.secondsToFrame(this._countInStartPosition);
|
|
2073
|
+
}
|
|
2074
|
+
const frame = this._clock.getFrame();
|
|
2075
|
+
const loopStartFrame = this._clock.secondsToFrame(this._loopStartSeconds);
|
|
2076
|
+
if (this._loopEnabled && frame < loopStartFrame) {
|
|
2077
|
+
return loopStartFrame;
|
|
2078
|
+
}
|
|
2079
|
+
return frame;
|
|
2080
|
+
}
|
|
2081
|
+
/** Current position in SampleTimeline samples (the `sampleRate` option's
|
|
2082
|
+
* rate; equal to getCurrentFrame() only when that matches the context).
|
|
2083
|
+
* Rounded once, at the Sample boundary. */
|
|
2084
|
+
getCurrentSample() {
|
|
2085
|
+
return this._sampleTimeline.secondsToSamples(this.getCurrentTime());
|
|
2086
|
+
}
|
|
2087
|
+
/** How many backward AudioContext clock readings the transport has absorbed
|
|
2088
|
+
* (see the `discontinuity` event). Diagnostics. */
|
|
2089
|
+
get rebaseCount() {
|
|
2090
|
+
return this._clock.rebaseCount;
|
|
2091
|
+
}
|
|
1391
2092
|
isPlaying() {
|
|
1392
2093
|
return this._playing;
|
|
1393
2094
|
}
|
|
@@ -1502,14 +2203,12 @@ var _Transport = class _Transport {
|
|
|
1502
2203
|
this._masterNode.setVolume(volume);
|
|
1503
2204
|
}
|
|
1504
2205
|
// --- Loop ---
|
|
1505
|
-
/** Primary loop API — ticks as source of truth
|
|
2206
|
+
/** Primary loop API — ticks as source of truth. Throws when `enabled` and
|
|
2207
|
+
* the range is non-finite, empty or inverted; nothing is changed and no
|
|
2208
|
+
* `loop` event fires. (NativePlayoutAdapter translates the engine's
|
|
2209
|
+
* default empty region to a disabled loop before reaching here.) */
|
|
1506
2210
|
setLoop(enabled, startTick, endTick) {
|
|
1507
|
-
|
|
1508
|
-
console.warn(
|
|
1509
|
-
"[waveform-playlist] Transport.setLoop: startTick (" + startTick + ") must be less than endTick (" + endTick + ")"
|
|
1510
|
-
);
|
|
1511
|
-
return;
|
|
1512
|
-
}
|
|
2211
|
+
assertValidLoopRange("Transport.setLoop", enabled, startTick, endTick, "tick");
|
|
1513
2212
|
this._loopEnabled = enabled;
|
|
1514
2213
|
this._loopStartTick = startTick;
|
|
1515
2214
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1517,28 +2216,37 @@ var _Transport = class _Transport {
|
|
|
1517
2216
|
this._clipPlayer.setLoop(enabled, startTick, endTick);
|
|
1518
2217
|
this._emit("loop");
|
|
1519
2218
|
}
|
|
1520
|
-
/** Convenience — converts seconds to ticks
|
|
2219
|
+
/** Convenience — converts seconds to ticks. Same validation as setLoop,
|
|
2220
|
+
* applied in seconds so the error names the caller's unit. */
|
|
1521
2221
|
setLoopSeconds(enabled, startSec, endSec) {
|
|
2222
|
+
assertValidLoopRange("Transport.setLoopSeconds", enabled, startSec, endSec, "second");
|
|
1522
2223
|
const startTick = this._tempoMap.secondsToTicks(startSec);
|
|
1523
2224
|
const endTick = this._tempoMap.secondsToTicks(endSec);
|
|
2225
|
+
assertLoopRangeSpansATick(
|
|
2226
|
+
"Transport.setLoopSeconds",
|
|
2227
|
+
enabled,
|
|
2228
|
+
startSec,
|
|
2229
|
+
endSec,
|
|
2230
|
+
"second",
|
|
2231
|
+
startTick,
|
|
2232
|
+
endTick
|
|
2233
|
+
);
|
|
1524
2234
|
this.setLoop(enabled, startTick, endTick);
|
|
1525
2235
|
}
|
|
1526
|
-
/** Convenience — sets loop in samples */
|
|
2236
|
+
/** Convenience — sets loop in samples. Same validation as setLoop. */
|
|
1527
2237
|
setLoopSamples(enabled, startSample, endSample) {
|
|
1528
|
-
|
|
1529
|
-
console.warn(
|
|
1530
|
-
"[waveform-playlist] Transport.setLoopSamples: non-finite sample values (" + startSample + ", " + endSample + ")"
|
|
1531
|
-
);
|
|
1532
|
-
return;
|
|
1533
|
-
}
|
|
1534
|
-
if (enabled && startSample >= endSample) {
|
|
1535
|
-
console.warn(
|
|
1536
|
-
"[waveform-playlist] Transport.setLoopSamples: startSample (" + startSample + ") must be less than endSample (" + endSample + ")"
|
|
1537
|
-
);
|
|
1538
|
-
return;
|
|
1539
|
-
}
|
|
2238
|
+
assertValidLoopRange("Transport.setLoopSamples", enabled, startSample, endSample, "sample");
|
|
1540
2239
|
const startTick = this._sampleTimeline.samplesToTicks(startSample);
|
|
1541
2240
|
const endTick = this._sampleTimeline.samplesToTicks(endSample);
|
|
2241
|
+
assertLoopRangeSpansATick(
|
|
2242
|
+
"Transport.setLoopSamples",
|
|
2243
|
+
enabled,
|
|
2244
|
+
startSample,
|
|
2245
|
+
endSample,
|
|
2246
|
+
"sample",
|
|
2247
|
+
startTick,
|
|
2248
|
+
endTick
|
|
2249
|
+
);
|
|
1542
2250
|
this._loopEnabled = enabled;
|
|
1543
2251
|
this._loopStartTick = startTick;
|
|
1544
2252
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(startTick);
|
|
@@ -1557,7 +2265,7 @@ var _Transport = class _Transport {
|
|
|
1557
2265
|
);
|
|
1558
2266
|
return false;
|
|
1559
2267
|
}
|
|
1560
|
-
this._tempoMap.
|
|
2268
|
+
this._replaceTempoMap(this._tempoMap.withTempo(bpm, atTick, options));
|
|
1561
2269
|
if (this._loopEnabled) {
|
|
1562
2270
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1563
2271
|
}
|
|
@@ -1594,7 +2302,7 @@ var _Transport = class _Transport {
|
|
|
1594
2302
|
});
|
|
1595
2303
|
}
|
|
1596
2304
|
clearTempos() {
|
|
1597
|
-
this._tempoMap.
|
|
2305
|
+
this._replaceTempoMap(this._tempoMap.withoutTempos());
|
|
1598
2306
|
if (this._loopEnabled) {
|
|
1599
2307
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1600
2308
|
}
|
|
@@ -1605,7 +2313,7 @@ var _Transport = class _Transport {
|
|
|
1605
2313
|
* invalidation and event; the emitted bpm is the tempo now in force at
|
|
1606
2314
|
* the removed position. */
|
|
1607
2315
|
removeTempo(atTick) {
|
|
1608
|
-
this._tempoMap.
|
|
2316
|
+
this._replaceTempoMap(this._tempoMap.withoutTempo(atTick));
|
|
1609
2317
|
if (this._loopEnabled) {
|
|
1610
2318
|
this._loopStartSeconds = this._tempoMap.ticksToSeconds(this._loopStartTick);
|
|
1611
2319
|
}
|
|
@@ -1614,14 +2322,28 @@ var _Transport = class _Transport {
|
|
|
1614
2322
|
barToTick(bar) {
|
|
1615
2323
|
return this._meterMap.barToTick(bar);
|
|
1616
2324
|
}
|
|
2325
|
+
/** Snap a (possibly fractional) tick to the meter grid: `subdivision` is
|
|
2326
|
+
* `{ ticks }`, `{ note, dotted?, triplet? }`, 'bar' or 'beat'; `mode` is
|
|
2327
|
+
* 'nearest' (default) | 'next' | 'previous'; `strength` 0–1 scales the
|
|
2328
|
+
* move. Grid lines restart at each bar line, so odd meters stay aligned.
|
|
2329
|
+
* Pure function over the (live) MeterMap. */
|
|
2330
|
+
quantizeTick(tick, subdivision, options) {
|
|
2331
|
+
return quantizeTick(this._meterMap, tick, subdivision, options);
|
|
2332
|
+
}
|
|
1617
2333
|
tickToBar(tick) {
|
|
1618
2334
|
return this._meterMap.tickToBar(tick);
|
|
1619
2335
|
}
|
|
1620
|
-
/** Convert transport time (seconds) to tick position, using the tempo map. */
|
|
2336
|
+
/** Convert transport time (seconds) to an integer tick position, using the tempo map. */
|
|
1621
2337
|
timeToTick(seconds) {
|
|
1622
2338
|
return this._tempoMap.secondsToTicks(seconds);
|
|
1623
2339
|
}
|
|
1624
|
-
/** Convert
|
|
2340
|
+
/** Convert transport time (seconds) to a fractional tick position — for
|
|
2341
|
+
* sub-tick placement (e.g. a recorded note between ticks, before quantising). */
|
|
2342
|
+
timeToTickExact(seconds) {
|
|
2343
|
+
return this._tempoMap.secondsToTicksExact(seconds);
|
|
2344
|
+
}
|
|
2345
|
+
/** Convert a tick position (integer Tick or the fractional value
|
|
2346
|
+
* timeToTickExact returned) to transport time (seconds). */
|
|
1625
2347
|
tickToTime(tick) {
|
|
1626
2348
|
return this._tempoMap.ticksToSeconds(tick);
|
|
1627
2349
|
}
|
|
@@ -1713,18 +2435,20 @@ var _Transport = class _Transport {
|
|
|
1713
2435
|
// --- Dispose ---
|
|
1714
2436
|
dispose() {
|
|
1715
2437
|
this.stop();
|
|
2438
|
+
this._disposed = true;
|
|
1716
2439
|
for (const node of this._trackNodes.values()) {
|
|
1717
2440
|
node.dispose();
|
|
1718
2441
|
}
|
|
1719
2442
|
this._trackNodes.clear();
|
|
1720
2443
|
this._masterNode.dispose();
|
|
2444
|
+
this._timer.dispose();
|
|
1721
2445
|
this._listeners.clear();
|
|
1722
2446
|
}
|
|
1723
2447
|
// --- Private ---
|
|
1724
|
-
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead) {
|
|
1725
|
-
if (sampleRate
|
|
2448
|
+
static _validateOptions(sampleRate, ppqn, tempo, numerator, denominator, lookahead, timerIntervalMs) {
|
|
2449
|
+
if (!(Number.isFinite(sampleRate) && sampleRate > 0)) {
|
|
1726
2450
|
throw new Error(
|
|
1727
|
-
"[waveform-playlist] Transport: sampleRate must be positive, got " + sampleRate
|
|
2451
|
+
"[waveform-playlist] Transport: options.sampleRate must be a positive finite number, got " + sampleRate
|
|
1728
2452
|
);
|
|
1729
2453
|
}
|
|
1730
2454
|
if (ppqn <= 0 || !Number.isInteger(ppqn)) {
|
|
@@ -1750,6 +2474,11 @@ var _Transport = class _Transport {
|
|
|
1750
2474
|
"[waveform-playlist] Transport: schedulerLookahead must be positive, got " + lookahead
|
|
1751
2475
|
);
|
|
1752
2476
|
}
|
|
2477
|
+
if (!(timerIntervalMs > 0) || timerIntervalMs >= lookahead * 1e3) {
|
|
2478
|
+
throw new Error(
|
|
2479
|
+
"[waveform-playlist] Transport: timerIntervalMs must be positive and shorter than the lookahead (" + lookahead * 1e3 + " ms), got " + timerIntervalMs
|
|
2480
|
+
);
|
|
2481
|
+
}
|
|
1753
2482
|
}
|
|
1754
2483
|
_initAudioGraph(audioContext) {
|
|
1755
2484
|
this._masterNode = new MasterNode(audioContext);
|
|
@@ -1808,6 +2537,9 @@ var _Transport = class _Transport {
|
|
|
1808
2537
|
this._countingIn = true;
|
|
1809
2538
|
this._playing = true;
|
|
1810
2539
|
this._endTime = endTime;
|
|
2540
|
+
this._scheduler.setPlayEnd(
|
|
2541
|
+
endTime !== void 0 ? this._tempoMap.secondsToTicks(endTime) : null
|
|
2542
|
+
);
|
|
1811
2543
|
const playPositionTick = this._tempoMap.secondsToTicks(currentTime);
|
|
1812
2544
|
const meter = this._meterMap.getMeter(playPositionTick);
|
|
1813
2545
|
const totalBeats = meter.numerator * this._countInBars;
|
|
@@ -1818,7 +2550,8 @@ var _Transport = class _Transport {
|
|
|
1818
2550
|
const countInMeterMap = new MeterMap(this._ppqn, meter.numerator, meter.denominator);
|
|
1819
2551
|
this._countInDuration = countInTempoMap.ticksToSeconds(countInTicks);
|
|
1820
2552
|
this._countInScheduler = new Scheduler(countInTempoMap, {
|
|
1821
|
-
lookahead: this._schedulerLookahead
|
|
2553
|
+
lookahead: this._schedulerLookahead,
|
|
2554
|
+
onError: (error) => this._emitError(error)
|
|
1822
2555
|
});
|
|
1823
2556
|
this._countInPlayer.configure({
|
|
1824
2557
|
totalBeats,
|
|
@@ -1833,6 +2566,7 @@ var _Transport = class _Transport {
|
|
|
1833
2566
|
this._countInScheduler.addListener(this._countInPlayer);
|
|
1834
2567
|
this._countInScheduler.reset(0);
|
|
1835
2568
|
this._clock.seekTo(0);
|
|
2569
|
+
this._markRebasesHandled();
|
|
1836
2570
|
this._clock.start();
|
|
1837
2571
|
this._timer.start();
|
|
1838
2572
|
}
|
|
@@ -1855,6 +2589,28 @@ var _Transport = class _Transport {
|
|
|
1855
2589
|
this._countingIn = false;
|
|
1856
2590
|
this._timer.stop();
|
|
1857
2591
|
}
|
|
2592
|
+
/** Install a new immutable TempoMap everywhere one is held. The count-in
|
|
2593
|
+
* player is configured with its own dedicated map at each count-in start,
|
|
2594
|
+
* so it is not on this list. */
|
|
2595
|
+
_replaceTempoMap(next) {
|
|
2596
|
+
this._tempoMap = next;
|
|
2597
|
+
this._scheduler.setTempoMap(next);
|
|
2598
|
+
this._sampleTimeline.setTempoMap(next);
|
|
2599
|
+
this._clipPlayer.setTempoMap(next);
|
|
2600
|
+
this._metronomePlayer.setTempoMap(next);
|
|
2601
|
+
if (this._endTime !== void 0) {
|
|
2602
|
+
this._scheduler.setPlayEnd(next.secondsToTicks(this._endTime));
|
|
2603
|
+
}
|
|
2604
|
+
}
|
|
2605
|
+
/** A disposed transport has no timer or audio graph; a late play()/seek()
|
|
2606
|
+
* must not report "playing" with nothing ticking. */
|
|
2607
|
+
_refuseIfDisposed(what) {
|
|
2608
|
+
if (!this._disposed) return false;
|
|
2609
|
+
console.warn(
|
|
2610
|
+
"[waveform-playlist] Transport: " + what + "() on a disposed transport is ignored"
|
|
2611
|
+
);
|
|
2612
|
+
return true;
|
|
2613
|
+
}
|
|
1858
2614
|
_silenceAll() {
|
|
1859
2615
|
this._clipPlayer.silence();
|
|
1860
2616
|
this._metronomePlayer.silence();
|
|
@@ -1868,6 +2624,22 @@ var _Transport = class _Transport {
|
|
|
1868
2624
|
node.setMute(isExplicitlyMuted || isSoloMuted);
|
|
1869
2625
|
}
|
|
1870
2626
|
}
|
|
2627
|
+
/** Route a scheduler listener failure to `error` subscribers, or to
|
|
2628
|
+
* console.warn (once per listener and failure kind) when nobody is listening —
|
|
2629
|
+
* the failure must stay visible either way. Subscribers are called on a
|
|
2630
|
+
* microtask, after the scheduler window that produced the failure has
|
|
2631
|
+
* completed: a handler that reacts with stop()/setTracks()/off() must not
|
|
2632
|
+
* re-enter the listener iteration that is still running. */
|
|
2633
|
+
_emitError(error) {
|
|
2634
|
+
queueMicrotask(() => {
|
|
2635
|
+
const listeners = this._listeners.get("error");
|
|
2636
|
+
if (listeners && listeners.size > 0) {
|
|
2637
|
+
this._emit("error", error);
|
|
2638
|
+
} else {
|
|
2639
|
+
this._errorLog.warnOnce(error);
|
|
2640
|
+
}
|
|
2641
|
+
});
|
|
2642
|
+
}
|
|
1871
2643
|
_emit(event, ...args) {
|
|
1872
2644
|
const listeners = this._listeners.get(event);
|
|
1873
2645
|
if (listeners) {
|
|
@@ -1888,12 +2660,21 @@ var _Transport = class _Transport {
|
|
|
1888
2660
|
_Transport.MIN_COUNT_IN_BARS = 1;
|
|
1889
2661
|
_Transport.MAX_COUNT_IN_BARS = 8;
|
|
1890
2662
|
var Transport = _Transport;
|
|
2663
|
+
function assertFiniteSeconds(method, name, value) {
|
|
2664
|
+
if (!Number.isFinite(value)) {
|
|
2665
|
+
throw new Error(
|
|
2666
|
+
"[waveform-playlist] Transport." + method + ": " + name + " must be finite, got " + value
|
|
2667
|
+
);
|
|
2668
|
+
}
|
|
2669
|
+
}
|
|
1891
2670
|
|
|
1892
2671
|
// src/adapter.ts
|
|
1893
2672
|
var NativePlayoutAdapter = class {
|
|
1894
2673
|
constructor(audioContext, options) {
|
|
2674
|
+
this._onPlaybackEnded = null;
|
|
1895
2675
|
this._audioContext = audioContext;
|
|
1896
2676
|
this._transport = new Transport(audioContext, options);
|
|
2677
|
+
this._transport.on("ended", () => this._onPlaybackEnded?.());
|
|
1897
2678
|
}
|
|
1898
2679
|
get audioContext() {
|
|
1899
2680
|
return this._audioContext;
|
|
@@ -1914,21 +2695,26 @@ var NativePlayoutAdapter = class {
|
|
|
1914
2695
|
const warmupTarget = Math.max(MIN_WARMUP, this._audioContext.outputLatency ?? MIN_WARMUP);
|
|
1915
2696
|
if (this._audioContext.currentTime < warmupTarget) {
|
|
1916
2697
|
const MAX_WARMUP_MS = 2e3;
|
|
1917
|
-
|
|
2698
|
+
const WARMUP_POLL_MS = 16;
|
|
2699
|
+
await new Promise((resolve, reject) => {
|
|
1918
2700
|
const startMs = performance.now();
|
|
1919
2701
|
const check = () => {
|
|
1920
2702
|
if (this._audioContext.currentTime >= warmupTarget) {
|
|
1921
2703
|
resolve();
|
|
1922
|
-
} else if (this._audioContext.state === "closed"
|
|
2704
|
+
} else if (this._audioContext.state === "closed") {
|
|
2705
|
+
reject(
|
|
2706
|
+
new Error("[waveform-playlist] Cannot init: AudioContext closed during warmup")
|
|
2707
|
+
);
|
|
2708
|
+
} else if (performance.now() - startMs > MAX_WARMUP_MS) {
|
|
1923
2709
|
console.warn(
|
|
1924
2710
|
"[waveform-playlist] AudioContext warmup timed out (currentTime=" + this._audioContext.currentTime + ", target=" + warmupTarget + ", state=" + this._audioContext.state + "). Proceeding without warmup."
|
|
1925
2711
|
);
|
|
1926
2712
|
resolve();
|
|
1927
2713
|
} else {
|
|
1928
|
-
|
|
2714
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1929
2715
|
}
|
|
1930
2716
|
};
|
|
1931
|
-
|
|
2717
|
+
setTimeout(check, WARMUP_POLL_MS);
|
|
1932
2718
|
});
|
|
1933
2719
|
}
|
|
1934
2720
|
}
|
|
@@ -1954,6 +2740,13 @@ var NativePlayoutAdapter = class {
|
|
|
1954
2740
|
stop() {
|
|
1955
2741
|
this._transport.stop();
|
|
1956
2742
|
}
|
|
2743
|
+
/** Engine hook: adapter-initiated completion of a bounded play(start, end)
|
|
2744
|
+
* (the transport's `ended` event). Never fired for a consumer
|
|
2745
|
+
* stop()/pause()/seek()/dispose(), whether issued through this adapter or
|
|
2746
|
+
* directly on `adapter.transport`. */
|
|
2747
|
+
onPlaybackEnded(callback) {
|
|
2748
|
+
this._onPlaybackEnded = callback;
|
|
2749
|
+
}
|
|
1957
2750
|
seek(time) {
|
|
1958
2751
|
this._transport.seek(time);
|
|
1959
2752
|
}
|
|
@@ -1979,7 +2772,13 @@ var NativePlayoutAdapter = class {
|
|
|
1979
2772
|
this._transport.setTrackPan(trackId, pan);
|
|
1980
2773
|
}
|
|
1981
2774
|
setLoop(enabled, start, end) {
|
|
1982
|
-
|
|
2775
|
+
const finite = Number.isFinite(start) && Number.isFinite(end);
|
|
2776
|
+
const degenerate = enabled && finite && this._transport.timeToTick(start) >= this._transport.timeToTick(end);
|
|
2777
|
+
if (degenerate && !(start === 0 && end === 0)) {
|
|
2778
|
+
const why = start > end ? "inverted loop region (" + start + " > " + end + ")" : start === end ? "empty loop region (" + start + ")" : "loop region (" + start + ", " + end + ") is shorter than one tick";
|
|
2779
|
+
console.warn("[waveform-playlist] NativePlayoutAdapter.setLoop: " + why + " \u2014 loop disabled");
|
|
2780
|
+
}
|
|
2781
|
+
this._transport.setLoopSeconds(enabled && !degenerate, start, end);
|
|
1983
2782
|
}
|
|
1984
2783
|
setCountIn(enabled) {
|
|
1985
2784
|
this._transport.setCountIn(enabled);
|
|
@@ -2012,25 +2811,33 @@ var NativePlayoutAdapter = class {
|
|
|
2012
2811
|
secondsToTicks(seconds) {
|
|
2013
2812
|
return this._transport.timeToTick(seconds);
|
|
2014
2813
|
}
|
|
2814
|
+
/** Fractional tick position (engine `PlayoutAdapter.secondsToTicksExact`). */
|
|
2815
|
+
secondsToTicksExact(seconds) {
|
|
2816
|
+
return this._transport.timeToTickExact(seconds);
|
|
2817
|
+
}
|
|
2015
2818
|
get masterOutputNode() {
|
|
2016
2819
|
return this._transport.masterOutputNode;
|
|
2017
2820
|
}
|
|
2018
2821
|
dispose() {
|
|
2822
|
+
this._onPlaybackEnded = null;
|
|
2019
2823
|
this._transport.dispose();
|
|
2020
2824
|
}
|
|
2021
2825
|
};
|
|
2022
2826
|
export {
|
|
2023
2827
|
ClipPlayer,
|
|
2024
2828
|
Clock,
|
|
2829
|
+
DEFAULT_TIMER_INTERVAL_MS,
|
|
2025
2830
|
MasterNode,
|
|
2026
2831
|
MeterMap,
|
|
2027
2832
|
MetronomePlayer,
|
|
2028
2833
|
NativePlayoutAdapter,
|
|
2834
|
+
RENDER_QUANTUM_FRAMES,
|
|
2029
2835
|
SampleTimeline,
|
|
2030
2836
|
Scheduler,
|
|
2031
2837
|
TempoMap,
|
|
2032
2838
|
Timer,
|
|
2033
2839
|
TrackNode,
|
|
2034
|
-
Transport
|
|
2840
|
+
Transport,
|
|
2841
|
+
quantizeTick
|
|
2035
2842
|
};
|
|
2036
2843
|
//# sourceMappingURL=index.mjs.map
|