@waveform-playlist/spectrogram 15.0.0-next.1 → 15.0.0-next.10

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
@@ -30,9 +30,9 @@ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: tru
30
30
  // src/index.ts
31
31
  var src_exports = {};
32
32
  __export(src_exports, {
33
- SpectrogramMenuItems: () => SpectrogramMenuItems,
34
33
  SpectrogramProvider: () => SpectrogramProvider,
35
- SpectrogramSettingsModal: () => SpectrogramSettingsModal
34
+ SpectrogramSettingsModal: () => SpectrogramSettingsModal,
35
+ spectrogramMenuItems: () => spectrogramMenuItems
36
36
  });
37
37
  module.exports = __toCommonJS(src_exports);
38
38
 
@@ -81,7 +81,7 @@ var RENDER_MODES = [
81
81
  { value: "spectrogram", label: "Spectrogram" },
82
82
  { value: "both", label: "Both" }
83
83
  ];
84
- function SpectrogramMenuItems({
84
+ function spectrogramMenuItems({
85
85
  renderMode,
86
86
  onRenderModeChange,
87
87
  onOpenSettings,
@@ -90,7 +90,6 @@ function SpectrogramMenuItems({
90
90
  return [
91
91
  {
92
92
  id: "spectrogram-display",
93
- label: "Display",
94
93
  content: /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(DropdownSection, { children: [
95
94
  /* @__PURE__ */ (0, import_jsx_runtime.jsx)(SectionLabel, { children: "Display" }),
96
95
  RENDER_MODES.map(({ value, label }) => /* @__PURE__ */ (0, import_jsx_runtime.jsxs)(RadioLabel, { children: [
@@ -131,6 +130,7 @@ function SpectrogramMenuItems({
131
130
  // src/components/SpectrogramSettingsModal.tsx
132
131
  var import_react = require("react");
133
132
  var import_styled_components2 = __toESM(require("styled-components"));
133
+ var import_core = require("@waveform-playlist/core");
134
134
  var import_jsx_runtime2 = require("react/jsx-runtime");
135
135
  var StyledDialog = import_styled_components2.default.dialog`
136
136
  border: 1px solid rgba(128, 128, 128, 0.4);
@@ -205,11 +205,12 @@ var ModalButton = import_styled_components2.default.button`
205
205
  border-radius: 4px;
206
206
  cursor: pointer;
207
207
  font-size: 0.85rem;
208
- background: ${(p) => p.$primary ? "var(--ifm-color-primary, #4a9)" : "transparent"};
209
- color: ${(p) => p.$primary ? "#fff" : "inherit"};
208
+ background: ${(p) => p.$primary ? p.theme.buttonBackground ?? "#0091ff" : "transparent"};
209
+ color: ${(p) => p.$primary ? p.theme.buttonText ?? "#fff" : "inherit"};
210
+ ${(p) => p.$primary && p.theme.buttonBorder ? `border-color: ${p.theme.buttonBorder};` : ""}
210
211
 
211
212
  &:hover {
212
- opacity: 0.85;
213
+ ${(p) => p.$primary && p.theme.buttonHoverBackground ? `background: ${p.theme.buttonHoverBackground};` : "opacity: 0.85;"}
213
214
  }
214
215
  `;
215
216
  var FFT_SIZES = [256, 512, 1024, 2048, 4096, 8192];
@@ -223,39 +224,40 @@ var WINDOW_FUNCTIONS = [
223
224
  ];
224
225
  var FREQ_SCALES = ["linear", "logarithmic", "mel", "bark", "erb"];
225
226
  var COLOR_MAPS = ["viridis", "magma", "inferno", "grayscale", "igray", "roseus"];
226
- var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
227
+ var CUSTOM_COLOR_MAP = "custom";
228
+ var SettingsForm = ({
229
+ onClose,
230
+ config,
231
+ colorMap,
232
+ onApply,
233
+ sampleRate
234
+ }) => {
227
235
  const id = (0, import_react.useId)();
228
- const [fftSize, setFftSize] = (0, import_react.useState)(config.fftSize ?? 2048);
229
- const [windowFn, setWindowFn] = (0, import_react.useState)(config.windowFunction ?? "hann");
230
- const [freqScale, setFreqScale] = (0, import_react.useState)(config.frequencyScale ?? "mel");
231
- const [localColorMap, setLocalColorMap] = (0, import_react.useState)(
232
- typeof colorMap === "string" ? colorMap : "viridis"
233
- );
234
- const [minFreq, setMinFreq] = (0, import_react.useState)(config.minFrequency ?? 0);
235
- const [maxFreq, setMaxFreq] = (0, import_react.useState)(config.maxFrequency ?? 2e4);
236
- const [gainDb, setGainDb] = (0, import_react.useState)(config.gainDb ?? 20);
237
- const [rangeDb, setRangeDb] = (0, import_react.useState)(config.rangeDb ?? 80);
238
- const [zeroPadding, setZeroPadding] = (0, import_react.useState)(config.zeroPaddingFactor ?? 2);
239
- const [hopSize, setHopSize] = (0, import_react.useState)(
240
- config.hopSize ?? Math.floor((config.fftSize ?? 2048) / 4)
241
- );
242
- const [showLabels, setShowLabels] = (0, import_react.useState)(config.labels ?? false);
236
+ const [edits, setEdits] = (0, import_react.useState)({});
237
+ const [editedColorMap, setEditedColorMap] = (0, import_react.useState)(void 0);
238
+ const shown = (key) => key in edits ? edits[key] : config[key];
239
+ const edit = (changes) => setEdits((prev) => ({ ...prev, ...changes }));
240
+ const fftSize = shown("fftSize") ?? import_core.SPECTROGRAM_DEFAULTS.fftSize;
241
+ const hopSize = shown("hopSize") ?? Math.floor(fftSize / 4);
242
+ const zeroPadding = shown("zeroPaddingFactor") ?? import_core.SPECTROGRAM_DEFAULTS.zeroPaddingFactor;
243
+ const windowFn = shown("windowFunction") ?? import_core.SPECTROGRAM_DEFAULTS.windowFunction;
244
+ const freqScale = shown("frequencyScale") ?? import_core.SPECTROGRAM_DEFAULTS.frequencyScale;
245
+ const minFreq = shown("minFrequency") ?? import_core.SPECTROGRAM_DEFAULTS.minFrequency;
246
+ const nyquist = sampleRate !== void 0 ? sampleRate / 2 : void 0;
247
+ const maxFreq = "maxFrequency" in edits ? edits.maxFrequency : config.maxFrequency ?? nyquist;
248
+ const gainDb = shown("gainDb") ?? import_core.SPECTROGRAM_DEFAULTS.gainDb;
249
+ const rangeDb = shown("rangeDb") ?? import_core.SPECTROGRAM_DEFAULTS.rangeDb;
250
+ const showLabels = shown("labels") ?? import_core.SPECTROGRAM_DEFAULTS.labels;
251
+ const isCustomColorMap = typeof colorMap !== "string";
252
+ const colorMapValue = editedColorMap ?? (isCustomColorMap ? CUSTOM_COLOR_MAP : colorMap);
243
253
  const handleApply = () => {
244
- onApply(
245
- {
246
- fftSize,
247
- windowFunction: windowFn,
248
- frequencyScale: freqScale,
249
- minFrequency: minFreq,
250
- maxFrequency: maxFreq,
251
- gainDb,
252
- rangeDb,
253
- zeroPaddingFactor: zeroPadding,
254
- hopSize,
255
- labels: showLabels
256
- },
257
- localColorMap
254
+ const configChanged = Object.keys(edits).some(
255
+ (key) => edits[key] !== config[key]
258
256
  );
257
+ const colorMapChanged = editedColorMap !== void 0 && editedColorMap !== colorMap;
258
+ if (configChanged || colorMapChanged) {
259
+ onApply({ ...config, ...edits }, editedColorMap ?? colorMap);
260
+ }
259
261
  onClose();
260
262
  };
261
263
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(import_jsx_runtime2.Fragment, { children: [
@@ -269,8 +271,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
269
271
  value: fftSize,
270
272
  onChange: (e) => {
271
273
  const v = Number(e.target.value);
272
- setFftSize(v);
273
- setHopSize(Math.floor(v / 4));
274
+ edit({ fftSize: v, hopSize: Math.floor(v / 4) });
274
275
  },
275
276
  children: FFT_SIZES.map((s) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: s, children: s }, s))
276
277
  }
@@ -283,7 +284,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
283
284
  {
284
285
  id: `${id}-hop-size`,
285
286
  value: hopSize,
286
- onChange: (e) => setHopSize(Number(e.target.value)),
287
+ onChange: (e) => edit({ hopSize: Number(e.target.value) }),
287
288
  children: [
288
289
  { label: `${fftSize} (no overlap)`, value: fftSize },
289
290
  { label: `${Math.floor(fftSize / 2)} (50%)`, value: Math.floor(fftSize / 2) },
@@ -300,7 +301,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
300
301
  {
301
302
  id: `${id}-zero-padding`,
302
303
  value: zeroPadding,
303
- onChange: (e) => setZeroPadding(Number(e.target.value)),
304
+ onChange: (e) => edit({ zeroPaddingFactor: Number(e.target.value) }),
304
305
  children: [1, 2, 4, 8, 16].map((v) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: v, children: v }, v))
305
306
  }
306
307
  )
@@ -312,7 +313,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
312
313
  {
313
314
  id: `${id}-window-function`,
314
315
  value: windowFn,
315
- onChange: (e) => setWindowFn(e.target.value),
316
+ onChange: (e) => edit({ windowFunction: e.target.value }),
316
317
  children: WINDOW_FUNCTIONS.map((w) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: w, children: w }, w))
317
318
  }
318
319
  )
@@ -324,20 +325,28 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
324
325
  {
325
326
  id: `${id}-frequency-scale`,
326
327
  value: freqScale,
327
- onChange: (e) => setFreqScale(e.target.value),
328
+ onChange: (e) => edit({ frequencyScale: e.target.value }),
328
329
  children: FREQ_SCALES.map((s) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: s, children: s }, s))
329
330
  }
330
331
  )
331
332
  ] }),
332
333
  /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(Field, { children: [
333
334
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Label, { htmlFor: `${id}-color-map`, children: "Color Map" }),
334
- /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
335
+ /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(
335
336
  Select,
336
337
  {
337
338
  id: `${id}-color-map`,
338
- value: localColorMap,
339
- onChange: (e) => setLocalColorMap(e.target.value),
340
- children: COLOR_MAPS.map((c) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: c, children: c }, c))
339
+ value: colorMapValue,
340
+ onChange: (e) => (
341
+ // "custom" is the colour map given (an array): no edit.
342
+ setEditedColorMap(
343
+ e.target.value === CUSTOM_COLOR_MAP ? void 0 : e.target.value
344
+ )
345
+ ),
346
+ children: [
347
+ isCustomColorMap && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: CUSTOM_COLOR_MAP, children: CUSTOM_COLOR_MAP }),
348
+ COLOR_MAPS.map((c) => /* @__PURE__ */ (0, import_jsx_runtime2.jsx)("option", { value: c, children: c }, c))
349
+ ]
341
350
  }
342
351
  )
343
352
  ] }),
@@ -352,7 +361,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
352
361
  max: 5e3,
353
362
  step: 50,
354
363
  value: minFreq,
355
- onChange: (e) => setMinFreq(Number(e.target.value))
364
+ onChange: (e) => edit({ minFrequency: Number(e.target.value) })
356
365
  }
357
366
  )
358
367
  ] }),
@@ -364,10 +373,13 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
364
373
  id: `${id}-max-frequency`,
365
374
  type: "number",
366
375
  min: 1e3,
367
- max: 22050,
376
+ max: nyquist,
368
377
  step: 50,
369
- value: maxFreq,
370
- onChange: (e) => setMaxFreq(Number(e.target.value))
378
+ value: maxFreq ?? "",
379
+ onChange: (e) => (
380
+ // Emptied: back to the default, half the sample rate.
381
+ edit({ maxFrequency: e.target.value === "" ? void 0 : Number(e.target.value) })
382
+ )
371
383
  }
372
384
  )
373
385
  ] }),
@@ -382,7 +394,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
382
394
  max: 120,
383
395
  step: 1,
384
396
  value: rangeDb,
385
- onChange: (e) => setRangeDb(Number(e.target.value))
397
+ onChange: (e) => edit({ rangeDb: Number(e.target.value) })
386
398
  }
387
399
  )
388
400
  ] }),
@@ -397,7 +409,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
397
409
  max: 60,
398
410
  step: 1,
399
411
  value: gainDb,
400
- onChange: (e) => setGainDb(Number(e.target.value))
412
+ onChange: (e) => edit({ gainDb: Number(e.target.value) })
401
413
  }
402
414
  )
403
415
  ] }),
@@ -407,7 +419,7 @@ var SettingsForm = ({ onClose, config, colorMap, onApply }) => {
407
419
  {
408
420
  type: "checkbox",
409
421
  checked: showLabels,
410
- onChange: (e) => setShowLabels(e.target.checked)
422
+ onChange: (e) => edit({ labels: e.target.checked })
411
423
  }
412
424
  ),
413
425
  "Show Frequency Labels"
@@ -424,7 +436,8 @@ var SpectrogramSettingsModal = ({
424
436
  onClose,
425
437
  config,
426
438
  colorMap,
427
- onApply
439
+ onApply,
440
+ sampleRate
428
441
  }) => {
429
442
  const dialogRef = (0, import_react.useRef)(null);
430
443
  const titleId = (0, import_react.useId)();
@@ -454,20 +467,29 @@ var SpectrogramSettingsModal = ({
454
467
  }, [open]);
455
468
  return /* @__PURE__ */ (0, import_jsx_runtime2.jsxs)(StyledDialog, { ref: dialogRef, "aria-labelledby": titleId, children: [
456
469
  /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(Title, { id: titleId, children: "Spectrogram Settings" }),
457
- open && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(SettingsForm, { onClose, config, colorMap, onApply })
470
+ open && /* @__PURE__ */ (0, import_jsx_runtime2.jsx)(
471
+ SettingsForm,
472
+ {
473
+ onClose,
474
+ config,
475
+ colorMap,
476
+ onApply,
477
+ sampleRate
478
+ }
479
+ )
458
480
  ] });
459
481
  };
460
482
 
461
483
  // src/SpectrogramProvider.tsx
462
- var import_react2 = require("react");
463
- var import_core2 = require("@waveform-playlist/core");
484
+ var import_react3 = require("react");
485
+ var import_core3 = require("@waveform-playlist/core");
464
486
  var import_spectrogram2 = require("@dawcore/spectrogram");
465
487
 
466
488
  // src/spectrogram-helpers.ts
467
- var import_core = require("@waveform-playlist/core");
489
+ var import_core2 = require("@waveform-playlist/core");
468
490
  var import_spectrogram = require("@dawcore/spectrogram");
469
491
  function extractChunkNumber(canvasId) {
470
- const parsed = (0, import_core.parseSpectrogramCanvasId)(canvasId);
492
+ const parsed = (0, import_core2.parseSpectrogramCanvasId)(canvasId);
471
493
  if (!parsed) {
472
494
  console.warn(`[spectrogram] Unexpected canvas ID format: ${canvasId}`);
473
495
  return 0;
@@ -478,7 +500,7 @@ function presentChunkIndices(channelInfo, indices) {
478
500
  return indices.filter((i) => channelInfo.canvasIds[i] !== void 0);
479
501
  }
480
502
  function parseCanvasId(canvasId) {
481
- const parsed = (0, import_core.parseSpectrogramCanvasId)(canvasId);
503
+ const parsed = (0, import_core2.parseSpectrogramCanvasId)(canvasId);
482
504
  return parsed ? { clipId: parsed.clipId, channelIndex: parsed.channelIndex } : null;
483
505
  }
484
506
  function groupContiguousIndices(channelInfo, indices) {
@@ -516,7 +538,7 @@ function classifyChunkTiers(channelInfo, clipPixelOffset = 0, viewport) {
516
538
  const remainingIndices = [];
517
539
  for (let i = 0; i < channelInfo.canvasWidths.length; i++) {
518
540
  const chunkNumber = extractChunkNumber(channelInfo.canvasIds[i]);
519
- const chunkLeft = chunkNumber * import_core.MAX_CANVAS_WIDTH + clipPixelOffset;
541
+ const chunkLeft = chunkNumber * import_core2.MAX_CANVAS_WIDTH + clipPixelOffset;
520
542
  const chunkRight = chunkLeft + channelInfo.canvasWidths[i];
521
543
  if (chunkRight > scrollLeft && chunkLeft < scrollLeft + viewportWidth) {
522
544
  viewportIndices.push(i);
@@ -547,26 +569,13 @@ function computeChunkSampleRange({
547
569
  samplesPerPixel
548
570
  });
549
571
  }
550
- function resolveRenderMode(override, trackRenderMode) {
551
- return override?.renderMode ?? trackRenderMode ?? "waveform";
552
- }
553
- function toComputeConfig(cfg) {
554
- return {
555
- fftSize: cfg?.fftSize,
556
- hopSize: cfg?.hopSize,
557
- windowFunction: cfg?.windowFunction,
558
- alpha: cfg?.alpha,
559
- zeroPaddingFactor: cfg?.zeroPaddingFactor
560
- };
572
+ function resolveRenderMode(trackRenderMode) {
573
+ return trackRenderMode ?? "waveform";
561
574
  }
562
575
  function buildConfigKey(params) {
563
576
  const { mode, cfg, cm, mono } = params;
564
577
  return JSON.stringify({ mode, cfg, cm, mono });
565
578
  }
566
- function buildFFTKey(params) {
567
- const { mode, mono, computeConfig } = params;
568
- return JSON.stringify({ mode, mono, ...computeConfig });
569
- }
570
579
  function mapsDiffer(prev, current) {
571
580
  if (current.size !== prev.size) return true;
572
581
  for (const [key, value] of current) {
@@ -591,144 +600,138 @@ function resolveClipRange(clip, registered) {
591
600
  };
592
601
  }
593
602
 
603
+ // src/audioRegistration.ts
604
+ function createAudioKeyOf() {
605
+ const keys = /* @__PURE__ */ new WeakMap();
606
+ let next = 0;
607
+ return (buffer) => {
608
+ const existing = keys.get(buffer);
609
+ if (existing !== void 0) return existing;
610
+ next += 1;
611
+ const key = `audio-${next}`;
612
+ keys.set(buffer, key);
613
+ return key;
614
+ };
615
+ }
616
+ function spectrogramAudio(tracks, audioKeyOf) {
617
+ const wanted = /* @__PURE__ */ new Map();
618
+ for (const track of tracks) {
619
+ if (resolveRenderMode(track.renderMode) === "waveform") continue;
620
+ for (const clip of track.clips) {
621
+ if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);
622
+ }
623
+ }
624
+ return wanted;
625
+ }
626
+ function channelData(buffer) {
627
+ return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));
628
+ }
629
+
630
+ // src/useStableByContent.ts
631
+ var import_react2 = require("react");
632
+ function useStableByContent(value) {
633
+ const content = JSON.stringify(value);
634
+ return (0, import_react2.useMemo)(() => value, [content]);
635
+ }
636
+
594
637
  // src/SpectrogramProvider.tsx
595
638
  var import_browser = require("@waveform-playlist/browser");
596
639
  var import_browser2 = require("@waveform-playlist/browser");
597
640
  var import_jsx_runtime3 = require("react/jsx-runtime");
598
641
  var import_meta = {};
599
642
  var SpectrogramProvider = ({
600
- config: spectrogramConfig,
601
- colorMap: spectrogramColorMap,
643
+ config,
644
+ colorMap,
602
645
  workerPoolSize,
603
646
  children
604
647
  }) => {
648
+ const spectrogramConfig = useStableByContent(config);
649
+ const spectrogramColorMap = useStableByContent(colorMap);
605
650
  const { mono } = (0, import_browser2.usePlaylistView)();
606
651
  const { samplesPerPixel } = (0, import_browser2.usePlaylistZoom)();
607
- const { tracks, isReady } = (0, import_browser2.usePlaylistTimeline)();
652
+ const { tracks } = (0, import_browser2.usePlaylistTimeline)();
608
653
  const { scrollContainerRef } = (0, import_browser2.usePlaybackControls)();
609
- const [trackSpectrogramOverrides, setTrackSpectrogramOverrides] = (0, import_react2.useState)(() => /* @__PURE__ */ new Map());
610
- const spectrogramCanvasRegistryRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
611
- const canvasHeightsRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
612
- const canvasRangesRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
613
- const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = (0, import_react2.useState)(0);
614
- const prevSpectrogramConfigRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
615
- const prevSpectrogramFFTKeyRef = (0, import_react2.useRef)(/* @__PURE__ */ new Map());
616
- const spectrogramWorkerRef = (0, import_react2.useRef)(null);
617
- const spectrogramGenerationRef = (0, import_react2.useRef)(0);
618
- const prevCanvasVersionRef = (0, import_react2.useRef)(0);
619
- const renderedClipIdsRef = (0, import_react2.useRef)(/* @__PURE__ */ new Set());
620
- const backgroundRenderAbortRef = (0, import_react2.useRef)(null);
621
- const registeredAudioClipIdsRef = (0, import_react2.useRef)(/* @__PURE__ */ new Set());
622
- (0, import_react2.useEffect)(() => {
654
+ const arrangement = (0, import_browser2.useArrangement)();
655
+ const spectrogramCanvasRegistryRef = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
656
+ const canvasHeightsRef = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
657
+ const canvasRangesRef = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
658
+ const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = (0, import_react3.useState)(0);
659
+ const prevSpectrogramConfigRef = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
660
+ const spectrogramWorkerRef = (0, import_react3.useRef)(null);
661
+ const spectrogramGenerationRef = (0, import_react3.useRef)(0);
662
+ const prevCanvasVersionRef = (0, import_react3.useRef)(0);
663
+ const backgroundRenderAbortRef = (0, import_react3.useRef)(null);
664
+ const [audioKeyOf] = (0, import_react3.useState)(createAudioKeyOf);
665
+ const ensureWorkerPool = (0, import_react3.useCallback)(() => {
666
+ if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;
667
+ try {
668
+ const pool = (0, import_spectrogram2.createSpectrogramWorkerPool)(
669
+ () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import_meta.url), {
670
+ type: "module"
671
+ }),
672
+ workerPoolSize
673
+ );
674
+ spectrogramWorkerRef.current = pool;
675
+ return pool;
676
+ } catch (err) {
677
+ console.warn(
678
+ `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`
679
+ );
680
+ return null;
681
+ }
682
+ }, [workerPoolSize]);
683
+ (0, import_react3.useEffect)(() => {
623
684
  return () => {
624
685
  spectrogramWorkerRef.current?.terminate();
625
686
  spectrogramWorkerRef.current = null;
626
687
  };
627
688
  }, []);
628
- (0, import_react2.useEffect)(() => {
629
- if (!isReady || tracks.length === 0) return;
630
- let workerApi = spectrogramWorkerRef.current;
631
- if (!workerApi) {
632
- try {
633
- workerApi = (0, import_spectrogram2.createSpectrogramWorkerPool)(
634
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import_meta.url), {
635
- type: "module"
636
- }),
637
- workerPoolSize
638
- );
639
- spectrogramWorkerRef.current = workerApi;
640
- } catch (err) {
641
- console.warn(
642
- `[waveform-playlist] Spectrogram Web Worker unavailable for pre-transfer: ${err instanceof Error ? err.message : String(err)}`
643
- );
644
- return;
645
- }
689
+ (0, import_react3.useEffect)(() => {
690
+ const wanted = spectrogramAudio(tracks, audioKeyOf);
691
+ const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;
692
+ if (!pool) return;
693
+ const held = new Set(pool.registeredAudioClipIds());
694
+ for (const [key, buffer] of wanted) {
695
+ if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);
646
696
  }
647
- const currentClipIds = /* @__PURE__ */ new Set();
648
- for (const track of tracks) {
649
- for (const clip of track.clips) {
650
- if (!clip.audioBuffer) continue;
651
- currentClipIds.add(clip.id);
652
- if (!registeredAudioClipIdsRef.current.has(clip.id)) {
653
- const channelDataArrays = [];
654
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
655
- channelDataArrays.push(clip.audioBuffer.getChannelData(ch));
656
- }
657
- workerApi.registerAudioData(clip.id, channelDataArrays, clip.audioBuffer.sampleRate);
658
- registeredAudioClipIdsRef.current.add(clip.id);
659
- }
660
- }
697
+ for (const key of held) {
698
+ if (!wanted.has(key)) pool.unregisterAudioData(key);
661
699
  }
662
- for (const clipId of registeredAudioClipIdsRef.current) {
663
- if (!currentClipIds.has(clipId)) {
664
- workerApi.unregisterAudioData(clipId);
665
- registeredAudioClipIdsRef.current.delete(clipId);
666
- }
667
- }
668
- }, [isReady, tracks]);
669
- (0, import_react2.useEffect)(() => {
700
+ }, [tracks, audioKeyOf, ensureWorkerPool]);
701
+ (0, import_react3.useEffect)(() => {
670
702
  if (tracks.length === 0) return;
671
703
  const currentKeys = /* @__PURE__ */ new Map();
672
- const currentFFTKeys = /* @__PURE__ */ new Map();
673
704
  tracks.forEach((track) => {
674
- const override = trackSpectrogramOverrides.get(track.id);
675
- const mode = resolveRenderMode(override, track.renderMode);
705
+ const mode = resolveRenderMode(track.renderMode);
676
706
  if (mode === "waveform") return;
677
- const cfg = override?.config ?? track.spectrogramConfig ?? spectrogramConfig;
678
- const cm = override?.colorMap ?? track.spectrogramColorMap ?? spectrogramColorMap;
707
+ const cfg = track.spectrogramConfig ?? spectrogramConfig;
708
+ const cm = track.spectrogramColorMap ?? spectrogramColorMap;
679
709
  currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));
680
- currentFFTKeys.set(
681
- track.id,
682
- buildFFTKey({ mode, mono, computeConfig: toComputeConfig(cfg) })
683
- );
684
710
  });
685
711
  const prevKeys = prevSpectrogramConfigRef.current;
686
- const prevFFTKeys = prevSpectrogramFFTKeyRef.current;
687
712
  const configChanged = mapsDiffer(prevKeys, currentKeys);
688
- const fftKeyChanged = mapsDiffer(prevFFTKeys, currentFFTKeys);
689
713
  const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;
690
714
  prevCanvasVersionRef.current = spectrogramCanvasVersion;
691
715
  if (!configChanged && !canvasVersionChanged) return;
692
716
  if (configChanged) {
693
717
  prevSpectrogramConfigRef.current = currentKeys;
694
- prevSpectrogramFFTKeyRef.current = currentFFTKeys;
695
718
  }
696
719
  if (backgroundRenderAbortRef.current) {
697
720
  backgroundRenderAbortRef.current.aborted = true;
698
721
  }
699
722
  const generation = ++spectrogramGenerationRef.current;
700
- if (spectrogramWorkerRef.current) {
701
- spectrogramWorkerRef.current.abortGeneration(generation);
702
- }
703
- let workerApi = spectrogramWorkerRef.current;
704
- if (!workerApi) {
705
- try {
706
- workerApi = (0, import_spectrogram2.createSpectrogramWorkerPool)(
707
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import_meta.url), {
708
- type: "module"
709
- }),
710
- workerPoolSize
711
- );
712
- spectrogramWorkerRef.current = workerApi;
713
- } catch (err) {
714
- console.error(
715
- `[waveform-playlist] Spectrogram Web Worker required but unavailable: ${err instanceof Error ? err.message : String(err)}`
716
- );
717
- return;
718
- }
719
- }
720
- const clipsNeedingFFT = [];
721
- const clipsNeedingDisplayOnly = [];
722
- tracks.forEach((track, i) => {
723
- const override = trackSpectrogramOverrides.get(track.id);
724
- const mode = resolveRenderMode(override, track.renderMode);
723
+ const workerApi = ensureWorkerPool();
724
+ if (!workerApi) return;
725
+ workerApi.abortGeneration(generation);
726
+ const clipsToRender = [];
727
+ tracks.forEach((track) => {
728
+ const mode = resolveRenderMode(track.renderMode);
725
729
  if (mode === "waveform") return;
726
730
  const trackConfigChanged = configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);
727
- const trackFFTChanged = fftKeyChanged && currentFFTKeys.get(track.id) !== prevFFTKeys.get(track.id);
728
731
  const hasRegisteredCanvases = canvasVersionChanged && track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));
729
732
  if (!trackConfigChanged && !hasRegisteredCanvases) return;
730
- const cfg = override?.config ?? track.spectrogramConfig ?? spectrogramConfig ?? {};
731
- const cm = override?.colorMap ?? track.spectrogramColorMap ?? spectrogramColorMap ?? "viridis";
733
+ const cfg = track.spectrogramConfig ?? spectrogramConfig ?? {};
734
+ const cm = track.spectrogramColorMap ?? spectrogramColorMap ?? "viridis";
732
735
  for (const clip of track.clips) {
733
736
  if (!clip.audioBuffer) continue;
734
737
  const monoFlag = mono || clip.audioBuffer.numberOfChannels === 1;
@@ -739,34 +742,10 @@ var SpectrogramProvider = ({
739
742
  canvasRangesRef.current
740
743
  )
741
744
  );
742
- if (!trackFFTChanged && !hasRegisteredCanvases && renderedClipIdsRef.current.has(clip.id)) {
743
- const channelDataArrays2 = [];
744
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
745
- channelDataArrays2.push(clip.audioBuffer.getChannelData(ch));
746
- }
747
- clipsNeedingDisplayOnly.push({
748
- clipId: clip.id,
749
- trackIndex: i,
750
- channelDataArrays: channelDataArrays2,
751
- config: cfg,
752
- sampleRate: clip.audioBuffer.sampleRate,
753
- offsetSamples,
754
- durationSamples,
755
- clipStartSample: clip.startSample,
756
- monoFlag,
757
- colorMap: cm,
758
- numChannels: monoFlag ? 1 : clip.audioBuffer.numberOfChannels
759
- });
760
- continue;
761
- }
762
- const channelDataArrays = [];
763
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
764
- channelDataArrays.push(clip.audioBuffer.getChannelData(ch));
765
- }
766
- clipsNeedingFFT.push({
745
+ clipsToRender.push({
767
746
  clipId: clip.id,
768
- trackIndex: i,
769
- channelDataArrays,
747
+ audioKey: audioKeyOf(clip.audioBuffer),
748
+ channelDataArrays: channelData(clip.audioBuffer),
770
749
  config: cfg,
771
750
  sampleRate: clip.audioBuffer.sampleRate,
772
751
  offsetSamples,
@@ -777,7 +756,7 @@ var SpectrogramProvider = ({
777
756
  });
778
757
  }
779
758
  });
780
- if (clipsNeedingFFT.length === 0 && clipsNeedingDisplayOnly.length === 0) return;
759
+ if (clipsToRender.length === 0) return;
781
760
  const getVisibleChunkRange = (channelInfo, clipPixelOffset = 0) => {
782
761
  const container = scrollContainerRef.current;
783
762
  return classifyChunkTiers(
@@ -796,7 +775,7 @@ var SpectrogramProvider = ({
796
775
  const globalPixelOffsets = [];
797
776
  for (const idx of indices) {
798
777
  const chunkNumber = extractChunkNumber(channelInfo.canvasIds[idx]);
799
- globalPixelOffsets.push(chunkNumber * import_core2.MAX_CANVAS_WIDTH);
778
+ globalPixelOffsets.push(chunkNumber * import_core3.MAX_CANVAS_WIDTH);
800
779
  }
801
780
  const colorLUT = (0, import_spectrogram2.getColorMap)(item.colorMap);
802
781
  await api.renderChunks(
@@ -830,7 +809,8 @@ var SpectrogramProvider = ({
830
809
  });
831
810
  const { cacheKey } = await api.computeFFT(
832
811
  {
833
- clipId: item.clipId,
812
+ // The pool's "clip id" names the registered audio: the buffer's key.
813
+ clipId: item.audioKey,
834
814
  channelDataArrays: item.channelDataArrays,
835
815
  config: item.config,
836
816
  sampleRate: item.sampleRate,
@@ -886,7 +866,7 @@ var SpectrogramProvider = ({
886
866
  }
887
867
  return false;
888
868
  };
889
- for (const item of clipsNeedingFFT) {
869
+ for (const item of clipsToRender) {
890
870
  if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
891
871
  try {
892
872
  const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);
@@ -950,7 +930,6 @@ var SpectrogramProvider = ({
950
930
  }
951
931
  }
952
932
  }
953
- renderedClipIdsRef.current.add(item.clipId);
954
933
  if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
955
934
  if (await renderBackgroundBatches(channelRanges, item)) return;
956
935
  }
@@ -961,78 +940,6 @@ var SpectrogramProvider = ({
961
940
  );
962
941
  }
963
942
  }
964
- for (const item of clipsNeedingDisplayOnly) {
965
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
966
- const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);
967
- if (!clipCanvasInfo || clipCanvasInfo.size === 0) continue;
968
- try {
969
- const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);
970
- const channelRanges = [];
971
- for (let ch = 0; ch < item.numChannels; ch++) {
972
- const channelInfo = clipCanvasInfo.get(ch);
973
- if (!channelInfo) continue;
974
- const range = getVisibleChunkRange(channelInfo, clipPixelOffset);
975
- channelRanges.push({ ch, channelInfo, ...range });
976
- }
977
- if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {
978
- const cacheKey = await computeFFTForChunks(
979
- workerApi,
980
- channelRanges[0].channelInfo,
981
- channelRanges[0].viewportIndices,
982
- item,
983
- generation
984
- );
985
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
986
- for (const { ch, channelInfo, viewportIndices } of channelRanges) {
987
- await renderChunkSubset(
988
- workerApi,
989
- cacheKey,
990
- channelInfo,
991
- viewportIndices,
992
- item,
993
- ch,
994
- generation
995
- );
996
- }
997
- }
998
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
999
- if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {
1000
- const bufferGroups = groupContiguousIndices(
1001
- channelRanges[0].channelInfo,
1002
- channelRanges[0].bufferIndices
1003
- );
1004
- for (const group of bufferGroups) {
1005
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
1006
- const cacheKey = await computeFFTForChunks(
1007
- workerApi,
1008
- channelRanges[0].channelInfo,
1009
- group,
1010
- item,
1011
- generation
1012
- );
1013
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
1014
- for (const { ch, channelInfo } of channelRanges) {
1015
- await renderChunkSubset(
1016
- workerApi,
1017
- cacheKey,
1018
- channelInfo,
1019
- group,
1020
- item,
1021
- ch,
1022
- generation
1023
- );
1024
- }
1025
- }
1026
- }
1027
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
1028
- if (await renderBackgroundBatches(channelRanges, item)) return;
1029
- } catch (err) {
1030
- if (err instanceof import_spectrogram2.SpectrogramAbortError) return;
1031
- console.warn(
1032
- `[waveform-playlist] Spectrogram display re-render error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`
1033
- );
1034
- }
1035
- }
1036
943
  };
1037
944
  computeAsync().catch((err) => {
1038
945
  console.error(
@@ -1044,53 +951,32 @@ var SpectrogramProvider = ({
1044
951
  mono,
1045
952
  spectrogramConfig,
1046
953
  spectrogramColorMap,
1047
- trackSpectrogramOverrides,
1048
954
  samplesPerPixel,
1049
955
  spectrogramCanvasVersion,
1050
- scrollContainerRef
956
+ scrollContainerRef,
957
+ audioKeyOf,
958
+ ensureWorkerPool
1051
959
  ]);
1052
- const setTrackRenderMode = (0, import_react2.useCallback)((trackId, mode) => {
1053
- setTrackSpectrogramOverrides((prev) => {
1054
- const next = new Map(prev);
1055
- const existing = next.get(trackId);
1056
- next.set(trackId, { ...existing, renderMode: mode });
1057
- return next;
1058
- });
1059
- }, []);
1060
- const setTrackSpectrogramConfig = (0, import_react2.useCallback)(
1061
- (trackId, config, colorMap) => {
1062
- setTrackSpectrogramOverrides((prev) => {
1063
- const next = new Map(prev);
1064
- const existing = next.get(trackId);
1065
- next.set(trackId, {
1066
- renderMode: existing?.renderMode ?? "waveform",
1067
- config,
1068
- ...colorMap !== void 0 ? { colorMap } : { colorMap: existing?.colorMap }
1069
- });
1070
- return next;
1071
- });
960
+ const setTrackRenderMode = (0, import_react3.useCallback)(
961
+ (trackId, mode) => {
962
+ arrangement.updateTrack(
963
+ trackId,
964
+ (track) => (0, import_core3.trackKind)(track) === "midi" || resolveRenderMode(track.renderMode) === mode ? track : { ...track, renderMode: mode }
965
+ );
1072
966
  },
1073
- []
967
+ [arrangement]
1074
968
  );
1075
- const ensureWorkerPool = (0, import_react2.useCallback)(() => {
1076
- if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;
1077
- try {
1078
- const pool = (0, import_spectrogram2.createSpectrogramWorkerPool)(
1079
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import_meta.url), {
1080
- type: "module"
1081
- }),
1082
- workerPoolSize
1083
- );
1084
- spectrogramWorkerRef.current = pool;
1085
- return pool;
1086
- } catch (err) {
1087
- console.warn(
1088
- `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`
1089
- );
1090
- return null;
1091
- }
1092
- }, [workerPoolSize]);
1093
- const registerSpectrogramCanvas = (0, import_react2.useCallback)(
969
+ const setTrackSpectrogramConfig = (0, import_react3.useCallback)(
970
+ (trackId, config2, colorMap2) => {
971
+ arrangement.updateTrack(trackId, (track) => ({
972
+ ...track,
973
+ spectrogramConfig: config2,
974
+ spectrogramColorMap: colorMap2 ?? track.spectrogramColorMap
975
+ }));
976
+ },
977
+ [arrangement]
978
+ );
979
+ const registerSpectrogramCanvas = (0, import_react3.useCallback)(
1094
980
  (reg) => {
1095
981
  const pool = ensureWorkerPool();
1096
982
  if (!pool) return;
@@ -1129,7 +1015,7 @@ var SpectrogramProvider = ({
1129
1015
  },
1130
1016
  [ensureWorkerPool]
1131
1017
  );
1132
- const unregisterSpectrogramCanvas = (0, import_react2.useCallback)((canvasId) => {
1018
+ const unregisterSpectrogramCanvas = (0, import_react3.useCallback)((canvasId) => {
1133
1019
  canvasHeightsRef.current.delete(canvasId);
1134
1020
  canvasRangesRef.current.delete(canvasId);
1135
1021
  const pool = spectrogramWorkerRef.current;
@@ -1163,9 +1049,9 @@ var SpectrogramProvider = ({
1163
1049
  }
1164
1050
  setSpectrogramCanvasVersion((v) => v + 1);
1165
1051
  }, []);
1166
- const renderMenuItems = (0, import_react2.useCallback)(
1052
+ const renderMenuItems = (0, import_react3.useCallback)(
1167
1053
  (props) => {
1168
- return SpectrogramMenuItems({
1054
+ return spectrogramMenuItems({
1169
1055
  renderMode: props.renderMode,
1170
1056
  onRenderModeChange: props.onRenderModeChange,
1171
1057
  onOpenSettings: props.onOpenSettings,
@@ -1174,9 +1060,8 @@ var SpectrogramProvider = ({
1174
1060
  },
1175
1061
  []
1176
1062
  );
1177
- const value = (0, import_react2.useMemo)(
1063
+ const value = (0, import_react3.useMemo)(
1178
1064
  () => ({
1179
- trackSpectrogramOverrides,
1180
1065
  spectrogramConfig,
1181
1066
  spectrogramColorMap,
1182
1067
  setTrackRenderMode,
@@ -1189,7 +1074,6 @@ var SpectrogramProvider = ({
1189
1074
  getFrequencyScale: import_spectrogram2.getFrequencyScale
1190
1075
  }),
1191
1076
  [
1192
- trackSpectrogramOverrides,
1193
1077
  spectrogramConfig,
1194
1078
  spectrogramColorMap,
1195
1079
  setTrackRenderMode,
@@ -1199,12 +1083,12 @@ var SpectrogramProvider = ({
1199
1083
  renderMenuItems
1200
1084
  ]
1201
1085
  );
1202
- return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_browser.SpectrogramIntegrationProvider, { value, children });
1086
+ return /* @__PURE__ */ (0, import_jsx_runtime3.jsx)(import_browser.SpectrogramIntegrationContext, { value, children });
1203
1087
  };
1204
1088
  // Annotate the CommonJS export names for ESM import in node:
1205
1089
  0 && (module.exports = {
1206
- SpectrogramMenuItems,
1207
1090
  SpectrogramProvider,
1208
- SpectrogramSettingsModal
1091
+ SpectrogramSettingsModal,
1092
+ spectrogramMenuItems
1209
1093
  });
1210
1094
  //# sourceMappingURL=index.js.map