@waveform-playlist/core 12.6.2 → 13.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/dist/index.js CHANGED
@@ -26,6 +26,7 @@ __export(index_exports, {
26
26
  InteractionState: () => InteractionState,
27
27
  LINK_THRESHOLD: () => LINK_THRESHOLD,
28
28
  MAX_CANVAS_WIDTH: () => MAX_CANVAS_WIDTH,
29
+ METER_PEAK_DECAY: () => METER_PEAK_DECAY,
29
30
  MIN_ANNOTATION_DURATION: () => MIN_ANNOTATION_DURATION,
30
31
  MIN_PIXELS_PER_UNIT: () => MIN_PIXELS_PER_UNIT,
31
32
  PPQN: () => PPQN,
@@ -35,12 +36,15 @@ __export(index_exports, {
35
36
  appendToAudioBuffer: () => appendToAudioBuffer,
36
37
  applyFadeIn: () => applyFadeIn,
37
38
  applyFadeOut: () => applyFadeOut,
39
+ assertTrackKind: () => assertTrackKind,
38
40
  audibleLatencySamples: () => audibleLatencySamples,
41
+ audioTrack: () => audioTrack,
39
42
  buildSpectrogramCanvasId: () => buildSpectrogramCanvasId,
40
43
  calculateDuration: () => calculateDuration,
41
44
  carveClipRange: () => carveClipRange,
42
45
  clipDurationTime: () => clipDurationTime,
43
46
  clipEndTime: () => clipEndTime,
47
+ clipKind: () => clipKind,
44
48
  clipOffsetTime: () => clipOffsetTime,
45
49
  clipPixelWidth: () => clipPixelWidth,
46
50
  clipStartTime: () => clipStartTime,
@@ -51,10 +55,15 @@ __export(index_exports, {
51
55
  createClip: () => createClip,
52
56
  createClipFromSeconds: () => createClipFromSeconds,
53
57
  createClipFromTicks: () => createClipFromTicks,
58
+ createEffectInstance: () => createEffectInstance,
59
+ createPanStage: () => createPanStage,
60
+ createSourceLoader: () => createSourceLoader,
54
61
  createTimeline: () => createTimeline,
55
62
  createTrack: () => createTrack,
63
+ createValueSource: () => createValueSource,
56
64
  dBToNormalized: () => dBToNormalized,
57
65
  detectMeterChanges: () => detectMeterChanges,
66
+ ensureEffectPrepared: () => ensureEffectPrepared,
58
67
  enumerateMicrophones: () => enumerateMicrophones,
59
68
  exponentialCurve: () => exponentialCurve,
60
69
  findGaps: () => findGaps,
@@ -64,16 +73,23 @@ __export(index_exports, {
64
73
  generatePeaks: () => generatePeaks,
65
74
  getClipsAtSample: () => getClipsAtSample,
66
75
  getClipsInRange: () => getClipsInRange,
67
- getShortcutLabel: () => getShortcutLabel,
76
+ getEffectDefinitions: () => getEffectDefinitions,
68
77
  handleKeyboardEvent: () => handleKeyboardEvent,
78
+ isLoadingClip: () => isLoadingClip,
79
+ keyBelongsToFocusedControl: () => keyBelongsToFocusedControl,
69
80
  linearCurve: () => linearCurve,
70
81
  logarithmicCurve: () => logarithmicCurve,
71
82
  matchesKeyBinding: () => matchesKeyBinding,
83
+ needsPrepare: () => needsPrepare,
72
84
  normalizedToDb: () => normalizedToDb,
85
+ panMatrix: () => panMatrix,
73
86
  parseSpectrogramCanvasId: () => parseSpectrogramCanvasId,
74
87
  pixelsToSamples: () => pixelsToSamples,
75
88
  pixelsToSeconds: () => pixelsToSeconds,
89
+ prepareEffect: () => prepareEffect,
76
90
  probeRangeSupport: () => probeRangeSupport,
91
+ readMeterMessage: () => readMeterMessage,
92
+ registerEffect: () => registerEffect,
77
93
  resolveAnnotationShortcuts: () => resolveAnnotationShortcuts,
78
94
  resolveRecordingOffsetSamples: () => resolveRecordingOffsetSamples,
79
95
  sCurveCurve: () => sCurveCurve,
@@ -82,15 +98,19 @@ __export(index_exports, {
82
98
  samplesToTicks: () => samplesToTicks,
83
99
  secondsToPixels: () => secondsToPixels,
84
100
  secondsToSamples: () => secondsToSamples,
101
+ silentMeterLevels: () => silentMeterLevels,
85
102
  snapTickToGrid: () => snapTickToGrid,
86
103
  snapToGrid: () => snapToGrid,
87
104
  snapToTicks: () => snapToTicks,
88
105
  sortClipsByTime: () => sortClipsByTime,
106
+ splitTrackByKind: () => splitTrackByKind,
89
107
  ticksPerBar: () => ticksPerBar,
90
108
  ticksPerBeat: () => ticksPerBeat,
91
109
  ticksToBarBeat: () => ticksToBarBeat,
92
110
  ticksToSamples: () => ticksToSamples,
93
111
  trackChannelCount: () => trackChannelCount,
112
+ trackKind: () => trackKind,
113
+ unregisterEffect: () => unregisterEffect,
94
114
  updateAnnotationBoundaries: () => updateAnnotationBoundaries,
95
115
  watchMicrophoneDevices: () => watchMicrophoneDevices
96
116
  });
@@ -100,6 +120,9 @@ module.exports = __toCommonJS(index_exports);
100
120
  var MAX_CANVAS_WIDTH = 1e3;
101
121
 
102
122
  // src/types/clip.ts
123
+ function isLoadingClip(clip) {
124
+ return !("sampleRate" in clip) || clip.sampleRate == null;
125
+ }
103
126
  function createClipFromTicks(options) {
104
127
  const { startTick, ticksToSeconds, bpm, ppqn } = options;
105
128
  if (startTick < 0) {
@@ -136,7 +159,8 @@ function createClipFromTicks(options) {
136
159
  sourceDurationSamples: options.sourceDurationSamples,
137
160
  midiNotes: options.midiNotes,
138
161
  midiChannel: options.midiChannel,
139
- midiProgram: options.midiProgram
162
+ midiProgram: options.midiProgram,
163
+ src: options.src
140
164
  });
141
165
  }
142
166
  function createClip(options) {
@@ -153,7 +177,8 @@ function createClip(options) {
153
177
  waveformData,
154
178
  midiNotes,
155
179
  midiChannel,
156
- midiProgram
180
+ midiProgram,
181
+ src
157
182
  } = options;
158
183
  const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;
159
184
  const sourceDurationSamples = audioBuffer?.length ?? options.sourceDurationSamples ?? (waveformData && sampleRate ? Math.ceil(waveformData.duration * sampleRate) : void 0);
@@ -190,7 +215,8 @@ function createClip(options) {
190
215
  waveformData,
191
216
  midiNotes,
192
217
  midiChannel,
193
- midiProgram
218
+ midiProgram,
219
+ ...src !== void 0 ? { src } : {}
194
220
  };
195
221
  }
196
222
  function createClipFromSeconds(options) {
@@ -206,7 +232,8 @@ function createClipFromSeconds(options) {
206
232
  waveformData,
207
233
  midiNotes,
208
234
  midiChannel,
209
- midiProgram
235
+ midiProgram,
236
+ src
210
237
  } = options;
211
238
  const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;
212
239
  if (sampleRate === void 0) {
@@ -237,12 +264,14 @@ function createClipFromSeconds(options) {
237
264
  waveformData,
238
265
  midiNotes,
239
266
  midiChannel,
240
- midiProgram
267
+ midiProgram,
268
+ src
241
269
  });
242
270
  }
243
271
  function createTrack(options) {
244
272
  const {
245
273
  name,
274
+ kind = "audio",
246
275
  clips = [],
247
276
  muted = false,
248
277
  soloed = false,
@@ -255,6 +284,7 @@ function createTrack(options) {
255
284
  } = options;
256
285
  return {
257
286
  id: generateId(),
287
+ kind,
258
288
  name,
259
289
  clips,
260
290
  muted,
@@ -542,14 +572,14 @@ function computeMusicalTicks(params) {
542
572
  }
543
573
  const barIndexInSegment = Math.floor(tickOffsetInSegment / tpBar);
544
574
  const barIndex = barOffset + barIndexInSegment;
545
- let label;
575
+ let label2;
546
576
  if (type === "major") {
547
- label = `${barIndex + 1}`;
577
+ label2 = `${barIndex + 1}`;
548
578
  } else if (type === "minor" && tpBeat / ticksPerPixel >= MIN_PIXELS_PER_LABEL) {
549
579
  const beatInBar = Math.floor(tickOffsetInSegment % tpBar / tpBeat) + 1;
550
- label = `${barIndex + 1}.${beatInBar}`;
580
+ label2 = `${barIndex + 1}.${beatInBar}`;
551
581
  }
552
- ticks.push({ pixel, type, barIndex, ...label !== void 0 ? { label } : {} });
582
+ ticks.push({ pixel, type, barIndex, ...label2 !== void 0 ? { label: label2 } : {} });
553
583
  }
554
584
  }
555
585
  ticks.sort((a, b) => a.pixel - b.pixel);
@@ -817,6 +847,31 @@ function carveClipRange(clips, rangeStart, rangeEnd) {
817
847
  return result;
818
848
  }
819
849
 
850
+ // src/utils/meterLevels.ts
851
+ var METER_PEAK_DECAY = 0.98;
852
+ function readMeterMessage({
853
+ data,
854
+ previousSmoothedPeaks,
855
+ heldPeakLevels,
856
+ minChannels = 0
857
+ }) {
858
+ const channels = Math.floor(data.length / 2);
859
+ const smoothedPeaks = [];
860
+ const peaks = [];
861
+ const rms = [];
862
+ for (let ch = 0; ch < channels; ch++) {
863
+ const smoothed = Math.max(data[ch], (previousSmoothedPeaks[ch] ?? 0) * METER_PEAK_DECAY);
864
+ smoothedPeaks.push(smoothed);
865
+ peaks.push(gainToNormalized(smoothed));
866
+ rms.push(gainToNormalized(data[channels + ch]));
867
+ }
868
+ const mirror = channels > 0 && channels < minChannels;
869
+ const levels = mirror ? new Array(minChannels).fill(peaks[0]) : peaks;
870
+ const rmsLevels = mirror ? new Array(minChannels).fill(rms[0]) : rms;
871
+ const peakLevels = levels.map((level, i) => Math.max(heldPeakLevels[i] ?? 0, level));
872
+ return { smoothedPeaks, levels: { levels, peakLevels, rmsLevels } };
873
+ }
874
+
820
875
  // src/clipTimeHelpers.ts
821
876
  function clipStartTime(clip) {
822
877
  return clip.startSample / clip.sampleRate;
@@ -840,6 +895,46 @@ function clipPixelWidth(startSample, durationSamples, samplesPerPixel) {
840
895
  return Math.floor((startSample + durationSamples) / samplesPerPixel) - Math.floor(startSample / samplesPerPixel);
841
896
  }
842
897
 
898
+ // src/trackKind.ts
899
+ function clipKind(clip) {
900
+ return clip.midiNotes != null ? "midi" : "audio";
901
+ }
902
+ function trackKind(track) {
903
+ return track.kind ?? "audio";
904
+ }
905
+ function label(named) {
906
+ return '"' + (named.name || named.id) + '"';
907
+ }
908
+ function assertTrackKind(track) {
909
+ const kind = trackKind(track);
910
+ if (kind !== "audio" && kind !== "midi") {
911
+ throw new Error(
912
+ "[waveform-playlist] Track " + label(track) + ' has kind "' + String(kind) + `"; a track's kind is 'audio' or 'midi'.`
913
+ );
914
+ }
915
+ const stray = track.clips.find((clip) => clipKind(clip) !== kind);
916
+ if (!stray) return;
917
+ const strayKind = clipKind(stray);
918
+ const fix = track.kind === void 0 ? "The track has no kind, which is read as 'audio': set kind: 'midi' on a track of MIDI clips." : "A track holds one kind of clip: put the clip on a track of its own kind (splitTrackByKind() splits a track that has both).";
919
+ throw new Error(
920
+ "[waveform-playlist] Track " + label(track) + " is an " + kind + " track but its clip " + label(stray) + " is " + (strayKind === "audio" ? "an audio" : "a midi") + " clip. " + fix
921
+ );
922
+ }
923
+ function splitTrackByKind(track, midiTrackId = track.id + "-midi") {
924
+ const audioClips = track.clips.filter((clip) => clipKind(clip) === "audio");
925
+ const midiClips = track.clips.filter((clip) => clipKind(clip) === "midi");
926
+ if (midiClips.length === 0) {
927
+ return [{ ...track, kind: track.clips.length === 0 ? track.kind ?? "audio" : "audio" }];
928
+ }
929
+ if (audioClips.length === 0) {
930
+ return [{ ...track, kind: "midi" }];
931
+ }
932
+ return [
933
+ { ...track, kind: "audio", clips: audioClips },
934
+ { ...track, id: midiTrackId, kind: "midi", clips: midiClips }
935
+ ];
936
+ }
937
+
843
938
  // src/spectrogramCanvasId.ts
844
939
  var CANVAS_ID_RE = /^(.+)-ch(\d+)-chunk(\d+)$/;
845
940
  function buildSpectrogramCanvasId(parts) {
@@ -952,13 +1047,80 @@ function matchesKeyBinding(event, binding) {
952
1047
  const altMatch = binding.altKey === void 0 || event.altKey === binding.altKey;
953
1048
  return keyMatch && ctrlMatch && shiftMatch && metaMatch && altMatch;
954
1049
  }
1050
+ var ELEMENT_NODE = 1;
1051
+ function elementPath(event) {
1052
+ const composed = typeof event.composedPath === "function" ? event.composedPath() : [];
1053
+ if (composed.length > 0) {
1054
+ return composed.filter(
1055
+ (node) => node?.nodeType === ELEMENT_NODE
1056
+ );
1057
+ }
1058
+ const path = [];
1059
+ let current = event.target;
1060
+ while (current && current.nodeType === ELEMENT_NODE) {
1061
+ path.push(current);
1062
+ current = current.parentElement;
1063
+ }
1064
+ return path;
1065
+ }
1066
+ function matchesOr(element, selector, fallback) {
1067
+ try {
1068
+ return element.matches(selector);
1069
+ } catch {
1070
+ return fallback;
1071
+ }
1072
+ }
1073
+ function ownsAllKeys(element) {
1074
+ const tag = element.tagName;
1075
+ return tag === "INPUT" || tag === "TEXTAREA" || tag === "SELECT" || element.isContentEditable === true;
1076
+ }
1077
+ function activates(element, key) {
1078
+ if (key !== " " && key !== "Enter") return false;
1079
+ const tag = element.tagName;
1080
+ if (tag === "BUTTON") return element.disabled !== true;
1081
+ if (tag === "SUMMARY") return true;
1082
+ return key === "Enter" && (tag === "A" || tag === "AREA") && element.hasAttribute("href");
1083
+ }
1084
+ function isRendered(element) {
1085
+ if (element.hasAttribute("hidden")) return false;
1086
+ if (element.getAttribute("aria-hidden") === "true") return false;
1087
+ const check = element.checkVisibility;
1088
+ if (typeof check !== "function") return true;
1089
+ try {
1090
+ return check.call(element, { visibilityProperty: true, opacityProperty: true });
1091
+ } catch {
1092
+ return true;
1093
+ }
1094
+ }
1095
+ function isOpenModal(element) {
1096
+ if (element.getAttribute("aria-modal") === "true") {
1097
+ return isRendered(element);
1098
+ }
1099
+ return element.tagName === "DIALOG" && element.hasAttribute("open") && matchesOr(element, ":modal", true);
1100
+ }
1101
+ function documentHasOpenModal(doc) {
1102
+ if (!doc) return false;
1103
+ try {
1104
+ return Array.from(doc.querySelectorAll('dialog[open], [aria-modal="true"]')).some(isOpenModal);
1105
+ } catch {
1106
+ return false;
1107
+ }
1108
+ }
1109
+ function keyBelongsToFocusedControl(event) {
1110
+ const path = elementPath(event);
1111
+ const focused = path[0];
1112
+ if (event.key === "Escape") {
1113
+ const doc = focused?.ownerDocument ?? (typeof document !== "undefined" ? document : null);
1114
+ if (path.some(isOpenModal) || documentHasOpenModal(doc)) return true;
1115
+ }
1116
+ if (!focused) return false;
1117
+ if (ownsAllKeys(focused)) return true;
1118
+ return activates(focused, event.key);
1119
+ }
955
1120
  function handleKeyboardEvent(event, shortcuts, enabled) {
956
1121
  if (!enabled) return;
957
1122
  if (event.repeat) return;
958
- const target = event.target;
959
- if (target.tagName === "INPUT" || target.tagName === "TEXTAREA" || target.isContentEditable) {
960
- return;
961
- }
1123
+ if (keyBelongsToFocusedControl(event)) return;
962
1124
  const matchingShortcut = shortcuts.find((shortcut) => matchesKeyBinding(event, shortcut));
963
1125
  if (matchingShortcut) {
964
1126
  if (matchingShortcut.preventDefault !== false) {
@@ -967,24 +1129,6 @@ function handleKeyboardEvent(event, shortcuts, enabled) {
967
1129
  matchingShortcut.action();
968
1130
  }
969
1131
  }
970
- var getShortcutLabel = (shortcut) => {
971
- const parts = [];
972
- const isMac = typeof navigator !== "undefined" && navigator.platform.includes("Mac");
973
- if (shortcut.metaKey) {
974
- parts.push(isMac ? "Cmd" : "Ctrl");
975
- }
976
- if (shortcut.ctrlKey && !shortcut.metaKey) {
977
- parts.push("Ctrl");
978
- }
979
- if (shortcut.altKey) {
980
- parts.push(isMac ? "Option" : "Alt");
981
- }
982
- if (shortcut.shiftKey) {
983
- parts.push("Shift");
984
- }
985
- parts.push(shortcut.key.toUpperCase());
986
- return parts.join("+");
987
- };
988
1132
 
989
1133
  // src/probeRangeSupport.ts
990
1134
  async function probeRangeSupport(url, fetchImpl = fetch) {
@@ -1076,14 +1220,13 @@ function updateAnnotationBoundaries(params, options = {}) {
1076
1220
  const annotation = annotations[annotationIndex];
1077
1221
  if (isDraggingStart) {
1078
1222
  const constrainedStart = Math.min(annotation.end - minDuration, Math.max(0, newTime));
1079
- const delta = constrainedStart - annotation.start;
1080
1223
  updatedAnnotations[annotationIndex] = { ...annotation, start: constrainedStart };
1081
1224
  if (linkEndpoints && annotationIndex > 0) {
1082
1225
  const prevAnnotation = updatedAnnotations[annotationIndex - 1];
1083
1226
  if (Math.abs(prevAnnotation.end - annotation.start) < linkThreshold) {
1084
1227
  updatedAnnotations[annotationIndex - 1] = {
1085
1228
  ...prevAnnotation,
1086
- end: Math.max(prevAnnotation.start + minDuration, prevAnnotation.end + delta)
1229
+ end: Math.max(prevAnnotation.start + minDuration, constrainedStart)
1087
1230
  };
1088
1231
  } else if (constrainedStart <= prevAnnotation.end) {
1089
1232
  updatedAnnotations[annotationIndex] = {
@@ -1099,15 +1242,13 @@ function updateAnnotationBoundaries(params, options = {}) {
1099
1242
  }
1100
1243
  } else {
1101
1244
  const constrainedEnd = Math.max(annotation.start + minDuration, Math.min(newTime, duration));
1102
- const delta = constrainedEnd - annotation.end;
1103
1245
  updatedAnnotations[annotationIndex] = { ...annotation, end: constrainedEnd };
1104
1246
  if (linkEndpoints && annotationIndex < updatedAnnotations.length - 1) {
1105
1247
  const nextAnnotation = updatedAnnotations[annotationIndex + 1];
1106
1248
  if (Math.abs(nextAnnotation.start - annotation.end) < linkThreshold) {
1107
- const newStart = nextAnnotation.start + delta;
1108
1249
  updatedAnnotations[annotationIndex + 1] = {
1109
1250
  ...nextAnnotation,
1110
- start: Math.min(nextAnnotation.end - minDuration, newStart)
1251
+ start: Math.min(nextAnnotation.end - minDuration, constrainedEnd)
1111
1252
  };
1112
1253
  let currentIndex = annotationIndex + 1;
1113
1254
  while (currentIndex < updatedAnnotations.length - 1) {
@@ -1179,6 +1320,417 @@ function resolveAnnotationShortcuts(remap) {
1179
1320
  return bindings.map((binding) => ({ action, binding }));
1180
1321
  });
1181
1322
  }
1323
+
1324
+ // src/panStage.ts
1325
+ var PREFIX = "[waveform-playlist] ";
1326
+ function panMatrix(pan, sourceChannelCount) {
1327
+ const p = Number.isFinite(pan) ? Math.max(-1, Math.min(1, pan)) : 0;
1328
+ if (sourceChannelCount < 2) {
1329
+ const theta = (p + 1) * Math.PI / 4;
1330
+ return { ll: Math.cos(theta), lr: 0, rl: 0, rr: Math.sin(theta) };
1331
+ }
1332
+ if (p <= 0) {
1333
+ const x2 = (p + 1) * Math.PI / 2;
1334
+ return { ll: 1, lr: 0, rl: Math.cos(x2), rr: Math.sin(x2) };
1335
+ }
1336
+ const x = p * Math.PI / 2;
1337
+ return { ll: Math.cos(x), lr: Math.sin(x), rl: 0, rr: 1 };
1338
+ }
1339
+ function createPanStage(context, pan, sourceChannelCount) {
1340
+ const upmix = context.createGain();
1341
+ upmix.channelCount = 2;
1342
+ upmix.channelCountMode = "explicit";
1343
+ upmix.channelInterpretation = "speakers";
1344
+ const split = context.createChannelSplitter(2);
1345
+ const merge = context.createChannelMerger(2);
1346
+ const ll = context.createGain();
1347
+ const lr = context.createGain();
1348
+ const rl = context.createGain();
1349
+ const rr = context.createGain();
1350
+ let currentPan = pan;
1351
+ let currentChannelCount = sourceChannelCount;
1352
+ const apply = () => {
1353
+ const matrix = panMatrix(currentPan, currentChannelCount);
1354
+ ll.gain.value = matrix.ll;
1355
+ lr.gain.value = matrix.lr;
1356
+ rl.gain.value = matrix.rl;
1357
+ rr.gain.value = matrix.rr;
1358
+ };
1359
+ apply();
1360
+ upmix.connect(split);
1361
+ split.connect(ll, 0, 0);
1362
+ split.connect(lr, 0, 0);
1363
+ split.connect(rl, 1, 0);
1364
+ split.connect(rr, 1, 0);
1365
+ ll.connect(merge, 0, 0);
1366
+ rl.connect(merge, 0, 0);
1367
+ lr.connect(merge, 0, 1);
1368
+ rr.connect(merge, 0, 1);
1369
+ return {
1370
+ input: upmix,
1371
+ output: merge,
1372
+ setPan: (value) => {
1373
+ currentPan = value;
1374
+ apply();
1375
+ },
1376
+ setSourceChannelCount: (value) => {
1377
+ currentChannelCount = value;
1378
+ apply();
1379
+ },
1380
+ dispose: () => {
1381
+ for (const node of [upmix, split, ll, lr, rl, rr, merge]) {
1382
+ try {
1383
+ node.disconnect();
1384
+ } catch (err) {
1385
+ console.warn(PREFIX + "pan stage: error disconnecting node: " + String(err));
1386
+ }
1387
+ }
1388
+ }
1389
+ };
1390
+ }
1391
+
1392
+ // src/valueSource.ts
1393
+ function silentMeterLevels(channelCount) {
1394
+ const count = Math.max(0, Math.floor(channelCount));
1395
+ return {
1396
+ levels: new Array(count).fill(0),
1397
+ peakLevels: new Array(count).fill(0),
1398
+ rmsLevels: new Array(count).fill(0)
1399
+ };
1400
+ }
1401
+ function createValueSource(initial) {
1402
+ let current = initial;
1403
+ const listeners = /* @__PURE__ */ new Map();
1404
+ const source = {
1405
+ subscribe(listener) {
1406
+ const token = /* @__PURE__ */ Symbol("subscription");
1407
+ listeners.set(token, listener);
1408
+ return () => {
1409
+ listeners.delete(token);
1410
+ };
1411
+ },
1412
+ getSnapshot() {
1413
+ return current;
1414
+ }
1415
+ };
1416
+ const publish = (value) => {
1417
+ if (Object.is(value, current)) return;
1418
+ current = value;
1419
+ for (const listener of [...listeners.values()]) {
1420
+ try {
1421
+ listener(value);
1422
+ } catch (err) {
1423
+ console.warn("[waveform-playlist] A value source listener threw: " + String(err));
1424
+ }
1425
+ }
1426
+ };
1427
+ return { source, publish };
1428
+ }
1429
+
1430
+ // src/sourceLoader.ts
1431
+ function toError(reason) {
1432
+ return reason instanceof Error ? reason : new Error(String(reason));
1433
+ }
1434
+ function createSourceLoader(options) {
1435
+ const { load } = options;
1436
+ const entries = /* @__PURE__ */ new Map();
1437
+ let suspended = false;
1438
+ const { source, publish } = createValueSource(/* @__PURE__ */ new Map());
1439
+ const publishEntries = () => {
1440
+ const next = /* @__PURE__ */ new Map();
1441
+ for (const [key, entry] of entries) next.set(key, entry.state);
1442
+ publish(next);
1443
+ };
1444
+ const abort = (entry) => {
1445
+ entry.controller?.abort();
1446
+ };
1447
+ const start = (key) => {
1448
+ const token = /* @__PURE__ */ Symbol("load");
1449
+ const controller = new AbortController();
1450
+ const entry = { state: { status: "pending" }, controller, token };
1451
+ entries.set(key, entry);
1452
+ const settle = (state) => {
1453
+ const current = entries.get(key);
1454
+ if (!current || current.token !== token) return;
1455
+ entries.set(key, { state, token });
1456
+ publishEntries();
1457
+ };
1458
+ let promise;
1459
+ try {
1460
+ promise = Promise.resolve(load(key, controller.signal));
1461
+ } catch (err) {
1462
+ entries.set(key, { state: { status: "failed", error: toError(err) }, token });
1463
+ return;
1464
+ }
1465
+ promise.then(
1466
+ (value) => settle({ status: "loaded", value }),
1467
+ (err) => {
1468
+ if (controller.signal.aborted) return;
1469
+ settle({ status: "failed", error: toError(err) });
1470
+ }
1471
+ );
1472
+ };
1473
+ return {
1474
+ setWanted(keys) {
1475
+ const wanted = new Set(keys);
1476
+ suspended = false;
1477
+ let changed = false;
1478
+ for (const [key, entry] of [...entries]) {
1479
+ if (wanted.has(key)) continue;
1480
+ abort(entry);
1481
+ entries.delete(key);
1482
+ changed = true;
1483
+ }
1484
+ for (const key of wanted) {
1485
+ const entry = entries.get(key);
1486
+ if (entry && (entry.state.status !== "pending" || entry.controller)) continue;
1487
+ start(key);
1488
+ if (!entry || entries.get(key)?.state.status !== "pending") changed = true;
1489
+ }
1490
+ if (changed) publishEntries();
1491
+ },
1492
+ suspend() {
1493
+ suspended = true;
1494
+ for (const [key, entry] of [...entries]) {
1495
+ if (entry.state.status !== "pending" || !entry.controller) continue;
1496
+ abort(entry);
1497
+ entries.set(key, { state: entry.state, token: /* @__PURE__ */ Symbol("suspended") });
1498
+ }
1499
+ },
1500
+ provide(key, value) {
1501
+ const entry = entries.get(key);
1502
+ if (entry?.state.status === "loaded") return;
1503
+ if (entry) abort(entry);
1504
+ entries.set(key, { state: { status: "loaded", value }, token: /* @__PURE__ */ Symbol("provided") });
1505
+ publishEntries();
1506
+ },
1507
+ retry(key) {
1508
+ if (entries.get(key)?.state.status !== "failed") return;
1509
+ if (suspended) {
1510
+ entries.set(key, { state: { status: "pending" }, token: /* @__PURE__ */ Symbol("suspended") });
1511
+ } else {
1512
+ start(key);
1513
+ }
1514
+ publishEntries();
1515
+ },
1516
+ subscribe: source.subscribe,
1517
+ getSnapshot: source.getSnapshot
1518
+ };
1519
+ }
1520
+
1521
+ // src/audioTrack.ts
1522
+ function generateId2() {
1523
+ return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;
1524
+ }
1525
+ function checkNonNegative(name, value) {
1526
+ if (value !== void 0 && !(Number.isFinite(value) && value >= 0)) {
1527
+ throw new Error(`audioTrack: ${name} must be a finite number of seconds, 0 or more`);
1528
+ }
1529
+ }
1530
+ function checkOptions(options) {
1531
+ checkNonNegative("start", options.start);
1532
+ checkNonNegative("offset", options.offset);
1533
+ const { duration } = options;
1534
+ if (duration !== void 0 && !(Number.isFinite(duration) && duration > 0)) {
1535
+ throw new Error("audioTrack: duration must be a positive finite number of seconds");
1536
+ }
1537
+ }
1538
+ function decodeName(name) {
1539
+ try {
1540
+ return decodeURIComponent(name);
1541
+ } catch {
1542
+ return name;
1543
+ }
1544
+ }
1545
+ function defaultName(src) {
1546
+ const raw = typeof src === "string" ? src : typeof File !== "undefined" && src instanceof File ? src.name : "";
1547
+ if (/^(data|blob):/i.test(raw)) return "Untitled";
1548
+ const path = raw.split(/[?#]/)[0];
1549
+ const file = path.slice(path.lastIndexOf("/") + 1);
1550
+ const dot = file.lastIndexOf(".");
1551
+ const base = dot > 0 ? file.slice(0, dot) : file;
1552
+ return decodeName(base) || "Untitled";
1553
+ }
1554
+ function fitToAudio(name, offset, duration, sampleRate, sourceSamples) {
1555
+ const offsetSamples = Math.round(offset * sampleRate);
1556
+ if (offsetSamples >= sourceSamples) {
1557
+ throw new Error("audioTrack: offset is past the end of the audio");
1558
+ }
1559
+ const remaining = sourceSamples - offsetSamples;
1560
+ if (duration === void 0) return remaining / sampleRate;
1561
+ const wanted = Math.round(duration * sampleRate);
1562
+ if (offsetSamples + wanted > sourceSamples + 1) {
1563
+ console.warn(
1564
+ `[waveform-playlist] audioTrack: offset + duration of "${name}" runs past the end of the audio; the clip is cut to the end.`
1565
+ );
1566
+ }
1567
+ return Math.min(wanted, remaining) / sampleRate;
1568
+ }
1569
+ function buildLoadingClip(id, src, name, options) {
1570
+ const given = {
1571
+ start: options.start,
1572
+ duration: options.duration,
1573
+ offset: options.offset,
1574
+ gain: options.gain,
1575
+ fadeIn: options.fadeIn,
1576
+ fadeOut: options.fadeOut,
1577
+ color: options.color,
1578
+ waveformData: options.waveformData
1579
+ };
1580
+ const present = Object.entries(given).filter(([, value]) => value !== void 0);
1581
+ return { id, src, name, ...Object.fromEntries(present) };
1582
+ }
1583
+ function buildClip(options, name) {
1584
+ const { audioBuffer, waveformData, start = 0, offset = 0, duration } = options;
1585
+ const src = options.src || void 0;
1586
+ const id = options.clipId || generateId2();
1587
+ if (src !== void 0 && !audioBuffer) return buildLoadingClip(id, src, name, options);
1588
+ if (!audioBuffer && !waveformData) {
1589
+ throw new Error("audioTrack: give src, audioBuffer or waveformData");
1590
+ }
1591
+ const sampleRate = audioBuffer?.sampleRate ?? waveformData?.sample_rate ?? 0;
1592
+ const sourceSamples = audioBuffer?.length ?? Math.ceil((waveformData?.duration ?? 0) * sampleRate);
1593
+ const clipSeconds = fitToAudio(name, offset, duration, sampleRate, sourceSamples);
1594
+ const clip = createClipFromSeconds({
1595
+ audioBuffer,
1596
+ waveformData,
1597
+ startTime: start,
1598
+ offset,
1599
+ duration: clipSeconds,
1600
+ name,
1601
+ gain: options.gain,
1602
+ fadeIn: options.fadeIn,
1603
+ fadeOut: options.fadeOut,
1604
+ color: options.color,
1605
+ src
1606
+ });
1607
+ return { ...clip, id };
1608
+ }
1609
+ function audioTrack(options) {
1610
+ checkOptions(options);
1611
+ const name = options.name ?? defaultName(options.src);
1612
+ const clip = buildClip(options, name);
1613
+ const base = createTrack({
1614
+ name,
1615
+ muted: options.muted,
1616
+ soloed: options.soloed,
1617
+ volume: options.volume,
1618
+ pan: options.pan,
1619
+ spectrogramConfig: options.spectrogramConfig,
1620
+ spectrogramColorMap: options.spectrogramColorMap,
1621
+ color: options.color
1622
+ });
1623
+ const track = {
1624
+ ...base,
1625
+ id: options.id || base.id,
1626
+ clips: [clip],
1627
+ renderMode: options.renderMode
1628
+ };
1629
+ return track;
1630
+ }
1631
+
1632
+ // src/effects/registry.ts
1633
+ var REGISTRY_KEY = /* @__PURE__ */ Symbol.for("@waveform-playlist/core/effect-registry/v1");
1634
+ function registryState() {
1635
+ const holder = globalThis;
1636
+ const existing = holder[REGISTRY_KEY];
1637
+ if (existing) return existing;
1638
+ const created = { definitions: /* @__PURE__ */ new Map(), prepared: /* @__PURE__ */ new WeakMap() };
1639
+ holder[REGISTRY_KEY] = created;
1640
+ return created;
1641
+ }
1642
+ var registry = registryState().definitions;
1643
+ var prepared = registryState().prepared;
1644
+ function registerEffect(type, definition) {
1645
+ if (registry.has(type)) {
1646
+ console.warn(
1647
+ '[waveform-playlist] registerEffect: overwriting existing effect type "' + type + '"'
1648
+ );
1649
+ }
1650
+ registry.set(type, definition);
1651
+ }
1652
+ function unregisterEffect(type) {
1653
+ return registry.delete(type);
1654
+ }
1655
+ function getEffectDefinitions() {
1656
+ return new Map(registry);
1657
+ }
1658
+ function prepareEffect(type, audioContext) {
1659
+ const definition = registry.get(type);
1660
+ if (!definition?.prepare) {
1661
+ return Promise.resolve();
1662
+ }
1663
+ const forContext = prepared.get(audioContext) ?? /* @__PURE__ */ new Map();
1664
+ prepared.set(audioContext, forContext);
1665
+ const existing = forContext.get(type);
1666
+ if (existing && existing.definition === definition) {
1667
+ return existing.promise;
1668
+ }
1669
+ const prepare = definition.prepare;
1670
+ const record = {
1671
+ definition,
1672
+ settled: false,
1673
+ // The async wrapper turns a synchronous throw into a rejection.
1674
+ promise: (async () => prepare(audioContext))().then(
1675
+ () => {
1676
+ record.settled = true;
1677
+ },
1678
+ (err) => {
1679
+ if (forContext.get(type) === record) {
1680
+ forContext.delete(type);
1681
+ }
1682
+ throw err;
1683
+ }
1684
+ )
1685
+ };
1686
+ forContext.set(type, record);
1687
+ return record.promise;
1688
+ }
1689
+ function isPrepared(type, definition, audioContext) {
1690
+ const record = prepared.get(audioContext)?.get(type);
1691
+ return record !== void 0 && record.definition === definition && record.settled;
1692
+ }
1693
+ function needsPrepare(type, audioContext) {
1694
+ const definition = registry.get(type);
1695
+ return definition?.prepare !== void 0 && !isPrepared(type, definition, audioContext);
1696
+ }
1697
+ async function ensureEffectPrepared(type, audioContext) {
1698
+ while (needsPrepare(type, audioContext)) {
1699
+ await prepareEffect(type, audioContext);
1700
+ }
1701
+ }
1702
+ function createEffectInstance(type, audioContext, params = {}) {
1703
+ const definition = registry.get(type);
1704
+ if (!definition) {
1705
+ throw new Error(
1706
+ '[waveform-playlist] createEffectInstance: unknown effect type "' + type + '". Available types: ' + [...registry.keys()].join(", ")
1707
+ );
1708
+ }
1709
+ const merged = { ...definition.defaults, ...params };
1710
+ let instance;
1711
+ try {
1712
+ instance = definition.create(audioContext, merged);
1713
+ } catch (err) {
1714
+ if (!definition.prepare || isPrepared(type, definition, audioContext)) {
1715
+ throw err;
1716
+ }
1717
+ const hinted = new Error(
1718
+ '[waveform-playlist] effect "' + type + `" has a prepare() step that has not completed on this audio context \u2014 await prepareEffect('` + type + "', audioContext) before creating it (on <daw-editor>: await editor.prepareEffect('" + type + "') before addEffect). Original error: " + (err instanceof Error ? err.message : String(err))
1719
+ );
1720
+ hinted.cause = err;
1721
+ throw hinted;
1722
+ }
1723
+ try {
1724
+ instance.applyParams(merged);
1725
+ } catch (err) {
1726
+ try {
1727
+ instance.dispose?.();
1728
+ } catch {
1729
+ }
1730
+ throw err;
1731
+ }
1732
+ return { instance, params: merged, wetParam: definition.wetParam };
1733
+ }
1182
1734
  // Annotate the CommonJS export names for ESM import in node:
1183
1735
  0 && (module.exports = {
1184
1736
  ANNOTATION_LINK_THRESHOLD_TICKS,
@@ -1187,6 +1739,7 @@ function resolveAnnotationShortcuts(remap) {
1187
1739
  InteractionState,
1188
1740
  LINK_THRESHOLD,
1189
1741
  MAX_CANVAS_WIDTH,
1742
+ METER_PEAK_DECAY,
1190
1743
  MIN_ANNOTATION_DURATION,
1191
1744
  MIN_PIXELS_PER_UNIT,
1192
1745
  PPQN,
@@ -1196,12 +1749,15 @@ function resolveAnnotationShortcuts(remap) {
1196
1749
  appendToAudioBuffer,
1197
1750
  applyFadeIn,
1198
1751
  applyFadeOut,
1752
+ assertTrackKind,
1199
1753
  audibleLatencySamples,
1754
+ audioTrack,
1200
1755
  buildSpectrogramCanvasId,
1201
1756
  calculateDuration,
1202
1757
  carveClipRange,
1203
1758
  clipDurationTime,
1204
1759
  clipEndTime,
1760
+ clipKind,
1205
1761
  clipOffsetTime,
1206
1762
  clipPixelWidth,
1207
1763
  clipStartTime,
@@ -1212,10 +1768,15 @@ function resolveAnnotationShortcuts(remap) {
1212
1768
  createClip,
1213
1769
  createClipFromSeconds,
1214
1770
  createClipFromTicks,
1771
+ createEffectInstance,
1772
+ createPanStage,
1773
+ createSourceLoader,
1215
1774
  createTimeline,
1216
1775
  createTrack,
1776
+ createValueSource,
1217
1777
  dBToNormalized,
1218
1778
  detectMeterChanges,
1779
+ ensureEffectPrepared,
1219
1780
  enumerateMicrophones,
1220
1781
  exponentialCurve,
1221
1782
  findGaps,
@@ -1225,16 +1786,23 @@ function resolveAnnotationShortcuts(remap) {
1225
1786
  generatePeaks,
1226
1787
  getClipsAtSample,
1227
1788
  getClipsInRange,
1228
- getShortcutLabel,
1789
+ getEffectDefinitions,
1229
1790
  handleKeyboardEvent,
1791
+ isLoadingClip,
1792
+ keyBelongsToFocusedControl,
1230
1793
  linearCurve,
1231
1794
  logarithmicCurve,
1232
1795
  matchesKeyBinding,
1796
+ needsPrepare,
1233
1797
  normalizedToDb,
1798
+ panMatrix,
1234
1799
  parseSpectrogramCanvasId,
1235
1800
  pixelsToSamples,
1236
1801
  pixelsToSeconds,
1802
+ prepareEffect,
1237
1803
  probeRangeSupport,
1804
+ readMeterMessage,
1805
+ registerEffect,
1238
1806
  resolveAnnotationShortcuts,
1239
1807
  resolveRecordingOffsetSamples,
1240
1808
  sCurveCurve,
@@ -1243,15 +1811,19 @@ function resolveAnnotationShortcuts(remap) {
1243
1811
  samplesToTicks,
1244
1812
  secondsToPixels,
1245
1813
  secondsToSamples,
1814
+ silentMeterLevels,
1246
1815
  snapTickToGrid,
1247
1816
  snapToGrid,
1248
1817
  snapToTicks,
1249
1818
  sortClipsByTime,
1819
+ splitTrackByKind,
1250
1820
  ticksPerBar,
1251
1821
  ticksPerBeat,
1252
1822
  ticksToBarBeat,
1253
1823
  ticksToSamples,
1254
1824
  trackChannelCount,
1825
+ trackKind,
1826
+ unregisterEffect,
1255
1827
  updateAnnotationBoundaries,
1256
1828
  watchMicrophoneDevices
1257
1829
  });