@waveform-playlist/engine 13.6.1 → 14.0.0-next.1
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 +246 -13
- package/dist/index.d.mts +297 -32
- package/dist/index.d.ts +297 -32
- package/dist/index.js +1681 -360
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +1678 -360
- package/dist/index.mjs.map +1 -1
- package/package.json +3 -3
package/dist/index.mjs
CHANGED
|
@@ -57,7 +57,8 @@ function splitClip(clip, splitSample) {
|
|
|
57
57
|
color: clip.color,
|
|
58
58
|
fadeIn: clip.fadeIn,
|
|
59
59
|
audioBuffer: clip.audioBuffer,
|
|
60
|
-
waveformData: clip.waveformData
|
|
60
|
+
waveformData: clip.waveformData,
|
|
61
|
+
src: clip.src
|
|
61
62
|
});
|
|
62
63
|
const right = createClip({
|
|
63
64
|
startSample: splitSample,
|
|
@@ -70,7 +71,8 @@ function splitClip(clip, splitSample) {
|
|
|
70
71
|
color: clip.color,
|
|
71
72
|
fadeOut: clip.fadeOut,
|
|
72
73
|
audioBuffer: clip.audioBuffer,
|
|
73
|
-
waveformData: clip.waveformData
|
|
74
|
+
waveformData: clip.waveformData,
|
|
75
|
+
src: clip.src
|
|
74
76
|
});
|
|
75
77
|
return { left, right };
|
|
76
78
|
}
|
|
@@ -146,15 +148,1525 @@ function clampSeekPosition(time, duration) {
|
|
|
146
148
|
return Math.max(0, Math.min(time, duration));
|
|
147
149
|
}
|
|
148
150
|
|
|
151
|
+
// src/arrangement/Arrangement.ts
|
|
152
|
+
import { isLoadingClip as isLoadingClip5 } from "@waveform-playlist/core";
|
|
153
|
+
|
|
154
|
+
// src/arrangement/attach.ts
|
|
155
|
+
var ARRANGEMENT_ATTACH_DECODE = /* @__PURE__ */ Symbol.for(
|
|
156
|
+
"@waveform-playlist/engine/arrangement/attach-decode/v1"
|
|
157
|
+
);
|
|
158
|
+
var ARRANGEMENT_ATTACH_TIME_BASE = /* @__PURE__ */ Symbol.for(
|
|
159
|
+
"@waveform-playlist/engine/arrangement/time-base/v1"
|
|
160
|
+
);
|
|
161
|
+
function attachPoints(value) {
|
|
162
|
+
return typeof value === "object" && value !== null ? value : {};
|
|
163
|
+
}
|
|
164
|
+
function isArrangement(value) {
|
|
165
|
+
return typeof attachPoints(value)[ARRANGEMENT_ATTACH_TIME_BASE] === "function";
|
|
166
|
+
}
|
|
167
|
+
function attachDecodeContext(arrangement, getContext) {
|
|
168
|
+
const attach = attachPoints(arrangement)[ARRANGEMENT_ATTACH_DECODE];
|
|
169
|
+
if (typeof attach !== "function") {
|
|
170
|
+
throw new Error(
|
|
171
|
+
"[waveform-playlist] attachDecodeContext: the first argument must be an arrangement made by createArrangement()."
|
|
172
|
+
);
|
|
173
|
+
}
|
|
174
|
+
return attach.call(arrangement, getContext);
|
|
175
|
+
}
|
|
176
|
+
function attachTimeBase(arrangement, timeBase) {
|
|
177
|
+
const attach = arrangement[ARRANGEMENT_ATTACH_TIME_BASE];
|
|
178
|
+
return attach.call(arrangement, timeBase);
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// src/arrangement/clipEdits.ts
|
|
182
|
+
import { isLoadingClip, sortClipsByTime } from "@waveform-playlist/core";
|
|
183
|
+
function loadedClips(track) {
|
|
184
|
+
return track.clips.filter((clip) => !isLoadingClip(clip));
|
|
185
|
+
}
|
|
186
|
+
function loadedClip(tracks, trackId, clipId) {
|
|
187
|
+
const clip = tracks.find((t) => t.id === trackId)?.clips.find((c) => c.id === clipId);
|
|
188
|
+
return clip && !isLoadingClip(clip) ? clip : void 0;
|
|
189
|
+
}
|
|
190
|
+
function findClip(tracks, trackId, clipId, operation) {
|
|
191
|
+
const track = tracks.find((t) => t.id === trackId);
|
|
192
|
+
if (!track) {
|
|
193
|
+
console.warn(`[waveform-playlist/engine] ${operation}: track "${trackId}" not found`);
|
|
194
|
+
return null;
|
|
195
|
+
}
|
|
196
|
+
const clipIndex = track.clips.findIndex((c) => c.id === clipId);
|
|
197
|
+
if (clipIndex === -1) {
|
|
198
|
+
console.warn(
|
|
199
|
+
`[waveform-playlist/engine] ${operation}: clip "${clipId}" not found in track "${trackId}"`
|
|
200
|
+
);
|
|
201
|
+
return null;
|
|
202
|
+
}
|
|
203
|
+
const clip = track.clips[clipIndex];
|
|
204
|
+
if (isLoadingClip(clip)) {
|
|
205
|
+
console.warn(
|
|
206
|
+
`[waveform-playlist/engine] ${operation}: clip "${clipId}" in track "${trackId}" is still loading and cannot be edited until its audio has loaded`
|
|
207
|
+
);
|
|
208
|
+
return null;
|
|
209
|
+
}
|
|
210
|
+
return { track, clip, clipIndex };
|
|
211
|
+
}
|
|
212
|
+
function withTrackClips(tracks, trackId, clips) {
|
|
213
|
+
return tracks.map((t) => t.id === trackId ? { ...t, clips } : t);
|
|
214
|
+
}
|
|
215
|
+
function clipBounds(tracks, trackId, clipId) {
|
|
216
|
+
const clip = loadedClip(tracks, trackId, clipId);
|
|
217
|
+
if (!clip) return null;
|
|
218
|
+
return {
|
|
219
|
+
offsetSamples: clip.offsetSamples,
|
|
220
|
+
durationSamples: clip.durationSamples,
|
|
221
|
+
startSample: clip.startSample,
|
|
222
|
+
sourceDurationSamples: clip.sourceDurationSamples
|
|
223
|
+
};
|
|
224
|
+
}
|
|
225
|
+
function constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time) {
|
|
226
|
+
const track = tracks.find((t) => t.id === trackId);
|
|
227
|
+
const clip = loadedClip(tracks, trackId, clipId);
|
|
228
|
+
if (!track || !clip) return 0;
|
|
229
|
+
const sortedClips = sortClipsByTime(loadedClips(track));
|
|
230
|
+
const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
|
|
231
|
+
return constrainBoundaryTrim(
|
|
232
|
+
clip,
|
|
233
|
+
deltaSamples,
|
|
234
|
+
boundary,
|
|
235
|
+
sortedClips,
|
|
236
|
+
sortedIndex,
|
|
237
|
+
time.minDuration(clip)
|
|
238
|
+
);
|
|
239
|
+
}
|
|
240
|
+
function moveClip(tracks, trackId, clipId, deltaSamples, time) {
|
|
241
|
+
const found = findClip(tracks, trackId, clipId, "moveClip");
|
|
242
|
+
if (!found) return null;
|
|
243
|
+
const { track, clip, clipIndex } = found;
|
|
244
|
+
const sortedClips = sortClipsByTime(loadedClips(track));
|
|
245
|
+
const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
|
|
246
|
+
const delta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
|
|
247
|
+
if (delta === 0) return null;
|
|
248
|
+
const startSample = Math.floor(clip.startSample + delta);
|
|
249
|
+
const moved = {
|
|
250
|
+
...clip,
|
|
251
|
+
startSample,
|
|
252
|
+
startTick: clip.startTick !== void 0 ? time.tickAt(startSample) : void 0
|
|
253
|
+
};
|
|
254
|
+
const clips = track.clips.map((c, i) => i === clipIndex ? moved : c);
|
|
255
|
+
return { tracks: withTrackClips(tracks, trackId, clips), delta };
|
|
256
|
+
}
|
|
257
|
+
function trimClip(tracks, trackId, clipId, boundary, deltaSamples, time) {
|
|
258
|
+
const found = findClip(tracks, trackId, clipId, "trimClip");
|
|
259
|
+
if (!found) return null;
|
|
260
|
+
const { track, clip, clipIndex } = found;
|
|
261
|
+
const constrained = constrainTrim(tracks, trackId, clipId, boundary, deltaSamples, time);
|
|
262
|
+
if (constrained === 0) return null;
|
|
263
|
+
let trimmed;
|
|
264
|
+
if (boundary === "left") {
|
|
265
|
+
const startSample = clip.startSample + constrained;
|
|
266
|
+
trimmed = {
|
|
267
|
+
...clip,
|
|
268
|
+
startSample,
|
|
269
|
+
startTick: clip.startTick !== void 0 ? time.tickAt(startSample) : void 0,
|
|
270
|
+
offsetSamples: clip.offsetSamples + constrained,
|
|
271
|
+
durationSamples: clip.durationSamples - constrained
|
|
272
|
+
};
|
|
273
|
+
} else {
|
|
274
|
+
trimmed = { ...clip, durationSamples: clip.durationSamples + constrained };
|
|
275
|
+
}
|
|
276
|
+
const clips = track.clips.map((c, i) => i === clipIndex ? trimmed : c);
|
|
277
|
+
return withTrackClips(tracks, trackId, clips);
|
|
278
|
+
}
|
|
279
|
+
function splitClip2(tracks, trackId, clipId, atSample, time) {
|
|
280
|
+
const found = findClip(tracks, trackId, clipId, "splitClip");
|
|
281
|
+
if (!found) return null;
|
|
282
|
+
const { track, clip, clipIndex } = found;
|
|
283
|
+
const minDuration = time.minDuration(clip);
|
|
284
|
+
if (!canSplitAt(clip, atSample, minDuration)) {
|
|
285
|
+
console.warn(
|
|
286
|
+
`[waveform-playlist/engine] splitClip: cannot split clip "${clipId}" at sample ${atSample} (clip range: ${clip.startSample}\u2013${clip.startSample + clip.durationSamples}, minDuration: ${minDuration})`
|
|
287
|
+
);
|
|
288
|
+
return null;
|
|
289
|
+
}
|
|
290
|
+
const { left, right } = splitClip(clip, atSample);
|
|
291
|
+
const withTick = (half) => clip.startTick !== void 0 ? { ...half, startTick: time.tickAt(half.startSample) } : half;
|
|
292
|
+
const clips = [...track.clips];
|
|
293
|
+
clips.splice(clipIndex, 1, withTick(left), withTick(right));
|
|
294
|
+
return withTrackClips(tracks, trackId, clips);
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// src/arrangement/devFreeze.ts
|
|
298
|
+
function isDevelopmentBuild() {
|
|
299
|
+
try {
|
|
300
|
+
return process.env.NODE_ENV !== "production";
|
|
301
|
+
} catch {
|
|
302
|
+
return false;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
function freezeTrackInDevelopment(track) {
|
|
306
|
+
if (!isDevelopmentBuild() || Object.isFrozen(track)) return track;
|
|
307
|
+
for (const clip of track.clips) Object.freeze(clip);
|
|
308
|
+
Object.freeze(track.clips);
|
|
309
|
+
return Object.freeze(track);
|
|
310
|
+
}
|
|
311
|
+
function freezeTracksInDevelopment(tracks) {
|
|
312
|
+
if (!isDevelopmentBuild()) return tracks;
|
|
313
|
+
for (const track of tracks) freezeTrackInDevelopment(track);
|
|
314
|
+
return Object.freeze(tracks);
|
|
315
|
+
}
|
|
316
|
+
|
|
317
|
+
// src/arrangement/loadSource.ts
|
|
318
|
+
var USERINFO = /^((?:[a-z][a-z0-9+.-]*:)?\/\/)[^/@]*@/i;
|
|
319
|
+
function urlLabel(url) {
|
|
320
|
+
const plain = url.split(/[?#]/)[0];
|
|
321
|
+
const cut = plain.replace(USERINFO, "$1");
|
|
322
|
+
if (cut !== plain) return cut;
|
|
323
|
+
try {
|
|
324
|
+
const parsed = new URL(url, "http://relative.invalid/");
|
|
325
|
+
if (parsed.username !== "" || parsed.password !== "") {
|
|
326
|
+
parsed.username = "";
|
|
327
|
+
parsed.password = "";
|
|
328
|
+
parsed.search = "";
|
|
329
|
+
parsed.hash = "";
|
|
330
|
+
return parsed.href;
|
|
331
|
+
}
|
|
332
|
+
} catch {
|
|
333
|
+
}
|
|
334
|
+
return plain;
|
|
335
|
+
}
|
|
336
|
+
function sourceLabel(src) {
|
|
337
|
+
if (typeof src === "string") {
|
|
338
|
+
if (/^data:/i.test(src)) return "data: URL";
|
|
339
|
+
if (/^blob:/i.test(src)) return "blob: URL";
|
|
340
|
+
return urlLabel(src);
|
|
341
|
+
}
|
|
342
|
+
if (typeof File !== "undefined" && src instanceof File) return src.name;
|
|
343
|
+
return "Blob";
|
|
344
|
+
}
|
|
345
|
+
async function readBytes(src, label2, signal) {
|
|
346
|
+
if (typeof src !== "string") {
|
|
347
|
+
const bytes2 = await src.arrayBuffer();
|
|
348
|
+
signal.throwIfAborted();
|
|
349
|
+
return bytes2;
|
|
350
|
+
}
|
|
351
|
+
let response;
|
|
352
|
+
try {
|
|
353
|
+
response = await fetch(src, { signal });
|
|
354
|
+
} catch (error) {
|
|
355
|
+
signal.throwIfAborted();
|
|
356
|
+
if (error instanceof TypeError) {
|
|
357
|
+
const failure = new Error("Failed to fetch " + label2);
|
|
358
|
+
throw label2 === src ? Object.assign(failure, { cause: error }) : failure;
|
|
359
|
+
}
|
|
360
|
+
throw error;
|
|
361
|
+
}
|
|
362
|
+
signal.throwIfAborted();
|
|
363
|
+
if (!response.ok) {
|
|
364
|
+
throw new Error(`Failed to fetch ${label2}: ${response.status} ${response.statusText}`);
|
|
365
|
+
}
|
|
366
|
+
const bytes = await response.arrayBuffer();
|
|
367
|
+
signal.throwIfAborted();
|
|
368
|
+
return bytes;
|
|
369
|
+
}
|
|
370
|
+
function isUsable(buffer) {
|
|
371
|
+
return !!buffer && buffer.length > 0 && typeof buffer.sampleRate === "number" && buffer.sampleRate > 0;
|
|
372
|
+
}
|
|
373
|
+
var defaultLoadSource = async (src, { signal, audioContext }) => {
|
|
374
|
+
signal.throwIfAborted();
|
|
375
|
+
const label2 = sourceLabel(src);
|
|
376
|
+
const bytes = await readBytes(src, label2, signal);
|
|
377
|
+
let buffer;
|
|
378
|
+
try {
|
|
379
|
+
buffer = await audioContext.decodeAudioData(bytes);
|
|
380
|
+
} catch (error) {
|
|
381
|
+
signal.throwIfAborted();
|
|
382
|
+
if (error instanceof Error) throw error;
|
|
383
|
+
throw new Error("Failed to decode audio: " + label2);
|
|
384
|
+
}
|
|
385
|
+
signal.throwIfAborted();
|
|
386
|
+
if (!isUsable(buffer)) throw new Error("Decoded audio is empty: " + label2);
|
|
387
|
+
return buffer;
|
|
388
|
+
};
|
|
389
|
+
|
|
390
|
+
// src/arrangement/sources.ts
|
|
391
|
+
import { createSourceLoader, createValueSource, isLoadingClip as isLoadingClip2 } from "@waveform-playlist/core";
|
|
392
|
+
|
|
393
|
+
// src/arrangement/resolveLoadingClip.ts
|
|
394
|
+
import { createClip as createClip2 } from "@waveform-playlist/core";
|
|
395
|
+
var warned = /* @__PURE__ */ new WeakMap();
|
|
396
|
+
function label(loading) {
|
|
397
|
+
return `clip "${loading.id}"`;
|
|
398
|
+
}
|
|
399
|
+
function warnOnce(loading, message) {
|
|
400
|
+
const seen = warned.get(loading) ?? /* @__PURE__ */ new Set();
|
|
401
|
+
warned.set(loading, seen);
|
|
402
|
+
if (seen.has(message)) return;
|
|
403
|
+
seen.add(message);
|
|
404
|
+
console.warn(`[waveform-playlist] ${label(loading)}: ${message}`);
|
|
405
|
+
}
|
|
406
|
+
var isNonNegative = (n) => Number.isFinite(n) && n >= 0;
|
|
407
|
+
function givenDuration(loading) {
|
|
408
|
+
return loading.duration ?? void 0;
|
|
409
|
+
}
|
|
410
|
+
function fieldProblem(loading) {
|
|
411
|
+
if (!isNonNegative(loading.start ?? 0)) {
|
|
412
|
+
return `start must be a finite number of seconds >= 0, got ${String(loading.start)}`;
|
|
413
|
+
}
|
|
414
|
+
if (!isNonNegative(loading.offset ?? 0)) {
|
|
415
|
+
return `offset must be a finite number of seconds >= 0, got ${String(loading.offset)}`;
|
|
416
|
+
}
|
|
417
|
+
const duration = givenDuration(loading);
|
|
418
|
+
if (duration !== void 0 && !(Number.isFinite(duration) && duration > 0)) {
|
|
419
|
+
return `duration must be a positive, finite number of seconds, got ${String(duration)}`;
|
|
420
|
+
}
|
|
421
|
+
return null;
|
|
422
|
+
}
|
|
423
|
+
function fitDuration(loading, offsetSamples, total, rate) {
|
|
424
|
+
if (!(offsetSamples < total)) return { problem: "offset is at or past the end of the audio" };
|
|
425
|
+
const rest = total - offsetSamples;
|
|
426
|
+
const duration = givenDuration(loading);
|
|
427
|
+
const wanted = duration === void 0 ? rest : Math.round(duration * rate);
|
|
428
|
+
if (!(wanted >= 1)) return { problem: "duration is shorter than one sample" };
|
|
429
|
+
if (wanted > rest + 1) {
|
|
430
|
+
warnOnce(loading, "duration runs past the end of the audio and was cut to it");
|
|
431
|
+
}
|
|
432
|
+
return { samples: Math.min(wanted, rest) };
|
|
433
|
+
}
|
|
434
|
+
function convert(loading, buffer) {
|
|
435
|
+
const rate = buffer?.sampleRate;
|
|
436
|
+
if (!(Number.isFinite(rate) && rate > 0 && buffer.length >= 1)) {
|
|
437
|
+
return "the decoded buffer is empty or has no usable sample rate";
|
|
438
|
+
}
|
|
439
|
+
const problem = fieldProblem(loading);
|
|
440
|
+
if (problem) return problem;
|
|
441
|
+
const offsetSamples = Math.round((loading.offset ?? 0) * rate);
|
|
442
|
+
const startSample = Math.round((loading.start ?? 0) * rate);
|
|
443
|
+
if (!Number.isSafeInteger(offsetSamples) || !Number.isSafeInteger(startSample)) {
|
|
444
|
+
return "start or offset is too large";
|
|
445
|
+
}
|
|
446
|
+
const fitted = fitDuration(loading, offsetSamples, buffer.length, rate);
|
|
447
|
+
if ("problem" in fitted) return fitted.problem;
|
|
448
|
+
return {
|
|
449
|
+
...createClip2({
|
|
450
|
+
audioBuffer: buffer,
|
|
451
|
+
startSample,
|
|
452
|
+
offsetSamples,
|
|
453
|
+
durationSamples: fitted.samples,
|
|
454
|
+
gain: loading.gain,
|
|
455
|
+
name: loading.name,
|
|
456
|
+
color: loading.color,
|
|
457
|
+
fadeIn: loading.fadeIn,
|
|
458
|
+
fadeOut: loading.fadeOut,
|
|
459
|
+
waveformData: loading.waveformData,
|
|
460
|
+
src: loading.src
|
|
461
|
+
}),
|
|
462
|
+
id: loading.id
|
|
463
|
+
};
|
|
464
|
+
}
|
|
465
|
+
function resolveLoadingClip(loading, buffer) {
|
|
466
|
+
let converted;
|
|
467
|
+
try {
|
|
468
|
+
converted = convert(loading, buffer);
|
|
469
|
+
} catch (error) {
|
|
470
|
+
converted = error instanceof Error ? error.message : String(error);
|
|
471
|
+
}
|
|
472
|
+
return typeof converted === "string" ? { unusable: `${label(loading)}: ${converted}` } : { clip: converted };
|
|
473
|
+
}
|
|
474
|
+
|
|
475
|
+
// src/arrangement/sources.ts
|
|
476
|
+
var EMPTY_VALUE = {
|
|
477
|
+
sources: /* @__PURE__ */ new Map(),
|
|
478
|
+
pendingCount: 0,
|
|
479
|
+
failedCount: 0,
|
|
480
|
+
isLoading: false
|
|
481
|
+
};
|
|
482
|
+
function deferred() {
|
|
483
|
+
let resolve = () => {
|
|
484
|
+
};
|
|
485
|
+
const promise = new Promise((done) => {
|
|
486
|
+
resolve = done;
|
|
487
|
+
});
|
|
488
|
+
return { promise, resolve };
|
|
489
|
+
}
|
|
490
|
+
function sameMembers(a, b) {
|
|
491
|
+
if (a.size !== b.size) return false;
|
|
492
|
+
for (const member of a) if (!b.has(member)) return false;
|
|
493
|
+
return true;
|
|
494
|
+
}
|
|
495
|
+
var ArrangementSources = class {
|
|
496
|
+
/**
|
|
497
|
+
* @param loadSource how a source becomes an AudioBuffer
|
|
498
|
+
* @param onSettled called when a source settled by itself (a load finished or failed)
|
|
499
|
+
*/
|
|
500
|
+
constructor(loadSource, onSettled) {
|
|
501
|
+
this._trackSources = /* @__PURE__ */ new WeakMap();
|
|
502
|
+
/** A loading clip and the buffer it was converted with: the same clip object every time. */
|
|
503
|
+
this._resolved = /* @__PURE__ */ new WeakMap();
|
|
504
|
+
this._wanted = /* @__PURE__ */ new Set();
|
|
505
|
+
/** Per source, the reason a clip of the CURRENT tracks could not be made (found by the last pass). */
|
|
506
|
+
this._unusable = /* @__PURE__ */ new Map();
|
|
507
|
+
this._getContext = null;
|
|
508
|
+
this._attached = deferred();
|
|
509
|
+
/** While `declare` talks to the loader, its notifications are not acted on. */
|
|
510
|
+
this._declaring = false;
|
|
511
|
+
const { source, publish } = createValueSource(EMPTY_VALUE);
|
|
512
|
+
this.value = source;
|
|
513
|
+
this._publish = publish;
|
|
514
|
+
this._loader = createSourceLoader({
|
|
515
|
+
load: async (src, signal) => {
|
|
516
|
+
let getContext = this._getContext;
|
|
517
|
+
while (!getContext) {
|
|
518
|
+
await this._attached.promise;
|
|
519
|
+
getContext = this._getContext;
|
|
520
|
+
}
|
|
521
|
+
signal.throwIfAborted();
|
|
522
|
+
const audioContext = await getContext();
|
|
523
|
+
signal.throwIfAborted();
|
|
524
|
+
return loadSource(src, { signal, audioContext });
|
|
525
|
+
}
|
|
526
|
+
});
|
|
527
|
+
this._loader.subscribe(() => {
|
|
528
|
+
if (!this._declaring) onSettled();
|
|
529
|
+
});
|
|
530
|
+
}
|
|
531
|
+
/**
|
|
532
|
+
* Give the loader a context to decode with; loads that were waiting start.
|
|
533
|
+
* Returns the function that takes it away again: loads in flight are
|
|
534
|
+
* aborted, loaded sources are kept, and the next attach starts the aborted
|
|
535
|
+
* ones again.
|
|
536
|
+
*/
|
|
537
|
+
attachDecodeContext(getContext) {
|
|
538
|
+
if (this._getContext) {
|
|
539
|
+
console.warn(
|
|
540
|
+
"[waveform-playlist] An arrangement decodes with one audio context at a time: a context was attached while another still is. Detach the first (dispose its engine) before attaching another."
|
|
541
|
+
);
|
|
542
|
+
}
|
|
543
|
+
this._getContext = getContext;
|
|
544
|
+
this._attached.resolve();
|
|
545
|
+
this._loader.setWanted(this._wanted);
|
|
546
|
+
return () => {
|
|
547
|
+
if (this._getContext !== getContext) return;
|
|
548
|
+
this._getContext = null;
|
|
549
|
+
this._attached = deferred();
|
|
550
|
+
this._loader.suspend();
|
|
551
|
+
};
|
|
552
|
+
}
|
|
553
|
+
/** Start a source whose load failed again. Does nothing for any other source. */
|
|
554
|
+
retry(src) {
|
|
555
|
+
this._loader.retry(src);
|
|
556
|
+
}
|
|
557
|
+
/**
|
|
558
|
+
* Tell the loader what `states` name. The loader is touched only when the
|
|
559
|
+
* set of wanted sources changed or a clip brought the audio of a source
|
|
560
|
+
* that is not loaded yet.
|
|
561
|
+
*/
|
|
562
|
+
declare(states) {
|
|
563
|
+
const wanted = /* @__PURE__ */ new Set();
|
|
564
|
+
const carried = /* @__PURE__ */ new Map();
|
|
565
|
+
for (const tracks of states) {
|
|
566
|
+
for (const track of tracks) {
|
|
567
|
+
const named = this._sourcesOf(track);
|
|
568
|
+
for (const clip of named.loading) wanted.add(clip.src);
|
|
569
|
+
for (const [src, buffer] of named.carried) if (!carried.has(src)) carried.set(src, buffer);
|
|
570
|
+
}
|
|
571
|
+
}
|
|
572
|
+
for (const src of carried.keys()) wanted.add(src);
|
|
573
|
+
this._declaring = true;
|
|
574
|
+
try {
|
|
575
|
+
for (const [src, buffer] of carried) this._loader.provide(src, buffer);
|
|
576
|
+
if (!sameMembers(wanted, this._wanted)) {
|
|
577
|
+
this._wanted = wanted;
|
|
578
|
+
this._loader.setWanted(wanted);
|
|
579
|
+
}
|
|
580
|
+
} finally {
|
|
581
|
+
this._declaring = false;
|
|
582
|
+
}
|
|
583
|
+
}
|
|
584
|
+
/**
|
|
585
|
+
* One pass over every state: two functions that replace, in a tracks
|
|
586
|
+
* array, every loading clip whose source is loaded with its loaded clip.
|
|
587
|
+
* They remember each track they have seen, so states that shared a track
|
|
588
|
+
* object go on sharing one, and they return the same array when nothing in
|
|
589
|
+
* it changed. Call `current` with the current tracks FIRST, then `stored`
|
|
590
|
+
* for each stored state, then `finishPass()`.
|
|
591
|
+
*
|
|
592
|
+
* A clip that cannot be made fails its source only while it is in the
|
|
593
|
+
* current tracks: one that only an undo or redo state holds is not
|
|
594
|
+
* something the app can see or mend.
|
|
595
|
+
*
|
|
596
|
+
* @param tickAt the tick of a sample position (undefined without an engine)
|
|
597
|
+
*/
|
|
598
|
+
beginPass(tickAt) {
|
|
599
|
+
const loaded = this._loader.getSnapshot();
|
|
600
|
+
const unusable = /* @__PURE__ */ new Map();
|
|
601
|
+
this._unusable = unusable;
|
|
602
|
+
const seen = /* @__PURE__ */ new Map();
|
|
603
|
+
let inCurrentTracks = false;
|
|
604
|
+
const switched = (clip) => {
|
|
605
|
+
const state = loaded.get(clip.src);
|
|
606
|
+
if (state?.status !== "loaded") return clip;
|
|
607
|
+
const result = this._resolve(clip, state.value, tickAt);
|
|
608
|
+
if ("clip" in result) return result.clip;
|
|
609
|
+
if (inCurrentTracks && !unusable.has(clip.src)) unusable.set(clip.src, result.unusable);
|
|
610
|
+
return clip;
|
|
611
|
+
};
|
|
612
|
+
const mapTrack = (track) => {
|
|
613
|
+
const known = seen.get(track);
|
|
614
|
+
if (known) return known;
|
|
615
|
+
let next = track;
|
|
616
|
+
if (this._sourcesOf(track).loading.length > 0) {
|
|
617
|
+
const clips = track.clips.map((clip) => isLoadingClip2(clip) ? switched(clip) : clip);
|
|
618
|
+
if (clips.some((clip, i) => clip !== track.clips[i])) next = { ...track, clips };
|
|
619
|
+
}
|
|
620
|
+
seen.set(track, next);
|
|
621
|
+
return next;
|
|
622
|
+
};
|
|
623
|
+
const apply = (tracks) => {
|
|
624
|
+
const next = tracks.map(mapTrack);
|
|
625
|
+
return next.some((track, i) => track !== tracks[i]) ? next : tracks;
|
|
626
|
+
};
|
|
627
|
+
return {
|
|
628
|
+
current: (tracks) => {
|
|
629
|
+
inCurrentTracks = true;
|
|
630
|
+
try {
|
|
631
|
+
return apply(tracks);
|
|
632
|
+
} finally {
|
|
633
|
+
inCurrentTracks = false;
|
|
634
|
+
}
|
|
635
|
+
},
|
|
636
|
+
stored: (tracks) => apply(tracks)
|
|
637
|
+
};
|
|
638
|
+
}
|
|
639
|
+
/** After a pass over every state: publish `value` if a status changed. */
|
|
640
|
+
finishPass() {
|
|
641
|
+
const next = this._currentValue();
|
|
642
|
+
const previous = this.value.getSnapshot();
|
|
643
|
+
if (!sameValue(previous, next)) this._publish(next);
|
|
644
|
+
}
|
|
645
|
+
_resolve(clip, buffer, tickAt) {
|
|
646
|
+
const memo = this._resolved.get(clip);
|
|
647
|
+
if (memo && memo.buffer === buffer) return memo.result;
|
|
648
|
+
let result = resolveLoadingClip(clip, buffer);
|
|
649
|
+
if ("clip" in result) {
|
|
650
|
+
result = { clip: { ...result.clip, startTick: tickAt(result.clip.startSample) } };
|
|
651
|
+
}
|
|
652
|
+
this._resolved.set(clip, { buffer, result });
|
|
653
|
+
return result;
|
|
654
|
+
}
|
|
655
|
+
_sourcesOf(track) {
|
|
656
|
+
const known = this._trackSources.get(track);
|
|
657
|
+
if (known) return known;
|
|
658
|
+
const loading = [];
|
|
659
|
+
const carried = [];
|
|
660
|
+
for (const clip of track.clips) {
|
|
661
|
+
if (isLoadingClip2(clip)) loading.push(clip);
|
|
662
|
+
else if (clip.src !== void 0 && clip.audioBuffer)
|
|
663
|
+
carried.push([clip.src, clip.audioBuffer]);
|
|
664
|
+
}
|
|
665
|
+
const named = { loading, carried };
|
|
666
|
+
this._trackSources.set(track, named);
|
|
667
|
+
return named;
|
|
668
|
+
}
|
|
669
|
+
_failure(src, message) {
|
|
670
|
+
const shown = this.value.getSnapshot().sources.get(src)?.error;
|
|
671
|
+
return shown && shown.message === message ? shown : new Error(message);
|
|
672
|
+
}
|
|
673
|
+
_currentValue() {
|
|
674
|
+
const sources = /* @__PURE__ */ new Map();
|
|
675
|
+
const loaderStates = this._loader.getSnapshot();
|
|
676
|
+
for (const src of this._wanted) {
|
|
677
|
+
const state = loaderStates.get(src) ?? { status: "pending" };
|
|
678
|
+
const reason = this._unusable.get(src);
|
|
679
|
+
if (state.status === "failed") {
|
|
680
|
+
sources.set(src, { status: "failed", error: state.error });
|
|
681
|
+
} else if (state.status === "loaded" && reason !== void 0) {
|
|
682
|
+
sources.set(src, { status: "failed", error: this._failure(src, reason) });
|
|
683
|
+
} else {
|
|
684
|
+
sources.set(src, { status: state.status });
|
|
685
|
+
}
|
|
686
|
+
}
|
|
687
|
+
let pendingCount = 0;
|
|
688
|
+
let failedCount = 0;
|
|
689
|
+
for (const state of sources.values()) {
|
|
690
|
+
if (state.status === "pending") pendingCount++;
|
|
691
|
+
else if (state.status === "failed") failedCount++;
|
|
692
|
+
}
|
|
693
|
+
return { sources, pendingCount, failedCount, isLoading: pendingCount > 0 };
|
|
694
|
+
}
|
|
695
|
+
};
|
|
696
|
+
function sameValue(a, b) {
|
|
697
|
+
if (a.sources.size !== b.sources.size) return false;
|
|
698
|
+
for (const [src, state] of b.sources) {
|
|
699
|
+
const before = a.sources.get(src);
|
|
700
|
+
if (!before || before.status !== state.status || before.error !== state.error) return false;
|
|
701
|
+
}
|
|
702
|
+
return true;
|
|
703
|
+
}
|
|
704
|
+
|
|
705
|
+
// src/arrangement/history.ts
|
|
706
|
+
var EMPTY_HISTORY = { undo: [], redo: [] };
|
|
707
|
+
function pushStep(history, tracks, limit) {
|
|
708
|
+
const undo = [...history.undo, tracks];
|
|
709
|
+
return { undo: undo.length > limit ? undo.slice(undo.length - limit) : undo, redo: [] };
|
|
710
|
+
}
|
|
711
|
+
function undoStep(history, current) {
|
|
712
|
+
if (history.undo.length === 0) return null;
|
|
713
|
+
const tracks = history.undo[history.undo.length - 1];
|
|
714
|
+
return {
|
|
715
|
+
history: { undo: history.undo.slice(0, -1), redo: [...history.redo, current] },
|
|
716
|
+
tracks
|
|
717
|
+
};
|
|
718
|
+
}
|
|
719
|
+
function redoStep(history, current) {
|
|
720
|
+
if (history.redo.length === 0) return null;
|
|
721
|
+
const tracks = history.redo[history.redo.length - 1];
|
|
722
|
+
return {
|
|
723
|
+
history: { undo: [...history.undo, current], redo: history.redo.slice(0, -1) },
|
|
724
|
+
tracks
|
|
725
|
+
};
|
|
726
|
+
}
|
|
727
|
+
function beginBase(tracks) {
|
|
728
|
+
return { tracks, changed: false };
|
|
729
|
+
}
|
|
730
|
+
function withoutTrack(tracks, trackId) {
|
|
731
|
+
return tracks.some((track) => track.id === trackId) ? tracks.filter((track) => track.id !== trackId) : tracks;
|
|
732
|
+
}
|
|
733
|
+
function sameTracks(a, b) {
|
|
734
|
+
return a === b || a.length === b.length && a.every((track, i) => track === b[i]);
|
|
735
|
+
}
|
|
736
|
+
function purgeTrack(history, current, trackId) {
|
|
737
|
+
const nextCurrent = withoutTrack(current, trackId);
|
|
738
|
+
const undo = [];
|
|
739
|
+
for (const step of history.undo) {
|
|
740
|
+
const stripped = withoutTrack(step, trackId);
|
|
741
|
+
if (undo.length === 0 || !sameTracks(undo[undo.length - 1], stripped)) undo.push(stripped);
|
|
742
|
+
}
|
|
743
|
+
while (undo.length > 0 && sameTracks(undo[undo.length - 1], nextCurrent)) undo.pop();
|
|
744
|
+
const redoFromCurrent = [];
|
|
745
|
+
for (let i = history.redo.length - 1; i >= 0; i--) {
|
|
746
|
+
const stripped = withoutTrack(history.redo[i], trackId);
|
|
747
|
+
const before = redoFromCurrent.length > 0 ? redoFromCurrent[redoFromCurrent.length - 1] : nextCurrent;
|
|
748
|
+
if (!sameTracks(before, stripped)) redoFromCurrent.push(stripped);
|
|
749
|
+
}
|
|
750
|
+
const redo = redoFromCurrent.reverse();
|
|
751
|
+
const unchanged = undo.length === history.undo.length && redo.length === history.redo.length && undo.every((step, i) => step === history.undo[i]) && redo.every((step, i) => step === history.redo[i]);
|
|
752
|
+
return { history: unchanged ? history : { undo, redo }, current: nextCurrent };
|
|
753
|
+
}
|
|
754
|
+
|
|
755
|
+
// src/arrangement/mixer.ts
|
|
756
|
+
var EMPTY_MIXER = /* @__PURE__ */ new Map();
|
|
757
|
+
var DEFAULT_VOLUME = 1;
|
|
758
|
+
var DEFAULT_PAN = 0;
|
|
759
|
+
function mixerValuesOf(track) {
|
|
760
|
+
return {
|
|
761
|
+
volume: track.volume ?? DEFAULT_VOLUME,
|
|
762
|
+
muted: track.muted ?? false,
|
|
763
|
+
soloed: track.soloed ?? false,
|
|
764
|
+
pan: track.pan ?? DEFAULT_PAN
|
|
765
|
+
};
|
|
766
|
+
}
|
|
767
|
+
function seedMixer(mixer, tracks) {
|
|
768
|
+
let next = null;
|
|
769
|
+
for (const track of tracks) {
|
|
770
|
+
if ((next ?? mixer).has(track.id)) continue;
|
|
771
|
+
if (!next) next = new Map(mixer);
|
|
772
|
+
next.set(track.id, mixerValuesOf(track));
|
|
773
|
+
}
|
|
774
|
+
return next ?? mixer;
|
|
775
|
+
}
|
|
776
|
+
function setMixerValues(mixer, trackId, patch) {
|
|
777
|
+
const entry = mixer.get(trackId);
|
|
778
|
+
if (!entry) return mixer;
|
|
779
|
+
return new Map(mixer).set(trackId, { ...entry, ...patch });
|
|
780
|
+
}
|
|
781
|
+
function carryMixerEntry(mixer, fromId, toId) {
|
|
782
|
+
const entry = mixer.get(fromId);
|
|
783
|
+
if (!entry || mixer.get(toId) === entry) return mixer;
|
|
784
|
+
return new Map(mixer).set(toId, entry);
|
|
785
|
+
}
|
|
786
|
+
function retainMixer(mixer, states) {
|
|
787
|
+
const held = /* @__PURE__ */ new Set();
|
|
788
|
+
for (const tracks of states) {
|
|
789
|
+
for (const track of tracks) held.add(track.id);
|
|
790
|
+
}
|
|
791
|
+
if ([...mixer.keys()].every((id) => held.has(id))) return mixer;
|
|
792
|
+
return new Map([...mixer].filter(([id]) => held.has(id)));
|
|
793
|
+
}
|
|
794
|
+
function withMixerValues(track, values) {
|
|
795
|
+
if (!values || track.volume === values.volume && track.muted === values.muted && track.soloed === values.soloed && track.pan === values.pan) {
|
|
796
|
+
return track;
|
|
797
|
+
}
|
|
798
|
+
return { ...track, ...values };
|
|
799
|
+
}
|
|
800
|
+
|
|
801
|
+
// src/arrangement/ticks.ts
|
|
802
|
+
import { isLoadingClip as isLoadingClip3 } from "@waveform-playlist/core";
|
|
803
|
+
function forLoadedClips(change) {
|
|
804
|
+
return (clip) => isLoadingClip3(clip) ? clip : change(clip);
|
|
805
|
+
}
|
|
806
|
+
function withClips(track, change) {
|
|
807
|
+
let changed = false;
|
|
808
|
+
const clips = track.clips.map((clip) => {
|
|
809
|
+
const next = change(clip);
|
|
810
|
+
if (next !== clip) changed = true;
|
|
811
|
+
return next;
|
|
812
|
+
});
|
|
813
|
+
return changed ? { ...track, clips } : track;
|
|
814
|
+
}
|
|
815
|
+
function clipMapper(change) {
|
|
816
|
+
const mapped = /* @__PURE__ */ new Map();
|
|
817
|
+
const mapTrack = (track) => {
|
|
818
|
+
const known = mapped.get(track);
|
|
819
|
+
if (known) return known;
|
|
820
|
+
const next = withClips(track, change);
|
|
821
|
+
mapped.set(track, next);
|
|
822
|
+
return next;
|
|
823
|
+
};
|
|
824
|
+
return (tracks) => {
|
|
825
|
+
const next = tracks.map(mapTrack);
|
|
826
|
+
return next.some((track, i) => track !== tracks[i]) ? next : tracks;
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
function tickPreparer(timeBase, fromPpqn) {
|
|
830
|
+
return clipMapper(
|
|
831
|
+
forLoadedClips((clip) => {
|
|
832
|
+
if (clip.startTick === void 0) {
|
|
833
|
+
const startTick2 = timeBase.secondsToTicks(clip.startSample / timeBase.sampleRate);
|
|
834
|
+
return { ...clip, startTick: startTick2 };
|
|
835
|
+
}
|
|
836
|
+
if (fromPpqn === null || fromPpqn === timeBase.ppqn) return clip;
|
|
837
|
+
const startTick = rescaleTick(clip.startTick, fromPpqn, timeBase.ppqn);
|
|
838
|
+
return startTick === clip.startTick ? clip : { ...clip, startTick };
|
|
839
|
+
})
|
|
840
|
+
);
|
|
841
|
+
}
|
|
842
|
+
function rescaleTick(tick, fromPpqn, toPpqn) {
|
|
843
|
+
return Math.round(tick * toPpqn / fromPpqn);
|
|
844
|
+
}
|
|
845
|
+
|
|
846
|
+
// src/arrangement/validate.ts
|
|
847
|
+
import { assertTrackKind, isLoadingClip as isLoadingClip4 } from "@waveform-playlist/core";
|
|
848
|
+
function assertClipsOfTrackKind(track) {
|
|
849
|
+
const clips = track.clips.map(
|
|
850
|
+
(clip) => isLoadingClip4(clip) ? { id: clip.id, name: clip.name } : clip
|
|
851
|
+
);
|
|
852
|
+
assertTrackKind({ ...track, clips });
|
|
853
|
+
}
|
|
854
|
+
function assertUniqueClipIds(track) {
|
|
855
|
+
const seen = /* @__PURE__ */ new Set();
|
|
856
|
+
for (const clip of track.clips) {
|
|
857
|
+
if (seen.has(clip.id)) {
|
|
858
|
+
throw new Error(
|
|
859
|
+
`[waveform-playlist] Track "${track.id}" has a duplicate clip id "${clip.id}". Clip ids must be unique within a track.`
|
|
860
|
+
);
|
|
861
|
+
}
|
|
862
|
+
seen.add(clip.id);
|
|
863
|
+
}
|
|
864
|
+
}
|
|
865
|
+
function assertUniqueTrackIds(tracks) {
|
|
866
|
+
const seen = /* @__PURE__ */ new Set();
|
|
867
|
+
for (const track of tracks) {
|
|
868
|
+
if (seen.has(track.id)) throw duplicateTrackId(track.id);
|
|
869
|
+
seen.add(track.id);
|
|
870
|
+
}
|
|
871
|
+
}
|
|
872
|
+
function duplicateTrackId(trackId) {
|
|
873
|
+
return new Error(
|
|
874
|
+
`[waveform-playlist] Duplicate track id "${trackId}". Track ids must be unique in an arrangement.`
|
|
875
|
+
);
|
|
876
|
+
}
|
|
877
|
+
|
|
878
|
+
// src/arrangement/Arrangement.ts
|
|
879
|
+
var DEFAULT_MIN_DURATION_SECONDS = 0.1;
|
|
880
|
+
var DEFAULT_UNDO_LIMIT = 100;
|
|
881
|
+
var ArrangementImpl = class {
|
|
882
|
+
constructor(options = {}) {
|
|
883
|
+
this._tracks = [];
|
|
884
|
+
this._tracksVersion = 0;
|
|
885
|
+
this._mixerVersion = 0;
|
|
886
|
+
this._mixer = EMPTY_MIXER;
|
|
887
|
+
this._history = EMPTY_HISTORY;
|
|
888
|
+
this._transaction = null;
|
|
889
|
+
this._subscribers = /* @__PURE__ */ new Set();
|
|
890
|
+
this._listeners = /* @__PURE__ */ new Set();
|
|
891
|
+
this._pending = [];
|
|
892
|
+
this._delivering = false;
|
|
893
|
+
/** How the clip edits convert time: through the attached engine, or not at all. */
|
|
894
|
+
this._clipTime = {
|
|
895
|
+
tickAt: (startSample) => this._tickAt(startSample),
|
|
896
|
+
minDuration: (clip) => this._minDuration(clip)
|
|
897
|
+
};
|
|
898
|
+
this.undoLimit = options.undoLimit ?? DEFAULT_UNDO_LIMIT;
|
|
899
|
+
this._timeBase = options.timeBase ?? null;
|
|
900
|
+
this._tickPpqn = options.timeBase?.ppqn ?? null;
|
|
901
|
+
this._sources = new ArrangementSources(
|
|
902
|
+
options.loadSource ?? defaultLoadSource,
|
|
903
|
+
() => this._onSourceSettled()
|
|
904
|
+
);
|
|
905
|
+
if (options.tracks) this.setTracks(options.tracks);
|
|
906
|
+
}
|
|
907
|
+
// ---------------------------------------------------------------------------
|
|
908
|
+
// Read
|
|
909
|
+
// ---------------------------------------------------------------------------
|
|
910
|
+
/** The tracks. The same array until something changes; never written to. */
|
|
911
|
+
getTracks() {
|
|
912
|
+
return this._tracks;
|
|
913
|
+
}
|
|
914
|
+
/**
|
|
915
|
+
* The current mixer values by track id. The same Map until a value
|
|
916
|
+
* changes, a track with a new id enters or entries are dropped; never
|
|
917
|
+
* written to. A track's own mixer fields in `getTracks()`
|
|
918
|
+
* are the values it entered with, not these.
|
|
919
|
+
*/
|
|
920
|
+
getMixer() {
|
|
921
|
+
return this._mixer;
|
|
922
|
+
}
|
|
923
|
+
/**
|
|
924
|
+
* Where each source the clips name is: pending, loaded or failed. The same
|
|
925
|
+
* object until a status changes.
|
|
926
|
+
*/
|
|
927
|
+
get sources() {
|
|
928
|
+
return this._sources.value;
|
|
929
|
+
}
|
|
930
|
+
/** Start a source whose LOAD failed again. See `Arrangement.retry`. */
|
|
931
|
+
retry(src) {
|
|
932
|
+
this._sources.retry(src);
|
|
933
|
+
}
|
|
934
|
+
/** The attach point of `attachDecodeContext()` (./attach.ts): a context to decode with. */
|
|
935
|
+
[ARRANGEMENT_ATTACH_DECODE](getContext) {
|
|
936
|
+
return this._sources.attachDecodeContext(getContext);
|
|
937
|
+
}
|
|
938
|
+
/** The attach point an engine uses (./attach.ts): `attachEngine`. */
|
|
939
|
+
[ARRANGEMENT_ATTACH_TIME_BASE](timeBase) {
|
|
940
|
+
return this.attachEngine(timeBase);
|
|
941
|
+
}
|
|
942
|
+
/** Counts structural changes. */
|
|
943
|
+
get tracksVersion() {
|
|
944
|
+
return this._tracksVersion;
|
|
945
|
+
}
|
|
946
|
+
/** Counts mixer changes. */
|
|
947
|
+
get mixerVersion() {
|
|
948
|
+
return this._mixerVersion;
|
|
949
|
+
}
|
|
950
|
+
/** Be told after every change. See `Arrangement.subscribe`. */
|
|
951
|
+
subscribe(listener) {
|
|
952
|
+
const entry = () => listener();
|
|
953
|
+
this._subscribers.add(entry);
|
|
954
|
+
return () => {
|
|
955
|
+
this._subscribers.delete(entry);
|
|
956
|
+
};
|
|
957
|
+
}
|
|
958
|
+
/**
|
|
959
|
+
* Internal, for the engine: be told WHAT changed, before the subscribers
|
|
960
|
+
* are. A listener here that throws fails the change's caller (an adapter
|
|
961
|
+
* that fails must fail the call that caused it). A `'load'` has no caller
|
|
962
|
+
* (audio arrived by itself): the engine catches its adapter's error for
|
|
963
|
+
* that change and reports it.
|
|
964
|
+
*/
|
|
965
|
+
onChange(listener) {
|
|
966
|
+
this._listeners.add(listener);
|
|
967
|
+
return () => {
|
|
968
|
+
this._listeners.delete(listener);
|
|
969
|
+
};
|
|
970
|
+
}
|
|
971
|
+
/**
|
|
972
|
+
* Internal, for the engine: how to convert time, for as long as the engine
|
|
973
|
+
* lives. In every state the arrangement holds (the current tracks, the
|
|
974
|
+
* undo and redo states, an open transaction's base), ticks counted in
|
|
975
|
+
* another engine's ppqn are converted to this one's and clips that have no
|
|
976
|
+
* `startTick` yet are given one. Returns the function that detaches;
|
|
977
|
+
* afterwards clips are given no ticks until the next engine attaches.
|
|
978
|
+
*
|
|
979
|
+
* Ticks a clip came with before any engine attached are read in the first
|
|
980
|
+
* engine's ppqn. A different TEMPO is not converted: a tick is the musical
|
|
981
|
+
* position, and `startSample` follows it at the next tempo change.
|
|
982
|
+
*/
|
|
983
|
+
attachEngine(timeBase) {
|
|
984
|
+
if (this._timeBase) {
|
|
985
|
+
console.warn(
|
|
986
|
+
"[waveform-playlist] An arrangement plays through one engine at a time: a second engine was built on an arrangement whose first engine has not been disposed. Dispose the first engine before building another."
|
|
987
|
+
);
|
|
988
|
+
}
|
|
989
|
+
const prepare = tickPreparer(timeBase, this._tickPpqn);
|
|
990
|
+
const tracks = prepare(this._tracks);
|
|
991
|
+
const history = {
|
|
992
|
+
undo: this._history.undo.map(prepare),
|
|
993
|
+
redo: this._history.redo.map(prepare)
|
|
994
|
+
};
|
|
995
|
+
const transaction = this._transaction && {
|
|
996
|
+
...this._transaction,
|
|
997
|
+
tracks: prepare(this._transaction.tracks)
|
|
998
|
+
};
|
|
999
|
+
this._timeBase = timeBase;
|
|
1000
|
+
this._tickPpqn = timeBase.ppqn;
|
|
1001
|
+
this._history = history;
|
|
1002
|
+
this._transaction = transaction;
|
|
1003
|
+
if (tracks !== this._tracks) {
|
|
1004
|
+
this._tracks = tracks;
|
|
1005
|
+
this._tracksVersion++;
|
|
1006
|
+
this._emit({ type: "recompute" });
|
|
1007
|
+
}
|
|
1008
|
+
return () => {
|
|
1009
|
+
if (this._timeBase === timeBase) this._timeBase = null;
|
|
1010
|
+
};
|
|
1011
|
+
}
|
|
1012
|
+
// ---------------------------------------------------------------------------
|
|
1013
|
+
// Undo/Redo
|
|
1014
|
+
// ---------------------------------------------------------------------------
|
|
1015
|
+
get canUndo() {
|
|
1016
|
+
return this._history.undo.length > 0;
|
|
1017
|
+
}
|
|
1018
|
+
get canRedo() {
|
|
1019
|
+
return this._history.redo.length > 0;
|
|
1020
|
+
}
|
|
1021
|
+
undo() {
|
|
1022
|
+
this._abortOpenTransaction();
|
|
1023
|
+
const step = undoStep(this._history, this._tracks);
|
|
1024
|
+
if (!step) return;
|
|
1025
|
+
this._history = step.history;
|
|
1026
|
+
this._restoreTracks(step.tracks);
|
|
1027
|
+
}
|
|
1028
|
+
redo() {
|
|
1029
|
+
this._abortOpenTransaction();
|
|
1030
|
+
const step = redoStep(this._history, this._tracks);
|
|
1031
|
+
if (!step) return;
|
|
1032
|
+
this._history = step.history;
|
|
1033
|
+
this._restoreTracks(step.tracks);
|
|
1034
|
+
}
|
|
1035
|
+
clearHistory() {
|
|
1036
|
+
const hadHistory = this.canUndo || this.canRedo;
|
|
1037
|
+
this._history = EMPTY_HISTORY;
|
|
1038
|
+
this._mixer = retainMixer(this._mixer, this._heldStates());
|
|
1039
|
+
if (hadHistory) this._emit({ type: "history" });
|
|
1040
|
+
}
|
|
1041
|
+
beginTransaction() {
|
|
1042
|
+
if (this._transaction) {
|
|
1043
|
+
console.warn(
|
|
1044
|
+
"[waveform-playlist/engine] beginTransaction: already in a transaction, previous snapshot will be overwritten"
|
|
1045
|
+
);
|
|
1046
|
+
}
|
|
1047
|
+
const replaced = this._transaction !== null;
|
|
1048
|
+
this._transaction = beginBase(this._tracks);
|
|
1049
|
+
if (replaced) this._resyncSourcesQuietly();
|
|
1050
|
+
}
|
|
1051
|
+
commitTransaction() {
|
|
1052
|
+
const transaction = this._transaction;
|
|
1053
|
+
if (!transaction) {
|
|
1054
|
+
console.warn("[waveform-playlist/engine] commitTransaction: no active transaction to commit");
|
|
1055
|
+
return;
|
|
1056
|
+
}
|
|
1057
|
+
this._transaction = null;
|
|
1058
|
+
if (transaction.changed && !sameTracks(transaction.tracks, this._tracks)) {
|
|
1059
|
+
this._pushStep(transaction.tracks);
|
|
1060
|
+
this._emit({ type: "history" });
|
|
1061
|
+
}
|
|
1062
|
+
}
|
|
1063
|
+
abortTransaction() {
|
|
1064
|
+
const transaction = this._transaction;
|
|
1065
|
+
if (!transaction) {
|
|
1066
|
+
console.warn("[waveform-playlist/engine] abortTransaction: no active transaction to abort");
|
|
1067
|
+
return;
|
|
1068
|
+
}
|
|
1069
|
+
this._abortOpenTransaction();
|
|
1070
|
+
}
|
|
1071
|
+
// ---------------------------------------------------------------------------
|
|
1072
|
+
// Track Management
|
|
1073
|
+
// ---------------------------------------------------------------------------
|
|
1074
|
+
// A track holds audio clips or MIDI clips, never both (#756); track ids are
|
|
1075
|
+
// unique, and so are clip ids within a track. The three methods that take a
|
|
1076
|
+
// track check it before they change anything, so a throw leaves the tracks,
|
|
1077
|
+
// the undo history, the mixer and every subscriber untouched.
|
|
1078
|
+
setTracks(tracks) {
|
|
1079
|
+
tracks.forEach(assertClipsOfTrackKind);
|
|
1080
|
+
assertUniqueTrackIds(tracks);
|
|
1081
|
+
tracks.forEach(assertUniqueClipIds);
|
|
1082
|
+
this._transaction = null;
|
|
1083
|
+
this._history = EMPTY_HISTORY;
|
|
1084
|
+
const kept = retainMixer(this._mixer, [this._tracks]);
|
|
1085
|
+
this._tracks = tracks.map((track) => this._ingest(track));
|
|
1086
|
+
this._mixer = retainMixer(seedMixer(kept, this._tracks), [this._tracks]);
|
|
1087
|
+
this._tracksVersion++;
|
|
1088
|
+
this._emit({ type: "set" });
|
|
1089
|
+
}
|
|
1090
|
+
addTrack(track) {
|
|
1091
|
+
assertClipsOfTrackKind(track);
|
|
1092
|
+
assertUniqueClipIds(track);
|
|
1093
|
+
if (this._tracks.some((t) => t.id === track.id)) throw duplicateTrackId(track.id);
|
|
1094
|
+
this._pushUndoSnapshot();
|
|
1095
|
+
const enriched = this._ingest(track);
|
|
1096
|
+
this._tracks = [...this._tracks, enriched];
|
|
1097
|
+
this._mixer = seedMixer(this._mixer, [enriched]);
|
|
1098
|
+
this._tracksVersion++;
|
|
1099
|
+
this._emit({ type: "add", trackId: track.id });
|
|
1100
|
+
}
|
|
1101
|
+
/**
|
|
1102
|
+
* Remove a track: an undo step. With `undoable: false` there is no step,
|
|
1103
|
+
* and the track is also taken out of every undo and redo state, so that no
|
|
1104
|
+
* undo or redo brings it back (a dropped file that could not be decoded).
|
|
1105
|
+
*/
|
|
1106
|
+
removeTrack(trackId, options) {
|
|
1107
|
+
if (options?.undoable === false) {
|
|
1108
|
+
this._removeTrackEverywhere(trackId);
|
|
1109
|
+
return;
|
|
1110
|
+
}
|
|
1111
|
+
if (!this._tracks.some((t) => t.id === trackId)) return;
|
|
1112
|
+
this._pushUndoSnapshot();
|
|
1113
|
+
this._tracks = this._tracks.filter((t) => t.id !== trackId);
|
|
1114
|
+
this._tracksVersion++;
|
|
1115
|
+
this._emit({ type: "remove", trackId });
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Move a track to a new position in the track order. Purely organizational —
|
|
1119
|
+
* track order is not audible.
|
|
1120
|
+
*/
|
|
1121
|
+
reorderTrack(trackId, toIndex) {
|
|
1122
|
+
const fromIndex = this._tracks.findIndex((t) => t.id === trackId);
|
|
1123
|
+
if (fromIndex === -1) return;
|
|
1124
|
+
const clamped = Math.max(0, Math.min(toIndex, this._tracks.length - 1));
|
|
1125
|
+
if (clamped === fromIndex) return;
|
|
1126
|
+
this._pushUndoSnapshot();
|
|
1127
|
+
const track = this._tracks[fromIndex];
|
|
1128
|
+
const without = this._tracks.filter((t) => t.id !== trackId);
|
|
1129
|
+
this._tracks = [...without.slice(0, clamped), track, ...without.slice(clamped)];
|
|
1130
|
+
this._tracksVersion++;
|
|
1131
|
+
this._emit({ type: "reorder" });
|
|
1132
|
+
}
|
|
1133
|
+
/**
|
|
1134
|
+
* Replace a track, with a track or with a function of the current one. The
|
|
1135
|
+
* mixer fields of the new track are not read: the mix is in `getMixer()`.
|
|
1136
|
+
* An id no track has changes nothing (a track object is still checked and
|
|
1137
|
+
* may throw; a function is not called for it).
|
|
1138
|
+
*
|
|
1139
|
+
* The track is copied on its way in, and so is each clip, except a clip
|
|
1140
|
+
* object this track already holds (one taken from `getTracks()`): that
|
|
1141
|
+
* one is kept as it is, so states go on sharing it and a listener can see
|
|
1142
|
+
* that it did not change.
|
|
1143
|
+
*/
|
|
1144
|
+
updateTrack(trackId, next) {
|
|
1145
|
+
const current = this._tracks.find((t) => t.id === trackId);
|
|
1146
|
+
const byFunction = typeof next === "function";
|
|
1147
|
+
if (byFunction && !current) return;
|
|
1148
|
+
const track = byFunction ? next(current) : next;
|
|
1149
|
+
if (byFunction && track === current) return;
|
|
1150
|
+
assertClipsOfTrackKind(track);
|
|
1151
|
+
assertUniqueClipIds(track);
|
|
1152
|
+
if (track.id !== trackId && this._tracks.some((t) => t.id === track.id)) {
|
|
1153
|
+
throw duplicateTrackId(track.id);
|
|
1154
|
+
}
|
|
1155
|
+
if (!current) return;
|
|
1156
|
+
this._pushUndoSnapshot();
|
|
1157
|
+
const enriched = this._ingest(track, new Set(current.clips));
|
|
1158
|
+
this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
|
|
1159
|
+
this._mixer = seedMixer(carryMixerEntry(this._mixer, trackId, enriched.id), [enriched]);
|
|
1160
|
+
if (enriched.id !== trackId) this._mixer = retainMixer(this._mixer, this._heldStates());
|
|
1161
|
+
this._tracksVersion++;
|
|
1162
|
+
this._emit({ type: "update", trackId, previous: current });
|
|
1163
|
+
}
|
|
1164
|
+
// ---------------------------------------------------------------------------
|
|
1165
|
+
// Clips (the edits themselves are pure functions in ./clipEdits)
|
|
1166
|
+
// ---------------------------------------------------------------------------
|
|
1167
|
+
/** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
|
|
1168
|
+
getClipBounds(trackId, clipId) {
|
|
1169
|
+
return clipBounds(this._tracks, trackId, clipId);
|
|
1170
|
+
}
|
|
1171
|
+
/** Constrain a trim delta using the collision/bounds logic.
|
|
1172
|
+
* Uses the clip's current state and neighboring clips for constraints. */
|
|
1173
|
+
constrainTrimDelta(trackId, clipId, boundary, deltaSamples) {
|
|
1174
|
+
return constrainTrim(this._tracks, trackId, clipId, boundary, deltaSamples, this._clipTime);
|
|
1175
|
+
}
|
|
1176
|
+
/** Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op). */
|
|
1177
|
+
moveClip(trackId, clipId, deltaSamples) {
|
|
1178
|
+
const moved = moveClip(this._tracks, trackId, clipId, deltaSamples, this._clipTime);
|
|
1179
|
+
if (!moved) return 0;
|
|
1180
|
+
this._replaceTrack(trackId, moved.tracks);
|
|
1181
|
+
return moved.delta;
|
|
1182
|
+
}
|
|
1183
|
+
splitClip(trackId, clipId, atSample) {
|
|
1184
|
+
const next = splitClip2(this._tracks, trackId, clipId, atSample, this._clipTime);
|
|
1185
|
+
if (next) this._replaceTrack(trackId, next);
|
|
1186
|
+
}
|
|
1187
|
+
trimClip(trackId, clipId, boundary, deltaSamples) {
|
|
1188
|
+
const next = trimClip(this._tracks, trackId, clipId, boundary, deltaSamples, this._clipTime);
|
|
1189
|
+
if (next) this._replaceTrack(trackId, next);
|
|
1190
|
+
}
|
|
1191
|
+
// ---------------------------------------------------------------------------
|
|
1192
|
+
// Mixer values
|
|
1193
|
+
// ---------------------------------------------------------------------------
|
|
1194
|
+
//
|
|
1195
|
+
// Each replaces the Map and one entry, bumps mixerVersion and announces
|
|
1196
|
+
// the change. NOT structural changes: no track object is replaced,
|
|
1197
|
+
// tracksVersion stays (#501), and they are not undo steps. An id that is
|
|
1198
|
+
// not in the current tracks does nothing.
|
|
1199
|
+
setTrackVolume(trackId, volume) {
|
|
1200
|
+
this._setMixerValues(trackId, { volume });
|
|
1201
|
+
}
|
|
1202
|
+
setTrackMute(trackId, muted) {
|
|
1203
|
+
this._setMixerValues(trackId, { muted });
|
|
1204
|
+
}
|
|
1205
|
+
setTrackSolo(trackId, soloed) {
|
|
1206
|
+
this._setMixerValues(trackId, { soloed });
|
|
1207
|
+
}
|
|
1208
|
+
setTrackPan(trackId, pan) {
|
|
1209
|
+
this._setMixerValues(trackId, { pan });
|
|
1210
|
+
}
|
|
1211
|
+
// ---------------------------------------------------------------------------
|
|
1212
|
+
// Tempo
|
|
1213
|
+
// ---------------------------------------------------------------------------
|
|
1214
|
+
/** Re-derive `startSample` from `startTick` for every clip that has one (after a tempo change). */
|
|
1215
|
+
recomputeStartSamples() {
|
|
1216
|
+
if (!this._timeBase) return;
|
|
1217
|
+
const { ticksToSeconds, sampleRate } = this._timeBase;
|
|
1218
|
+
this._tracks = this._tracks.map(
|
|
1219
|
+
(track) => withClips(
|
|
1220
|
+
track,
|
|
1221
|
+
forLoadedClips((clip) => {
|
|
1222
|
+
if (clip.startTick === void 0) return clip;
|
|
1223
|
+
const startSample = Math.round(ticksToSeconds(clip.startTick) * sampleRate);
|
|
1224
|
+
return startSample === clip.startSample ? clip : { ...clip, startSample };
|
|
1225
|
+
})
|
|
1226
|
+
)
|
|
1227
|
+
);
|
|
1228
|
+
this._tracksVersion++;
|
|
1229
|
+
this._emit({ type: "recompute" });
|
|
1230
|
+
}
|
|
1231
|
+
// ---------------------------------------------------------------------------
|
|
1232
|
+
// Private helpers
|
|
1233
|
+
// ---------------------------------------------------------------------------
|
|
1234
|
+
/** The tracks after an edit of one track: an undo step, the new array, the announcement. */
|
|
1235
|
+
_replaceTrack(trackId, tracks) {
|
|
1236
|
+
const previous = this._tracks.find((t) => t.id === trackId);
|
|
1237
|
+
this._pushUndoSnapshot();
|
|
1238
|
+
this._tracks = tracks;
|
|
1239
|
+
this._tracksVersion++;
|
|
1240
|
+
this._emit({ type: "update", trackId, previous });
|
|
1241
|
+
}
|
|
1242
|
+
/**
|
|
1243
|
+
* The tick of a sample position. Without an engine there is no tempo to
|
|
1244
|
+
* convert with, so there is no tick: a clip that is placed, moved or cut
|
|
1245
|
+
* meanwhile has none, and is given one when the next engine attaches.
|
|
1246
|
+
*/
|
|
1247
|
+
_tickAt(startSample) {
|
|
1248
|
+
if (!this._timeBase) return void 0;
|
|
1249
|
+
return this._timeBase.secondsToTicks(startSample / this._timeBase.sampleRate);
|
|
1250
|
+
}
|
|
1251
|
+
/** The shortest a clip may be: a tenth of a second, at the engine's rate or else the clip's own. */
|
|
1252
|
+
_minDuration(clip) {
|
|
1253
|
+
const sampleRate = this._timeBase?.sampleRate ?? clip.sampleRate;
|
|
1254
|
+
return Math.floor(DEFAULT_MIN_DURATION_SECONDS * sampleRate);
|
|
1255
|
+
}
|
|
1256
|
+
/**
|
|
1257
|
+
* A copy of a track on its way in, with a `startTick` on every clip when
|
|
1258
|
+
* an engine is attached (and none added when there is no engine). The track and each clip are copied, so the
|
|
1259
|
+
* arrangement holds no object its caller can still write to; a clip in
|
|
1260
|
+
* `held` is one the arrangement already holds and is kept as it is.
|
|
1261
|
+
*/
|
|
1262
|
+
_ingest(track, held) {
|
|
1263
|
+
return {
|
|
1264
|
+
...track,
|
|
1265
|
+
clips: track.clips.map((clip) => {
|
|
1266
|
+
if (held?.has(clip)) return clip;
|
|
1267
|
+
if (isLoadingClip5(clip)) return { ...clip };
|
|
1268
|
+
return { ...clip, startTick: clip.startTick ?? this._tickAt(clip.startSample) };
|
|
1269
|
+
})
|
|
1270
|
+
};
|
|
1271
|
+
}
|
|
1272
|
+
_setMixerValues(trackId, values) {
|
|
1273
|
+
if (!this._tracks.some((t) => t.id === trackId)) return;
|
|
1274
|
+
const next = setMixerValues(this._mixer, trackId, values);
|
|
1275
|
+
if (next === this._mixer) return;
|
|
1276
|
+
this._mixer = next;
|
|
1277
|
+
this._mixerVersion++;
|
|
1278
|
+
this._emit({ type: "mixer", trackId, values });
|
|
1279
|
+
}
|
|
1280
|
+
/** Every tracks array the arrangement can still return to, and the current one. */
|
|
1281
|
+
_heldStates() {
|
|
1282
|
+
return [
|
|
1283
|
+
this._tracks,
|
|
1284
|
+
...this._history.undo,
|
|
1285
|
+
...this._history.redo,
|
|
1286
|
+
...this._transaction ? [this._transaction.tracks] : []
|
|
1287
|
+
];
|
|
1288
|
+
}
|
|
1289
|
+
/** `removeTrack` with `undoable: false`: out of the current tracks and out of every stored state. */
|
|
1290
|
+
_removeTrackEverywhere(trackId) {
|
|
1291
|
+
const wasThere = this._tracks.some((t) => t.id === trackId);
|
|
1292
|
+
const purged = purgeTrack(this._history, this._tracks, trackId);
|
|
1293
|
+
const historyChanged = purged.history !== this._history;
|
|
1294
|
+
this._history = purged.history;
|
|
1295
|
+
if (this._transaction) {
|
|
1296
|
+
this._transaction = {
|
|
1297
|
+
...this._transaction,
|
|
1298
|
+
tracks: withoutTrack(this._transaction.tracks, trackId)
|
|
1299
|
+
};
|
|
1300
|
+
}
|
|
1301
|
+
this._tracks = purged.current;
|
|
1302
|
+
this._mixer = retainMixer(this._mixer, this._heldStates());
|
|
1303
|
+
if (wasThere) {
|
|
1304
|
+
this._tracksVersion++;
|
|
1305
|
+
this._emit({ type: "remove", trackId });
|
|
1306
|
+
} else if (historyChanged) {
|
|
1307
|
+
this._emit({ type: "history" });
|
|
1308
|
+
} else {
|
|
1309
|
+
this._resyncSourcesQuietly();
|
|
1310
|
+
}
|
|
1311
|
+
}
|
|
1312
|
+
/** The state before a change: an undo step, or the mark that an open transaction changed. */
|
|
1313
|
+
_pushUndoSnapshot() {
|
|
1314
|
+
if (this._transaction) {
|
|
1315
|
+
if (!this._transaction.changed) {
|
|
1316
|
+
this._transaction = { ...this._transaction, changed: true };
|
|
1317
|
+
}
|
|
1318
|
+
return;
|
|
1319
|
+
}
|
|
1320
|
+
this._pushStep(this._tracks);
|
|
1321
|
+
}
|
|
1322
|
+
/** Add an undo step. The history may let go of states with it (the redo stack, a step past the limit). */
|
|
1323
|
+
_pushStep(tracks) {
|
|
1324
|
+
const letsGo = this._history.redo.length > 0 || this._history.undo.length >= this.undoLimit;
|
|
1325
|
+
this._history = pushStep(this._history, tracks, this.undoLimit);
|
|
1326
|
+
if (letsGo) this._mixer = retainMixer(this._mixer, this._heldStates());
|
|
1327
|
+
}
|
|
1328
|
+
_restoreTracks(snapshot) {
|
|
1329
|
+
const previous = this._tracks;
|
|
1330
|
+
this._tracks = snapshot;
|
|
1331
|
+
this._tracksVersion++;
|
|
1332
|
+
this._emit({ type: "restore", previous });
|
|
1333
|
+
}
|
|
1334
|
+
/** Ends an open transaction, restoring the tracks it began from if it changed them. */
|
|
1335
|
+
_abortOpenTransaction() {
|
|
1336
|
+
const transaction = this._transaction;
|
|
1337
|
+
if (!transaction) return;
|
|
1338
|
+
this._transaction = null;
|
|
1339
|
+
if (transaction.changed) {
|
|
1340
|
+
this._restoreTracks(transaction.tracks);
|
|
1341
|
+
}
|
|
1342
|
+
}
|
|
1343
|
+
/** Declare the sources every state names, and switch the clips whose audio is there. */
|
|
1344
|
+
_syncSources() {
|
|
1345
|
+
this._sources.declare(this._heldStates());
|
|
1346
|
+
return this._switchLoaded();
|
|
1347
|
+
}
|
|
1348
|
+
/** The stored states changed with nothing to announce: the sources they name may have. */
|
|
1349
|
+
_resyncSourcesQuietly() {
|
|
1350
|
+
this._syncSources();
|
|
1351
|
+
this._sources.finishPass();
|
|
1352
|
+
}
|
|
1353
|
+
/**
|
|
1354
|
+
* Replace every loading clip whose source is loaded with its loaded clip,
|
|
1355
|
+
* in the current tracks and in every state the arrangement can return to.
|
|
1356
|
+
* The same loading-clip object becomes the same loaded clip everywhere, and
|
|
1357
|
+
* states go on sharing the tracks they shared. Not an undo step. Returns
|
|
1358
|
+
* the current tracks from before, or null when they did not change.
|
|
1359
|
+
*/
|
|
1360
|
+
_switchLoaded() {
|
|
1361
|
+
const pass = this._sources.beginPass((startSample) => this._tickAt(startSample));
|
|
1362
|
+
const previous = this._tracks;
|
|
1363
|
+
this._tracks = pass.current(previous);
|
|
1364
|
+
this._history = {
|
|
1365
|
+
undo: this._history.undo.map(pass.stored),
|
|
1366
|
+
redo: this._history.redo.map(pass.stored)
|
|
1367
|
+
};
|
|
1368
|
+
if (this._transaction) {
|
|
1369
|
+
this._transaction = { ...this._transaction, tracks: pass.stored(this._transaction.tracks) };
|
|
1370
|
+
}
|
|
1371
|
+
return this._tracks === previous ? null : previous;
|
|
1372
|
+
}
|
|
1373
|
+
/** A load finished or failed by itself (not inside one of this arrangement's methods). */
|
|
1374
|
+
_onSourceSettled() {
|
|
1375
|
+
const previous = this._switchLoaded();
|
|
1376
|
+
if (previous) {
|
|
1377
|
+
this._tracksVersion++;
|
|
1378
|
+
this._emit({ type: "load", previous });
|
|
1379
|
+
} else {
|
|
1380
|
+
this._sources.finishPass();
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
/**
|
|
1384
|
+
* Announce a change. Called after the state has changed. When a listener
|
|
1385
|
+
* makes a change of its own, that change waits here until the one being
|
|
1386
|
+
* delivered has reached every listener, so all of them see the changes in
|
|
1387
|
+
* the order they were made.
|
|
1388
|
+
*
|
|
1389
|
+
* A listener that throws does not stop the delivery; the first error is
|
|
1390
|
+
* thrown to the caller once everyone has been told (the engine's listener
|
|
1391
|
+
* throws when its adapter does, and the caller of the engine method has
|
|
1392
|
+
* always received that error).
|
|
1393
|
+
*/
|
|
1394
|
+
_emit(change) {
|
|
1395
|
+
const switched = change.type === "mixer" ? null : this._syncSources();
|
|
1396
|
+
freezeTracksInDevelopment(this._tracks);
|
|
1397
|
+
if (change.type === "remove" || change.type === "restore") {
|
|
1398
|
+
this._mixer = retainMixer(this._mixer, this._heldStates());
|
|
1399
|
+
}
|
|
1400
|
+
const at = {
|
|
1401
|
+
tracksVersion: this._tracksVersion,
|
|
1402
|
+
mixerVersion: this._mixerVersion
|
|
1403
|
+
};
|
|
1404
|
+
if (switched && (change.type === "add" || change.type === "update")) at.switched = switched;
|
|
1405
|
+
this._pending.push({ change, at });
|
|
1406
|
+
if (this._delivering) return;
|
|
1407
|
+
this._delivering = true;
|
|
1408
|
+
let failed = false;
|
|
1409
|
+
let firstError;
|
|
1410
|
+
try {
|
|
1411
|
+
for (let next = this._pending.shift(); next; next = this._pending.shift()) {
|
|
1412
|
+
for (const listener of [...this._listeners]) {
|
|
1413
|
+
try {
|
|
1414
|
+
listener(next.change, next.at);
|
|
1415
|
+
} catch (error) {
|
|
1416
|
+
if (!failed) {
|
|
1417
|
+
failed = true;
|
|
1418
|
+
firstError = error;
|
|
1419
|
+
}
|
|
1420
|
+
}
|
|
1421
|
+
}
|
|
1422
|
+
for (const subscriber of [...this._subscribers]) {
|
|
1423
|
+
try {
|
|
1424
|
+
subscriber();
|
|
1425
|
+
} catch (error) {
|
|
1426
|
+
console.warn("[waveform-playlist] Error in an arrangement subscriber:", error);
|
|
1427
|
+
}
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
} finally {
|
|
1431
|
+
this._delivering = false;
|
|
1432
|
+
}
|
|
1433
|
+
this._sources.finishPass();
|
|
1434
|
+
if (failed) throw firstError;
|
|
1435
|
+
}
|
|
1436
|
+
};
|
|
1437
|
+
|
|
1438
|
+
// src/arrangement/index.ts
|
|
1439
|
+
function createArrangement(options = {}) {
|
|
1440
|
+
return new ArrangementImpl(options);
|
|
1441
|
+
}
|
|
1442
|
+
|
|
1443
|
+
// src/adapterSync.ts
|
|
1444
|
+
import { isLoadingClip as isLoadingClip6 } from "@waveform-playlist/core";
|
|
1445
|
+
var AdapterSync = class {
|
|
1446
|
+
constructor(_arrangement, _adapter) {
|
|
1447
|
+
this._arrangement = _arrangement;
|
|
1448
|
+
this._adapter = _adapter;
|
|
1449
|
+
/**
|
|
1450
|
+
* The `tracksVersion` of each change made with `skipAdapter`. A change is
|
|
1451
|
+
* delivered later than it is made when it comes from inside a listener, so
|
|
1452
|
+
* the mark travels with the change's version, not with the call.
|
|
1453
|
+
*/
|
|
1454
|
+
this._skipAt = /* @__PURE__ */ new Set();
|
|
1455
|
+
/**
|
|
1456
|
+
* The arrangement's `tracksVersion` when the adapter was last sent every
|
|
1457
|
+
* track. A change that is delivered later than it was made (from inside a
|
|
1458
|
+
* listener) may already be in what the adapter was sent.
|
|
1459
|
+
*/
|
|
1460
|
+
this._syncedTracksVersion = -1;
|
|
1461
|
+
/**
|
|
1462
|
+
* An adapter call for a track change threw, so what the adapter holds is
|
|
1463
|
+
* not known: the next track change sends it every track.
|
|
1464
|
+
*/
|
|
1465
|
+
this._needsAllTracks = false;
|
|
1466
|
+
this._projection = null;
|
|
1467
|
+
this._withMixMemo = /* @__PURE__ */ new WeakMap();
|
|
1468
|
+
/** Per track object of the arrangement that holds a loading clip: the track without them. */
|
|
1469
|
+
this._loadedMemo = /* @__PURE__ */ new WeakMap();
|
|
1470
|
+
}
|
|
1471
|
+
/**
|
|
1472
|
+
* The arrangement's tracks, each without its loading clips and with the
|
|
1473
|
+
* current mixer values in its fields: what every adapter track call and
|
|
1474
|
+
* `getState().tracks` use. The same
|
|
1475
|
+
* array until the tracks or the mix change, and the same track object
|
|
1476
|
+
* while neither that track nor its mix changed.
|
|
1477
|
+
*/
|
|
1478
|
+
tracks() {
|
|
1479
|
+
const { tracksVersion, mixerVersion } = this._arrangement;
|
|
1480
|
+
const cached = this._projection;
|
|
1481
|
+
if (cached && cached.tracksVersion === tracksVersion && cached.mixerVersion === mixerVersion) {
|
|
1482
|
+
return cached.tracks;
|
|
1483
|
+
}
|
|
1484
|
+
const tracks = freezeTracksInDevelopment(
|
|
1485
|
+
this._arrangement.getTracks().map((track) => this._project(track))
|
|
1486
|
+
);
|
|
1487
|
+
this._projection = { tracksVersion, mixerVersion, tracks };
|
|
1488
|
+
return tracks;
|
|
1489
|
+
}
|
|
1490
|
+
/** When an engine attaches: send the tracks that are there. With none, the adapter is in step as it is. */
|
|
1491
|
+
sendInitialTracks() {
|
|
1492
|
+
if (this._arrangement.getTracks().length > 0) {
|
|
1493
|
+
this.sendAllTracks();
|
|
1494
|
+
} else {
|
|
1495
|
+
this._syncedTracksVersion = this._arrangement.tracksVersion;
|
|
1496
|
+
}
|
|
1497
|
+
}
|
|
1498
|
+
/** Send the adapter every track, and remember up to which change that covers. */
|
|
1499
|
+
sendAllTracks() {
|
|
1500
|
+
const version = this._arrangement.tracksVersion;
|
|
1501
|
+
this._adapter?.setTracks(this.tracks());
|
|
1502
|
+
this._syncedTracksVersion = version;
|
|
1503
|
+
}
|
|
1504
|
+
/** Send the arrangement's current track to the adapter. False when there is no such track. */
|
|
1505
|
+
sendTrack(trackId) {
|
|
1506
|
+
const track = this._arrangement.getTracks().find((t) => t.id === trackId);
|
|
1507
|
+
if (!track) return false;
|
|
1508
|
+
if (this._adapter?.updateTrack) {
|
|
1509
|
+
this._adapter.updateTrack(trackId, this._project(track));
|
|
1510
|
+
} else {
|
|
1511
|
+
this.sendAllTracks();
|
|
1512
|
+
}
|
|
1513
|
+
return true;
|
|
1514
|
+
}
|
|
1515
|
+
/** A mixer value changed: the adapter's setter for it. */
|
|
1516
|
+
sendMixerValues(trackId, values) {
|
|
1517
|
+
if (values.volume !== void 0) this._adapter?.setTrackVolume(trackId, values.volume);
|
|
1518
|
+
if (values.muted !== void 0) this._adapter?.setTrackMute(trackId, values.muted);
|
|
1519
|
+
if (values.soloed !== void 0) this._adapter?.setTrackSolo(trackId, values.soloed);
|
|
1520
|
+
if (values.pan !== void 0) this._adapter?.setTrackPan(trackId, values.pan);
|
|
1521
|
+
}
|
|
1522
|
+
/**
|
|
1523
|
+
* The adapter call for a change to the tracks.
|
|
1524
|
+
*
|
|
1525
|
+
* A change made from inside a listener is delivered later than it was
|
|
1526
|
+
* made. If the tracks have changed again by then, what this change did
|
|
1527
|
+
* cannot be told from the current tracks alone: the adapter is sent every
|
|
1528
|
+
* track, once, and the changes still waiting are then already sent.
|
|
1529
|
+
*/
|
|
1530
|
+
follow(change, at) {
|
|
1531
|
+
const skipped = change.type === "update" && this._skipAt.delete(at.tracksVersion);
|
|
1532
|
+
if (skipped || at.tracksVersion <= this._syncedTracksVersion) return;
|
|
1533
|
+
const needsAllTracks = this._needsAllTracks;
|
|
1534
|
+
this._needsAllTracks = true;
|
|
1535
|
+
if (needsAllTracks || at.tracksVersion < this._arrangement.tracksVersion) {
|
|
1536
|
+
this.sendAllTracks();
|
|
1537
|
+
} else {
|
|
1538
|
+
this._sendChange(change);
|
|
1539
|
+
if (at.switched && this._syncedTracksVersion < at.tracksVersion) this._restore(at.switched);
|
|
1540
|
+
}
|
|
1541
|
+
this._needsAllTracks = false;
|
|
1542
|
+
}
|
|
1543
|
+
/**
|
|
1544
|
+
* Before a change made with `skipAdapter`: mark the version that change
|
|
1545
|
+
* will have. Returns the mark, or null without `skipAdapter`.
|
|
1546
|
+
*/
|
|
1547
|
+
markSkip(skipAdapter) {
|
|
1548
|
+
if (!skipAdapter) return null;
|
|
1549
|
+
const mark = this._arrangement.tracksVersion + 1;
|
|
1550
|
+
this._skipAt.add(mark);
|
|
1551
|
+
return mark;
|
|
1552
|
+
}
|
|
1553
|
+
/** After the call: a call that changed nothing has no change to carry its mark. */
|
|
1554
|
+
unmarkIfUnchanged(mark) {
|
|
1555
|
+
if (mark !== null && this._arrangement.tracksVersion < mark) {
|
|
1556
|
+
this._skipAt.delete(mark);
|
|
1557
|
+
}
|
|
1558
|
+
}
|
|
1559
|
+
/** One change, made just now, as the adapter call that brings it in step. */
|
|
1560
|
+
_sendChange(change) {
|
|
1561
|
+
switch (change.type) {
|
|
1562
|
+
case "set":
|
|
1563
|
+
this.sendAllTracks();
|
|
1564
|
+
break;
|
|
1565
|
+
case "add":
|
|
1566
|
+
this._addTrack(change.trackId);
|
|
1567
|
+
break;
|
|
1568
|
+
case "remove":
|
|
1569
|
+
if (this._adapter?.removeTrack) {
|
|
1570
|
+
this._adapter.removeTrack(change.trackId);
|
|
1571
|
+
} else {
|
|
1572
|
+
this.sendAllTracks();
|
|
1573
|
+
}
|
|
1574
|
+
break;
|
|
1575
|
+
case "update":
|
|
1576
|
+
if (this._playsTheSame(change.previous, change.trackId)) break;
|
|
1577
|
+
if (!this.sendTrack(change.trackId)) this.sendAllTracks();
|
|
1578
|
+
break;
|
|
1579
|
+
case "restore":
|
|
1580
|
+
case "load":
|
|
1581
|
+
this._restore(change.previous);
|
|
1582
|
+
break;
|
|
1583
|
+
case "recompute":
|
|
1584
|
+
for (const track of this._arrangement.getTracks()) {
|
|
1585
|
+
this.sendTrack(track.id);
|
|
1586
|
+
}
|
|
1587
|
+
break;
|
|
1588
|
+
}
|
|
1589
|
+
}
|
|
1590
|
+
_addTrack(trackId) {
|
|
1591
|
+
const track = this._arrangement.getTracks().find((t) => t.id === trackId);
|
|
1592
|
+
if (track && this._adapter?.addTrack) {
|
|
1593
|
+
this._adapter.addTrack(this._project(track));
|
|
1594
|
+
} else {
|
|
1595
|
+
this.sendAllTracks();
|
|
1596
|
+
}
|
|
1597
|
+
}
|
|
1598
|
+
/**
|
|
1599
|
+
* After an undo, a redo or an abort. Use incremental adapter updates when
|
|
1600
|
+
* the same tracks are there before and after — avoids full playout rebuild
|
|
1601
|
+
* that interrupts playback. A track the restore did not touch is the same
|
|
1602
|
+
* object in both states and is skipped; so is a change of order only.
|
|
1603
|
+
*/
|
|
1604
|
+
_restore(previous) {
|
|
1605
|
+
const restored = this._arrangement.getTracks();
|
|
1606
|
+
const oldById = new Map(previous.map((t) => [t.id, t]));
|
|
1607
|
+
const sameSet = previous.length === restored.length && restored.every((t) => oldById.has(t.id));
|
|
1608
|
+
if (this._adapter && sameSet) {
|
|
1609
|
+
for (const track of restored) {
|
|
1610
|
+
const old = oldById.get(track.id);
|
|
1611
|
+
if (!this._playsTheSame(old, track.id)) this.sendTrack(track.id);
|
|
1612
|
+
}
|
|
1613
|
+
} else {
|
|
1614
|
+
this.sendAllTracks();
|
|
1615
|
+
}
|
|
1616
|
+
}
|
|
1617
|
+
/**
|
|
1618
|
+
* True when the arrangement's current track of that id is, for an adapter,
|
|
1619
|
+
* what `previous` was: the same loaded clip objects in the same order and
|
|
1620
|
+
* the same fields. Only its loading clips differ, and an adapter is not
|
|
1621
|
+
* given those, so there is nothing to send.
|
|
1622
|
+
*/
|
|
1623
|
+
_playsTheSame(previous, trackId) {
|
|
1624
|
+
const current = this._arrangement.getTracks().find((t) => t.id === trackId);
|
|
1625
|
+
if (!current) return false;
|
|
1626
|
+
if (current === previous) return true;
|
|
1627
|
+
const before = this._loaded(previous);
|
|
1628
|
+
const now = this._loaded(current);
|
|
1629
|
+
if (before.clips.length !== now.clips.length) return false;
|
|
1630
|
+
if (before.clips.some((clip, i) => clip !== now.clips[i])) return false;
|
|
1631
|
+
const keys = /* @__PURE__ */ new Set([...Object.keys(before), ...Object.keys(now)]);
|
|
1632
|
+
keys.delete("clips");
|
|
1633
|
+
return [...keys].every((key) => Object.is(before[key], now[key]));
|
|
1634
|
+
}
|
|
1635
|
+
/** What an adapter and `getState()` are given for one of the arrangement's tracks. */
|
|
1636
|
+
_project(track) {
|
|
1637
|
+
return this._withMix(this._loaded(track));
|
|
1638
|
+
}
|
|
1639
|
+
/**
|
|
1640
|
+
* The track without the clips that are still loading: an adapter plays
|
|
1641
|
+
* loaded clips only. A track that holds none is the arrangement's own
|
|
1642
|
+
* object (memoized per track object otherwise).
|
|
1643
|
+
*/
|
|
1644
|
+
_loaded(track) {
|
|
1645
|
+
const known = this._loadedMemo.get(track);
|
|
1646
|
+
if (known) return known;
|
|
1647
|
+
const clips = track.clips.filter((clip) => !isLoadingClip6(clip));
|
|
1648
|
+
const loaded = clips.length === track.clips.length ? track : { ...track, clips };
|
|
1649
|
+
this._loadedMemo.set(track, loaded);
|
|
1650
|
+
return loaded;
|
|
1651
|
+
}
|
|
1652
|
+
/** One track with its current mixer values in its fields (memoized per track object). */
|
|
1653
|
+
_withMix(track) {
|
|
1654
|
+
const values = this._arrangement.getMixer().get(track.id);
|
|
1655
|
+
const memo = this._withMixMemo.get(track);
|
|
1656
|
+
if (memo && memo.values === values) return memo.merged;
|
|
1657
|
+
const merged = freezeTrackInDevelopment(withMixerValues(track, values));
|
|
1658
|
+
this._withMixMemo.set(track, { values, merged });
|
|
1659
|
+
return merged;
|
|
1660
|
+
}
|
|
1661
|
+
};
|
|
1662
|
+
|
|
149
1663
|
// src/PlaylistEngine.ts
|
|
150
|
-
import { sortClipsByTime } from "@waveform-playlist/core";
|
|
151
1664
|
var DEFAULT_SAMPLE_RATE = 48e3;
|
|
152
1665
|
var DEFAULT_SAMPLES_PER_PIXEL = 1024;
|
|
153
1666
|
var DEFAULT_ZOOM_LEVELS = [256, 512, 1024, 2048, 4096, 8192];
|
|
154
|
-
var DEFAULT_MIN_DURATION_SECONDS = 0.1;
|
|
155
1667
|
var PlaylistEngine = class {
|
|
156
1668
|
constructor(options = {}) {
|
|
157
|
-
this.
|
|
1669
|
+
this._detachDecodeContext = null;
|
|
158
1670
|
this._currentTime = 0;
|
|
159
1671
|
this._playStartPosition = 0;
|
|
160
1672
|
this._isPlaying = false;
|
|
@@ -165,20 +1677,12 @@ var PlaylistEngine = class {
|
|
|
165
1677
|
this._loopStart = 0;
|
|
166
1678
|
this._loopEnd = 0;
|
|
167
1679
|
this._isLoopEnabled = false;
|
|
168
|
-
this._tracksVersion = 0;
|
|
169
|
-
this._mixerVersion = 0;
|
|
170
1680
|
this._disposed = false;
|
|
171
1681
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-function-type
|
|
172
1682
|
this._listeners = /* @__PURE__ */ new Map();
|
|
173
|
-
this._undoStack = [];
|
|
174
|
-
this._redoStack = [];
|
|
175
|
-
this._inTransaction = false;
|
|
176
|
-
this._transactionSnapshot = null;
|
|
177
|
-
this._transactionMutated = false;
|
|
178
1683
|
this._sampleRate = options.sampleRate ?? DEFAULT_SAMPLE_RATE;
|
|
179
1684
|
this._zoomLevels = [...options.zoomLevels ?? DEFAULT_ZOOM_LEVELS];
|
|
180
1685
|
this._adapter = options.adapter ?? null;
|
|
181
|
-
this.undoLimit = options.undoLimit ?? 100;
|
|
182
1686
|
this._adapter?.onPlaybackEnded?.(() => {
|
|
183
1687
|
queueMicrotask(() => {
|
|
184
1688
|
if (this._isPlaying && !this._disposed) {
|
|
@@ -199,81 +1703,79 @@ var PlaylistEngine = class {
|
|
|
199
1703
|
this._zoomIndex = zoomIndex;
|
|
200
1704
|
this._bpm = options.bpm ?? 120;
|
|
201
1705
|
this._ppqn = options.adapter?.ppqn ?? options.ppqn ?? 960;
|
|
1706
|
+
const timeBase = {
|
|
1707
|
+
sampleRate: this._sampleRate,
|
|
1708
|
+
ppqn: this._ppqn,
|
|
1709
|
+
secondsToTicks: (seconds) => this._secondsToTicks(seconds),
|
|
1710
|
+
ticksToSeconds: (tick) => this._ticksToSeconds(tick)
|
|
1711
|
+
};
|
|
1712
|
+
if (options.arrangement) {
|
|
1713
|
+
this._arrangement = asArrangementImpl(options.arrangement);
|
|
1714
|
+
if (options.undoLimit !== void 0) {
|
|
1715
|
+
console.warn(
|
|
1716
|
+
"[waveform-playlist] PlaylistEngine: undoLimit is ignored when an arrangement is passed. Set it on createArrangement({ undoLimit })."
|
|
1717
|
+
);
|
|
1718
|
+
}
|
|
1719
|
+
} else {
|
|
1720
|
+
this._arrangement = new ArrangementImpl({ undoLimit: options.undoLimit });
|
|
1721
|
+
}
|
|
1722
|
+
this.undoLimit = this._arrangement.undoLimit;
|
|
1723
|
+
this._detachFromArrangement = attachTimeBase(this._arrangement, timeBase);
|
|
1724
|
+
this._adapterSync = new AdapterSync(this._arrangement, this._adapter);
|
|
1725
|
+
this._stopFollowingArrangement = this._arrangement.onChange(
|
|
1726
|
+
(change, at) => this._onArrangementChange(change, at)
|
|
1727
|
+
);
|
|
1728
|
+
try {
|
|
1729
|
+
this._adapterSync.sendInitialTracks();
|
|
1730
|
+
} catch (error) {
|
|
1731
|
+
this._stopFollowingArrangement();
|
|
1732
|
+
this._detachFromArrangement();
|
|
1733
|
+
throw error;
|
|
1734
|
+
}
|
|
1735
|
+
const adapter = this._adapter;
|
|
1736
|
+
if (adapter && options.attachDecodeContext !== false) {
|
|
1737
|
+
this._detachDecodeContext = attachDecodeContext(
|
|
1738
|
+
this._arrangement,
|
|
1739
|
+
async () => adapter.audioContext
|
|
1740
|
+
);
|
|
1741
|
+
}
|
|
202
1742
|
}
|
|
203
1743
|
// ---------------------------------------------------------------------------
|
|
204
1744
|
// Undo/Redo
|
|
205
1745
|
// ---------------------------------------------------------------------------
|
|
206
1746
|
get canUndo() {
|
|
207
|
-
return this.
|
|
1747
|
+
return this._arrangement.canUndo;
|
|
208
1748
|
}
|
|
209
1749
|
get canRedo() {
|
|
210
|
-
return this.
|
|
1750
|
+
return this._arrangement.canRedo;
|
|
211
1751
|
}
|
|
212
1752
|
undo() {
|
|
213
|
-
|
|
214
|
-
const snapshot = this._undoStack.pop();
|
|
215
|
-
this._redoStack.push(this._snapshotTracks());
|
|
216
|
-
this._restoreTracks(snapshot);
|
|
1753
|
+
this._arrangement.undo();
|
|
217
1754
|
}
|
|
218
1755
|
redo() {
|
|
219
|
-
|
|
220
|
-
const snapshot = this._redoStack.pop();
|
|
221
|
-
this._undoStack.push(this._snapshotTracks());
|
|
222
|
-
this._restoreTracks(snapshot);
|
|
1756
|
+
this._arrangement.redo();
|
|
223
1757
|
}
|
|
224
1758
|
clearHistory() {
|
|
225
|
-
this.
|
|
226
|
-
this._redoStack = [];
|
|
1759
|
+
this._arrangement.clearHistory();
|
|
227
1760
|
}
|
|
228
1761
|
beginTransaction() {
|
|
229
|
-
|
|
230
|
-
console.warn(
|
|
231
|
-
"[waveform-playlist/engine] beginTransaction: already in a transaction, previous snapshot will be overwritten"
|
|
232
|
-
);
|
|
233
|
-
}
|
|
234
|
-
this._transactionSnapshot = this._snapshotTracks();
|
|
235
|
-
this._inTransaction = true;
|
|
236
|
-
this._transactionMutated = false;
|
|
1762
|
+
this._arrangement.beginTransaction();
|
|
237
1763
|
}
|
|
238
1764
|
commitTransaction() {
|
|
239
|
-
|
|
240
|
-
console.warn("[waveform-playlist/engine] commitTransaction: no active transaction to commit");
|
|
241
|
-
return;
|
|
242
|
-
}
|
|
243
|
-
if (this._transactionMutated) {
|
|
244
|
-
this._undoStack.push(this._transactionSnapshot);
|
|
245
|
-
if (this._undoStack.length > this.undoLimit) {
|
|
246
|
-
this._undoStack.shift();
|
|
247
|
-
}
|
|
248
|
-
this._redoStack = [];
|
|
249
|
-
}
|
|
250
|
-
this._transactionSnapshot = null;
|
|
251
|
-
this._inTransaction = false;
|
|
252
|
-
this._transactionMutated = false;
|
|
1765
|
+
this._arrangement.commitTransaction();
|
|
253
1766
|
}
|
|
254
1767
|
abortTransaction() {
|
|
255
|
-
|
|
256
|
-
console.warn("[waveform-playlist/engine] abortTransaction: no active transaction to abort");
|
|
257
|
-
return;
|
|
258
|
-
}
|
|
259
|
-
const snapshot = this._transactionSnapshot;
|
|
260
|
-
const mutated = this._transactionMutated;
|
|
261
|
-
this._transactionSnapshot = null;
|
|
262
|
-
this._inTransaction = false;
|
|
263
|
-
this._transactionMutated = false;
|
|
264
|
-
if (mutated) {
|
|
265
|
-
this._restoreTracks(snapshot);
|
|
266
|
-
}
|
|
1768
|
+
this._arrangement.abortTransaction();
|
|
267
1769
|
}
|
|
268
1770
|
// ---------------------------------------------------------------------------
|
|
269
1771
|
// State snapshot
|
|
270
1772
|
// ---------------------------------------------------------------------------
|
|
271
1773
|
getState() {
|
|
272
1774
|
return {
|
|
273
|
-
tracks: this.
|
|
274
|
-
tracksVersion: this.
|
|
275
|
-
mixerVersion: this.
|
|
276
|
-
duration: calculateDuration(this.
|
|
1775
|
+
tracks: this._adapterSync.tracks(),
|
|
1776
|
+
tracksVersion: this._arrangement.tracksVersion,
|
|
1777
|
+
mixerVersion: this._arrangement.mixerVersion,
|
|
1778
|
+
duration: calculateDuration(this._adapterSync.tracks()),
|
|
277
1779
|
currentTime: this._currentTime,
|
|
278
1780
|
isPlaying: this._isPlaying,
|
|
279
1781
|
samplesPerPixel: this._zoomLevels[this._zoomIndex],
|
|
@@ -297,51 +1799,17 @@ var PlaylistEngine = class {
|
|
|
297
1799
|
// ---------------------------------------------------------------------------
|
|
298
1800
|
// Track Management
|
|
299
1801
|
// ---------------------------------------------------------------------------
|
|
1802
|
+
// A track holds audio clips or MIDI clips, never both (#756). The three
|
|
1803
|
+
// methods that take a track check it before they change anything, so a
|
|
1804
|
+
// throw leaves the engine, the undo history and the adapter untouched.
|
|
300
1805
|
setTracks(tracks) {
|
|
301
|
-
this.
|
|
302
|
-
this._tracks = tracks.map((track) => ({
|
|
303
|
-
...track,
|
|
304
|
-
clips: track.clips.map((clip) => ({
|
|
305
|
-
...clip,
|
|
306
|
-
startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
|
|
307
|
-
}))
|
|
308
|
-
}));
|
|
309
|
-
this._tracksVersion++;
|
|
310
|
-
this._adapter?.setTracks(this._tracks);
|
|
311
|
-
this._emitStateChange();
|
|
1806
|
+
this._arrangement.setTracks(tracks);
|
|
312
1807
|
}
|
|
313
1808
|
addTrack(track) {
|
|
314
|
-
this.
|
|
315
|
-
const enriched = {
|
|
316
|
-
...track,
|
|
317
|
-
clips: track.clips.map((clip) => ({
|
|
318
|
-
...clip,
|
|
319
|
-
startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
|
|
320
|
-
}))
|
|
321
|
-
};
|
|
322
|
-
this._tracks = [...this._tracks, enriched];
|
|
323
|
-
this._tracksVersion++;
|
|
324
|
-
if (this._adapter?.addTrack) {
|
|
325
|
-
this._adapter.addTrack(enriched);
|
|
326
|
-
} else {
|
|
327
|
-
this._adapter?.setTracks(this._tracks);
|
|
328
|
-
}
|
|
329
|
-
this._emitStateChange();
|
|
1809
|
+
this._arrangement.addTrack(track);
|
|
330
1810
|
}
|
|
331
1811
|
removeTrack(trackId) {
|
|
332
|
-
|
|
333
|
-
this._pushUndoSnapshot();
|
|
334
|
-
this._tracks = this._tracks.filter((t) => t.id !== trackId);
|
|
335
|
-
this._tracksVersion++;
|
|
336
|
-
if (this._selectedTrackId === trackId) {
|
|
337
|
-
this._selectedTrackId = null;
|
|
338
|
-
}
|
|
339
|
-
if (this._adapter?.removeTrack) {
|
|
340
|
-
this._adapter.removeTrack(trackId);
|
|
341
|
-
} else {
|
|
342
|
-
this._adapter?.setTracks(this._tracks);
|
|
343
|
-
}
|
|
344
|
-
this._emitStateChange();
|
|
1812
|
+
this._arrangement.removeTrack(trackId);
|
|
345
1813
|
}
|
|
346
1814
|
/**
|
|
347
1815
|
* Move a track to a new position in the track order. Purely organizational —
|
|
@@ -350,55 +1818,18 @@ var PlaylistEngine = class {
|
|
|
350
1818
|
* playout and interrupt playback for a visual-only change.
|
|
351
1819
|
*/
|
|
352
1820
|
reorderTrack(trackId, toIndex) {
|
|
353
|
-
|
|
354
|
-
if (fromIndex === -1) return;
|
|
355
|
-
const clamped = Math.max(0, Math.min(toIndex, this._tracks.length - 1));
|
|
356
|
-
if (clamped === fromIndex) return;
|
|
357
|
-
this._pushUndoSnapshot();
|
|
358
|
-
const track = this._tracks[fromIndex];
|
|
359
|
-
const without = this._tracks.filter((t) => t.id !== trackId);
|
|
360
|
-
this._tracks = [...without.slice(0, clamped), track, ...without.slice(clamped)];
|
|
361
|
-
this._tracksVersion++;
|
|
362
|
-
this._emitStateChange();
|
|
1821
|
+
this._arrangement.reorderTrack(trackId, toIndex);
|
|
363
1822
|
}
|
|
364
|
-
/**
|
|
1823
|
+
/**
|
|
1824
|
+
* With a track: replace that track (an undo step). Without one: send the
|
|
1825
|
+
* current track to the adapter again (no full rebuild, no change of state).
|
|
1826
|
+
*/
|
|
365
1827
|
updateTrack(trackId, track) {
|
|
366
|
-
const resolved = track ?? this._tracks.find((t) => t.id === trackId);
|
|
367
|
-
if (!resolved) return;
|
|
368
1828
|
if (track) {
|
|
369
|
-
this.
|
|
370
|
-
const enriched = {
|
|
371
|
-
...track,
|
|
372
|
-
clips: track.clips.map((clip) => ({
|
|
373
|
-
...clip,
|
|
374
|
-
startTick: clip.startTick ?? this._secondsToTicks(clip.startSample / this._sampleRate)
|
|
375
|
-
}))
|
|
376
|
-
};
|
|
377
|
-
this._tracks = this._tracks.map((t) => t.id === trackId ? enriched : t);
|
|
378
|
-
this._tracksVersion++;
|
|
379
|
-
if (this._adapter?.updateTrack) {
|
|
380
|
-
this._adapter.updateTrack(trackId, enriched);
|
|
381
|
-
} else {
|
|
382
|
-
this._adapter?.setTracks(this._tracks);
|
|
383
|
-
}
|
|
384
|
-
this._emitStateChange();
|
|
1829
|
+
this._arrangement.updateTrack(trackId, track);
|
|
385
1830
|
return;
|
|
386
1831
|
}
|
|
387
|
-
if (this.
|
|
388
|
-
this._adapter.updateTrack(trackId, resolved);
|
|
389
|
-
} else {
|
|
390
|
-
this._adapter?.setTracks(this._tracks);
|
|
391
|
-
}
|
|
392
|
-
}
|
|
393
|
-
/** Internal: update adapter after modifying this._tracks in place. */
|
|
394
|
-
_updateTrackOnAdapter(trackId) {
|
|
395
|
-
const t = this._tracks.find((tr) => tr.id === trackId);
|
|
396
|
-
if (!t) return;
|
|
397
|
-
if (this._adapter?.updateTrack) {
|
|
398
|
-
this._adapter.updateTrack(trackId, t);
|
|
399
|
-
} else {
|
|
400
|
-
this._adapter?.setTracks(this._tracks);
|
|
401
|
-
}
|
|
1832
|
+
if (!this._disposed) this._adapterSync.sendTrack(trackId);
|
|
402
1833
|
}
|
|
403
1834
|
selectTrack(trackId) {
|
|
404
1835
|
if (trackId === this._selectedTrackId) return;
|
|
@@ -410,166 +1841,38 @@ var PlaylistEngine = class {
|
|
|
410
1841
|
// ---------------------------------------------------------------------------
|
|
411
1842
|
/** Get a clip's full bounds for trim constraint computation. Returns null if not found. */
|
|
412
1843
|
getClipBounds(trackId, clipId) {
|
|
413
|
-
|
|
414
|
-
if (!track) return null;
|
|
415
|
-
const clip = track.clips.find((c) => c.id === clipId);
|
|
416
|
-
if (!clip) return null;
|
|
417
|
-
return {
|
|
418
|
-
offsetSamples: clip.offsetSamples,
|
|
419
|
-
durationSamples: clip.durationSamples,
|
|
420
|
-
startSample: clip.startSample,
|
|
421
|
-
sourceDurationSamples: clip.sourceDurationSamples
|
|
422
|
-
};
|
|
1844
|
+
return this._arrangement.getClipBounds(trackId, clipId);
|
|
423
1845
|
}
|
|
424
1846
|
/** Constrain a trim delta using the engine's collision/bounds logic.
|
|
425
1847
|
* Uses the clip's current state and neighboring clips for constraints. */
|
|
426
1848
|
constrainTrimDelta(trackId, clipId, boundary, deltaSamples) {
|
|
427
|
-
|
|
428
|
-
if (!track) return 0;
|
|
429
|
-
const clipIndex = track.clips.findIndex((c) => c.id === clipId);
|
|
430
|
-
if (clipIndex === -1) return 0;
|
|
431
|
-
const clip = track.clips[clipIndex];
|
|
432
|
-
const sortedClips = sortClipsByTime(track.clips);
|
|
433
|
-
const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
|
|
434
|
-
const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
|
|
435
|
-
return constrainBoundaryTrim(
|
|
436
|
-
clip,
|
|
437
|
-
deltaSamples,
|
|
438
|
-
boundary,
|
|
439
|
-
sortedClips,
|
|
440
|
-
sortedIndex,
|
|
441
|
-
minDuration
|
|
442
|
-
);
|
|
1849
|
+
return this._arrangement.constrainTrimDelta(trackId, clipId, boundary, deltaSamples);
|
|
443
1850
|
}
|
|
444
1851
|
// ---------------------------------------------------------------------------
|
|
445
|
-
// Clip Editing (delegates to
|
|
1852
|
+
// Clip Editing (delegates to the arrangement)
|
|
446
1853
|
// ---------------------------------------------------------------------------
|
|
447
|
-
/**
|
|
1854
|
+
/**
|
|
1855
|
+
* Move a clip by deltaSamples. Returns the constrained delta actually applied (0 if no-op).
|
|
1856
|
+
* With `skipAdapter` the change is not sent to the adapter (a drag sends the track once, on drop).
|
|
1857
|
+
*/
|
|
448
1858
|
moveClip(trackId, clipId, deltaSamples, skipAdapter = false) {
|
|
449
|
-
const
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
const clipIndex = track.clips.findIndex((c) => c.id === clipId);
|
|
455
|
-
if (clipIndex === -1) {
|
|
456
|
-
console.warn(
|
|
457
|
-
`[waveform-playlist/engine] moveClip: clip "${clipId}" not found in track "${trackId}"`
|
|
458
|
-
);
|
|
459
|
-
return 0;
|
|
460
|
-
}
|
|
461
|
-
const clip = track.clips[clipIndex];
|
|
462
|
-
const sortedClips = sortClipsByTime(track.clips);
|
|
463
|
-
const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
|
|
464
|
-
const constrainedDelta = constrainClipDrag(clip, deltaSamples, sortedClips, sortedIndex);
|
|
465
|
-
if (constrainedDelta === 0) return 0;
|
|
466
|
-
this._pushUndoSnapshot();
|
|
467
|
-
this._tracks = this._tracks.map((t) => {
|
|
468
|
-
if (t.id !== trackId) return t;
|
|
469
|
-
const newClips = t.clips.map((c, i) => {
|
|
470
|
-
if (i !== clipIndex) return c;
|
|
471
|
-
const newStartSample = Math.floor(c.startSample + constrainedDelta);
|
|
472
|
-
return {
|
|
473
|
-
...c,
|
|
474
|
-
startSample: newStartSample,
|
|
475
|
-
startTick: c.startTick !== void 0 ? this._secondsToTicks(newStartSample / this._sampleRate) : void 0
|
|
476
|
-
};
|
|
477
|
-
});
|
|
478
|
-
return { ...t, clips: newClips };
|
|
479
|
-
});
|
|
480
|
-
this._tracksVersion++;
|
|
481
|
-
if (!skipAdapter) {
|
|
482
|
-
this._updateTrackOnAdapter(trackId);
|
|
1859
|
+
const mark = this._adapterSync.markSkip(skipAdapter);
|
|
1860
|
+
try {
|
|
1861
|
+
return this._arrangement.moveClip(trackId, clipId, deltaSamples);
|
|
1862
|
+
} finally {
|
|
1863
|
+
this._adapterSync.unmarkIfUnchanged(mark);
|
|
483
1864
|
}
|
|
484
|
-
this._emitStateChange();
|
|
485
|
-
return constrainedDelta;
|
|
486
1865
|
}
|
|
487
1866
|
splitClip(trackId, clipId, atSample) {
|
|
488
|
-
|
|
489
|
-
if (!track) {
|
|
490
|
-
console.warn(`[waveform-playlist/engine] splitClip: track "${trackId}" not found`);
|
|
491
|
-
return;
|
|
492
|
-
}
|
|
493
|
-
const clipIndex = track.clips.findIndex((c) => c.id === clipId);
|
|
494
|
-
if (clipIndex === -1) {
|
|
495
|
-
console.warn(
|
|
496
|
-
`[waveform-playlist/engine] splitClip: clip "${clipId}" not found in track "${trackId}"`
|
|
497
|
-
);
|
|
498
|
-
return;
|
|
499
|
-
}
|
|
500
|
-
const clip = track.clips[clipIndex];
|
|
501
|
-
const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
|
|
502
|
-
if (!canSplitAt(clip, atSample, minDuration)) {
|
|
503
|
-
console.warn(
|
|
504
|
-
`[waveform-playlist/engine] splitClip: cannot split clip "${clipId}" at sample ${atSample} (clip range: ${clip.startSample}\u2013${clip.startSample + clip.durationSamples}, minDuration: ${minDuration})`
|
|
505
|
-
);
|
|
506
|
-
return;
|
|
507
|
-
}
|
|
508
|
-
this._pushUndoSnapshot();
|
|
509
|
-
const { left, right } = splitClip(clip, atSample);
|
|
510
|
-
const enrichedLeft = clip.startTick !== void 0 ? { ...left, startTick: this._secondsToTicks(left.startSample / this._sampleRate) } : left;
|
|
511
|
-
const enrichedRight = clip.startTick !== void 0 ? { ...right, startTick: this._secondsToTicks(right.startSample / this._sampleRate) } : right;
|
|
512
|
-
this._tracks = this._tracks.map((t) => {
|
|
513
|
-
if (t.id !== trackId) return t;
|
|
514
|
-
const newClips = [...t.clips];
|
|
515
|
-
newClips.splice(clipIndex, 1, enrichedLeft, enrichedRight);
|
|
516
|
-
return { ...t, clips: newClips };
|
|
517
|
-
});
|
|
518
|
-
this._tracksVersion++;
|
|
519
|
-
this._updateTrackOnAdapter(trackId);
|
|
520
|
-
this._emitStateChange();
|
|
1867
|
+
this._arrangement.splitClip(trackId, clipId, atSample);
|
|
521
1868
|
}
|
|
522
1869
|
trimClip(trackId, clipId, boundary, deltaSamples, skipAdapter = false) {
|
|
523
|
-
const
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
const clipIndex = track.clips.findIndex((c) => c.id === clipId);
|
|
529
|
-
if (clipIndex === -1) {
|
|
530
|
-
console.warn(
|
|
531
|
-
`[waveform-playlist/engine] trimClip: clip "${clipId}" not found in track "${trackId}"`
|
|
532
|
-
);
|
|
533
|
-
return;
|
|
534
|
-
}
|
|
535
|
-
const clip = track.clips[clipIndex];
|
|
536
|
-
const sortedClips = sortClipsByTime(track.clips);
|
|
537
|
-
const sortedIndex = sortedClips.findIndex((c) => c.id === clipId);
|
|
538
|
-
const minDuration = Math.floor(DEFAULT_MIN_DURATION_SECONDS * this._sampleRate);
|
|
539
|
-
const constrained = constrainBoundaryTrim(
|
|
540
|
-
clip,
|
|
541
|
-
deltaSamples,
|
|
542
|
-
boundary,
|
|
543
|
-
sortedClips,
|
|
544
|
-
sortedIndex,
|
|
545
|
-
minDuration
|
|
546
|
-
);
|
|
547
|
-
if (constrained === 0) return;
|
|
548
|
-
this._pushUndoSnapshot();
|
|
549
|
-
this._tracks = this._tracks.map((t) => {
|
|
550
|
-
if (t.id !== trackId) return t;
|
|
551
|
-
const newClips = t.clips.map((c, i) => {
|
|
552
|
-
if (i !== clipIndex) return c;
|
|
553
|
-
if (boundary === "left") {
|
|
554
|
-
const newStartSample = c.startSample + constrained;
|
|
555
|
-
return {
|
|
556
|
-
...c,
|
|
557
|
-
startSample: newStartSample,
|
|
558
|
-
startTick: c.startTick !== void 0 ? this._secondsToTicks(newStartSample / this._sampleRate) : void 0,
|
|
559
|
-
offsetSamples: c.offsetSamples + constrained,
|
|
560
|
-
durationSamples: c.durationSamples - constrained
|
|
561
|
-
};
|
|
562
|
-
} else {
|
|
563
|
-
return { ...c, durationSamples: c.durationSamples + constrained };
|
|
564
|
-
}
|
|
565
|
-
});
|
|
566
|
-
return { ...t, clips: newClips };
|
|
567
|
-
});
|
|
568
|
-
this._tracksVersion++;
|
|
569
|
-
if (!skipAdapter) {
|
|
570
|
-
this._updateTrackOnAdapter(trackId);
|
|
1870
|
+
const mark = this._adapterSync.markSkip(skipAdapter);
|
|
1871
|
+
try {
|
|
1872
|
+
this._arrangement.trimClip(trackId, clipId, boundary, deltaSamples);
|
|
1873
|
+
} finally {
|
|
1874
|
+
this._adapterSync.unmarkIfUnchanged(mark);
|
|
571
1875
|
}
|
|
572
|
-
this._emitStateChange();
|
|
573
1876
|
}
|
|
574
1877
|
// ---------------------------------------------------------------------------
|
|
575
1878
|
// Playback (delegates to adapter, no-ops without adapter)
|
|
@@ -640,11 +1943,11 @@ var PlaylistEngine = class {
|
|
|
640
1943
|
return;
|
|
641
1944
|
}
|
|
642
1945
|
if (bpm === this._bpm && atTick === void 0) return;
|
|
1946
|
+
if (this._disposed) return;
|
|
643
1947
|
const accepted = this._adapter?.setTempo?.(bpm, atTick);
|
|
644
1948
|
if (accepted === false) return;
|
|
645
1949
|
this._bpm = bpm;
|
|
646
|
-
this.
|
|
647
|
-
this._emitStateChange();
|
|
1950
|
+
this._arrangement.recomputeStartSamples();
|
|
648
1951
|
}
|
|
649
1952
|
getCurrentTime() {
|
|
650
1953
|
if (this._adapter) {
|
|
@@ -722,45 +2025,36 @@ var PlaylistEngine = class {
|
|
|
722
2025
|
this._emitStateChange();
|
|
723
2026
|
}
|
|
724
2027
|
// ---------------------------------------------------------------------------
|
|
725
|
-
// Per-Track Audio (
|
|
2028
|
+
// Per-Track Audio (persists into the arrangement, forwards to adapter, emits)
|
|
726
2029
|
// ---------------------------------------------------------------------------
|
|
727
2030
|
//
|
|
728
|
-
// Each setter
|
|
729
|
-
//
|
|
730
|
-
//
|
|
731
|
-
//
|
|
2031
|
+
// Each setter writes the value into the arrangement's mixer part (so a later
|
|
2032
|
+
// adapter rebuild via setTracks keeps the value, and mixerVersion is bumped);
|
|
2033
|
+
// the engine's listener then calls the adapter and emits statechange. For a
|
|
2034
|
+
// track the arrangement does not hold nothing changes, and the adapter is
|
|
2035
|
+
// still called from here (a consumer may target a track that has not been
|
|
2036
|
+
// ingested yet). These are NOT structural
|
|
2037
|
+
// changes, so they deliberately do NOT bump tracksVersion — that would make
|
|
732
2038
|
// tracksVersion-gated consumers re-run expensive structural work (audio-graph
|
|
733
2039
|
// rewire, peak regeneration) on every volume/pan drag frame. Consumers that
|
|
734
2040
|
// cache a track snapshot (e.g. @dawcore/components' <daw-editor>) watch
|
|
735
|
-
//
|
|
2041
|
+
// mixerVersion to refresh that cache cheaply, so an unrelated setTracks
|
|
736
2042
|
// rebuild no longer reverts live mixer state (#501).
|
|
737
2043
|
setTrackVolume(trackId, volume) {
|
|
738
|
-
const
|
|
739
|
-
if (
|
|
740
|
-
this._adapter?.setTrackVolume(trackId, volume);
|
|
741
|
-
this._mixerVersion++;
|
|
742
|
-
this._emitStateChange();
|
|
2044
|
+
const changed = this._mixerChanged(() => this._arrangement.setTrackVolume(trackId, volume));
|
|
2045
|
+
if (!changed && !this._disposed) this._adapter?.setTrackVolume(trackId, volume);
|
|
743
2046
|
}
|
|
744
2047
|
setTrackMute(trackId, muted) {
|
|
745
|
-
const
|
|
746
|
-
if (
|
|
747
|
-
this._adapter?.setTrackMute(trackId, muted);
|
|
748
|
-
this._mixerVersion++;
|
|
749
|
-
this._emitStateChange();
|
|
2048
|
+
const changed = this._mixerChanged(() => this._arrangement.setTrackMute(trackId, muted));
|
|
2049
|
+
if (!changed && !this._disposed) this._adapter?.setTrackMute(trackId, muted);
|
|
750
2050
|
}
|
|
751
2051
|
setTrackSolo(trackId, soloed) {
|
|
752
|
-
const
|
|
753
|
-
if (
|
|
754
|
-
this._adapter?.setTrackSolo(trackId, soloed);
|
|
755
|
-
this._mixerVersion++;
|
|
756
|
-
this._emitStateChange();
|
|
2052
|
+
const changed = this._mixerChanged(() => this._arrangement.setTrackSolo(trackId, soloed));
|
|
2053
|
+
if (!changed && !this._disposed) this._adapter?.setTrackSolo(trackId, soloed);
|
|
757
2054
|
}
|
|
758
2055
|
setTrackPan(trackId, pan) {
|
|
759
|
-
const
|
|
760
|
-
if (
|
|
761
|
-
this._adapter?.setTrackPan(trackId, pan);
|
|
762
|
-
this._mixerVersion++;
|
|
763
|
-
this._emitStateChange();
|
|
2056
|
+
const changed = this._mixerChanged(() => this._arrangement.setTrackPan(trackId, pan));
|
|
2057
|
+
if (!changed && !this._disposed) this._adapter?.setTrackPan(trackId, pan);
|
|
764
2058
|
}
|
|
765
2059
|
// ---------------------------------------------------------------------------
|
|
766
2060
|
// Zoom
|
|
@@ -801,6 +2095,10 @@ var PlaylistEngine = class {
|
|
|
801
2095
|
dispose() {
|
|
802
2096
|
if (this._disposed) return;
|
|
803
2097
|
this._disposed = true;
|
|
2098
|
+
this._stopFollowingArrangement();
|
|
2099
|
+
this._detachFromArrangement();
|
|
2100
|
+
this._detachDecodeContext?.();
|
|
2101
|
+
this._detachDecodeContext = null;
|
|
804
2102
|
this._isPlaying = false;
|
|
805
2103
|
this._adapter?.onPlaybackEnded?.(null);
|
|
806
2104
|
try {
|
|
@@ -813,34 +2111,61 @@ var PlaylistEngine = class {
|
|
|
813
2111
|
// ---------------------------------------------------------------------------
|
|
814
2112
|
// Private helpers
|
|
815
2113
|
// ---------------------------------------------------------------------------
|
|
816
|
-
|
|
817
|
-
|
|
2114
|
+
/** Runs a mixer setter on the arrangement. True when a value changed. */
|
|
2115
|
+
_mixerChanged(change) {
|
|
2116
|
+
const version = this._arrangement.mixerVersion;
|
|
2117
|
+
change();
|
|
2118
|
+
return this._arrangement.mixerVersion !== version;
|
|
818
2119
|
}
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
2120
|
+
/**
|
|
2121
|
+
* The arrangement changed: bring the adapter in step, then emit
|
|
2122
|
+
* `statechange`. Every change is one emission. An adapter that throws
|
|
2123
|
+
* stops the emission and fails the arrangement call that is delivering
|
|
2124
|
+
* (for a change made from inside a listener, that is the outer call).
|
|
2125
|
+
*/
|
|
2126
|
+
_onArrangementChange(change, at) {
|
|
2127
|
+
switch (change.type) {
|
|
2128
|
+
case "mixer":
|
|
2129
|
+
this._adapterSync.sendMixerValues(change.trackId, change.values);
|
|
2130
|
+
break;
|
|
2131
|
+
case "reorder":
|
|
2132
|
+
// not audible: adapter nodes are keyed by track id
|
|
2133
|
+
case "history":
|
|
2134
|
+
break;
|
|
2135
|
+
default:
|
|
2136
|
+
if (change.type === "remove" || change.type === "restore" || change.type === "update") {
|
|
2137
|
+
this._clearSelectionIfGone();
|
|
2138
|
+
}
|
|
2139
|
+
if (change.type === "load") {
|
|
2140
|
+
this._followLoad(change, at);
|
|
2141
|
+
} else {
|
|
2142
|
+
this._adapterSync.follow(change, at);
|
|
2143
|
+
}
|
|
823
2144
|
}
|
|
824
|
-
this.
|
|
825
|
-
|
|
826
|
-
|
|
2145
|
+
this._emitStateChange();
|
|
2146
|
+
}
|
|
2147
|
+
/**
|
|
2148
|
+
* Audio arrived by itself: there is no caller to fail when the adapter
|
|
2149
|
+
* throws. The error is reported, the `statechange` is still emitted (the
|
|
2150
|
+
* tracks did change), and the next track change sends the adapter every
|
|
2151
|
+
* track.
|
|
2152
|
+
*/
|
|
2153
|
+
_followLoad(change, at) {
|
|
2154
|
+
try {
|
|
2155
|
+
this._adapterSync.follow(change, at);
|
|
2156
|
+
} catch (error) {
|
|
2157
|
+
console.error(
|
|
2158
|
+
"[waveform-playlist] The playout adapter failed while loaded audio was applied:",
|
|
2159
|
+
error
|
|
2160
|
+
);
|
|
827
2161
|
}
|
|
828
|
-
this._redoStack = [];
|
|
829
2162
|
}
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
this.
|
|
834
|
-
|
|
835
|
-
for (let i = 0; i < snapshot.length; i++) {
|
|
836
|
-
if (oldTracks[i] !== snapshot[i]) {
|
|
837
|
-
this._updateTrackOnAdapter(snapshot[i].id);
|
|
838
|
-
}
|
|
839
|
-
}
|
|
840
|
-
} else {
|
|
841
|
-
this._adapter?.setTracks(this._tracks);
|
|
2163
|
+
/** The selected track id names a track; when that track is gone, nothing is selected. */
|
|
2164
|
+
_clearSelectionIfGone() {
|
|
2165
|
+
const selected = this._selectedTrackId;
|
|
2166
|
+
if (selected !== null && !this._arrangement.getTracks().some((t) => t.id === selected)) {
|
|
2167
|
+
this._selectedTrackId = null;
|
|
842
2168
|
}
|
|
843
|
-
this._emitStateChange();
|
|
844
2169
|
}
|
|
845
2170
|
_emit(event, ...args) {
|
|
846
2171
|
const listeners = this._listeners.get(event);
|
|
@@ -879,28 +2204,19 @@ var PlaylistEngine = class {
|
|
|
879
2204
|
}
|
|
880
2205
|
return Math.round(seconds * this._ppqn * this._bpm / 60);
|
|
881
2206
|
}
|
|
882
|
-
_recomputeStartSamples() {
|
|
883
|
-
this._tracks = this._tracks.map((track) => ({
|
|
884
|
-
...track,
|
|
885
|
-
clips: track.clips.map((clip) => {
|
|
886
|
-
if (clip.startTick === void 0) return clip;
|
|
887
|
-
return {
|
|
888
|
-
...clip,
|
|
889
|
-
startSample: Math.round(this._ticksToSeconds(clip.startTick) * this._sampleRate)
|
|
890
|
-
};
|
|
891
|
-
})
|
|
892
|
-
}));
|
|
893
|
-
this._tracksVersion++;
|
|
894
|
-
for (const track of this._tracks) {
|
|
895
|
-
this._updateTrackOnAdapter(track.id);
|
|
896
|
-
}
|
|
897
|
-
}
|
|
898
2207
|
_emitStateChange() {
|
|
899
2208
|
this._emit("statechange", this.getState());
|
|
900
2209
|
}
|
|
901
2210
|
};
|
|
2211
|
+
function asArrangementImpl(arrangement) {
|
|
2212
|
+
if (isArrangement(arrangement)) return arrangement;
|
|
2213
|
+
throw new Error(
|
|
2214
|
+
"[waveform-playlist] PlaylistEngine: the `arrangement` option must be an arrangement made by createArrangement()."
|
|
2215
|
+
);
|
|
2216
|
+
}
|
|
902
2217
|
export {
|
|
903
2218
|
PlaylistEngine,
|
|
2219
|
+
attachDecodeContext,
|
|
904
2220
|
calculateDuration,
|
|
905
2221
|
calculateSplitPoint,
|
|
906
2222
|
calculateViewportBounds,
|
|
@@ -909,6 +2225,8 @@ export {
|
|
|
909
2225
|
clampSeekPosition,
|
|
910
2226
|
constrainBoundaryTrim,
|
|
911
2227
|
constrainClipDrag,
|
|
2228
|
+
createArrangement,
|
|
2229
|
+
defaultLoadSource,
|
|
912
2230
|
findClosestZoomIndex,
|
|
913
2231
|
getVisibleChunkIndices,
|
|
914
2232
|
shouldUpdateViewport,
|