@waveform-playlist/spectrogram 15.0.0-next.4 → 15.0.0-next.6

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.mjs CHANGED
@@ -421,7 +421,7 @@ var SpectrogramSettingsModal = ({
421
421
  };
422
422
 
423
423
  // src/SpectrogramProvider.tsx
424
- import { useState as useState2, useEffect as useEffect2, useRef as useRef2, useCallback, useMemo } from "react";
424
+ import { useState as useState2, useEffect as useEffect2, useRef as useRef2, useCallback, useMemo as useMemo2 } from "react";
425
425
  import {
426
426
  MAX_CANVAS_WIDTH as MAX_CANVAS_WIDTH2
427
427
  } from "@waveform-playlist/core";
@@ -522,23 +522,10 @@ function computeChunkSampleRange({
522
522
  function resolveRenderMode(override, trackRenderMode) {
523
523
  return override?.renderMode ?? trackRenderMode ?? "waveform";
524
524
  }
525
- function toComputeConfig(cfg) {
526
- return {
527
- fftSize: cfg?.fftSize,
528
- hopSize: cfg?.hopSize,
529
- windowFunction: cfg?.windowFunction,
530
- alpha: cfg?.alpha,
531
- zeroPaddingFactor: cfg?.zeroPaddingFactor
532
- };
533
- }
534
525
  function buildConfigKey(params) {
535
526
  const { mode, cfg, cm, mono } = params;
536
527
  return JSON.stringify({ mode, cfg, cm, mono });
537
528
  }
538
- function buildFFTKey(params) {
539
- const { mode, mono, computeConfig } = params;
540
- return JSON.stringify({ mode, mono, ...computeConfig });
541
- }
542
529
  function mapsDiffer(prev, current) {
543
530
  if (current.size !== prev.size) return true;
544
531
  for (const [key, value] of current) {
@@ -563,6 +550,40 @@ function resolveClipRange(clip, registered) {
563
550
  };
564
551
  }
565
552
 
553
+ // src/audioRegistration.ts
554
+ function createAudioKeyOf() {
555
+ const keys = /* @__PURE__ */ new WeakMap();
556
+ let next = 0;
557
+ return (buffer) => {
558
+ const existing = keys.get(buffer);
559
+ if (existing !== void 0) return existing;
560
+ next += 1;
561
+ const key = `audio-${next}`;
562
+ keys.set(buffer, key);
563
+ return key;
564
+ };
565
+ }
566
+ function spectrogramAudio(tracks, overrides, audioKeyOf) {
567
+ const wanted = /* @__PURE__ */ new Map();
568
+ for (const track of tracks) {
569
+ if (resolveRenderMode(overrides.get(track.id), track.renderMode) === "waveform") continue;
570
+ for (const clip of track.clips) {
571
+ if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);
572
+ }
573
+ }
574
+ return wanted;
575
+ }
576
+ function channelData(buffer) {
577
+ return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));
578
+ }
579
+
580
+ // src/useStableByContent.ts
581
+ import { useMemo } from "react";
582
+ function useStableByContent(value) {
583
+ const content = JSON.stringify(value);
584
+ return useMemo(() => value, [content]);
585
+ }
586
+
566
587
  // src/SpectrogramProvider.tsx
567
588
  import {
568
589
  SpectrogramIntegrationProvider
@@ -575,14 +596,16 @@ import {
575
596
  } from "@waveform-playlist/browser";
576
597
  import { jsx as jsx3 } from "react/jsx-runtime";
577
598
  var SpectrogramProvider = ({
578
- config: spectrogramConfig,
579
- colorMap: spectrogramColorMap,
599
+ config,
600
+ colorMap,
580
601
  workerPoolSize,
581
602
  children
582
603
  }) => {
604
+ const spectrogramConfig = useStableByContent(config);
605
+ const spectrogramColorMap = useStableByContent(colorMap);
583
606
  const { mono } = usePlaylistView();
584
607
  const { samplesPerPixel } = usePlaylistZoom();
585
- const { tracks, isReady } = usePlaylistTimeline();
608
+ const { tracks } = usePlaylistTimeline();
586
609
  const { scrollContainerRef } = usePlaybackControls();
587
610
  const [trackSpectrogramOverrides, setTrackSpectrogramOverrides] = useState2(() => /* @__PURE__ */ new Map());
588
611
  const spectrogramCanvasRegistryRef = useRef2(/* @__PURE__ */ new Map());
@@ -590,13 +613,29 @@ var SpectrogramProvider = ({
590
613
  const canvasRangesRef = useRef2(/* @__PURE__ */ new Map());
591
614
  const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = useState2(0);
592
615
  const prevSpectrogramConfigRef = useRef2(/* @__PURE__ */ new Map());
593
- const prevSpectrogramFFTKeyRef = useRef2(/* @__PURE__ */ new Map());
594
616
  const spectrogramWorkerRef = useRef2(null);
595
617
  const spectrogramGenerationRef = useRef2(0);
596
618
  const prevCanvasVersionRef = useRef2(0);
597
- const renderedClipIdsRef = useRef2(/* @__PURE__ */ new Set());
598
619
  const backgroundRenderAbortRef = useRef2(null);
599
- const registeredAudioClipIdsRef = useRef2(/* @__PURE__ */ new Set());
620
+ const [audioKeyOf] = useState2(createAudioKeyOf);
621
+ const ensureWorkerPool = useCallback(() => {
622
+ if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;
623
+ try {
624
+ const pool = createSpectrogramWorkerPool(
625
+ () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import.meta.url), {
626
+ type: "module"
627
+ }),
628
+ workerPoolSize
629
+ );
630
+ spectrogramWorkerRef.current = pool;
631
+ return pool;
632
+ } catch (err) {
633
+ console.warn(
634
+ `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`
635
+ );
636
+ return null;
637
+ }
638
+ }, [workerPoolSize]);
600
639
  useEffect2(() => {
601
640
  return () => {
602
641
  spectrogramWorkerRef.current?.terminate();
@@ -604,50 +643,20 @@ var SpectrogramProvider = ({
604
643
  };
605
644
  }, []);
606
645
  useEffect2(() => {
607
- if (!isReady || tracks.length === 0) return;
608
- let workerApi = spectrogramWorkerRef.current;
609
- if (!workerApi) {
610
- try {
611
- workerApi = createSpectrogramWorkerPool(
612
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import.meta.url), {
613
- type: "module"
614
- }),
615
- workerPoolSize
616
- );
617
- spectrogramWorkerRef.current = workerApi;
618
- } catch (err) {
619
- console.warn(
620
- `[waveform-playlist] Spectrogram Web Worker unavailable for pre-transfer: ${err instanceof Error ? err.message : String(err)}`
621
- );
622
- return;
623
- }
646
+ const wanted = spectrogramAudio(tracks, trackSpectrogramOverrides, audioKeyOf);
647
+ const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;
648
+ if (!pool) return;
649
+ const held = new Set(pool.registeredAudioClipIds());
650
+ for (const [key, buffer] of wanted) {
651
+ if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);
624
652
  }
625
- const currentClipIds = /* @__PURE__ */ new Set();
626
- for (const track of tracks) {
627
- for (const clip of track.clips) {
628
- if (!clip.audioBuffer) continue;
629
- currentClipIds.add(clip.id);
630
- if (!registeredAudioClipIdsRef.current.has(clip.id)) {
631
- const channelDataArrays = [];
632
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
633
- channelDataArrays.push(clip.audioBuffer.getChannelData(ch));
634
- }
635
- workerApi.registerAudioData(clip.id, channelDataArrays, clip.audioBuffer.sampleRate);
636
- registeredAudioClipIdsRef.current.add(clip.id);
637
- }
638
- }
639
- }
640
- for (const clipId of registeredAudioClipIdsRef.current) {
641
- if (!currentClipIds.has(clipId)) {
642
- workerApi.unregisterAudioData(clipId);
643
- registeredAudioClipIdsRef.current.delete(clipId);
644
- }
653
+ for (const key of held) {
654
+ if (!wanted.has(key)) pool.unregisterAudioData(key);
645
655
  }
646
- }, [isReady, tracks]);
656
+ }, [tracks, trackSpectrogramOverrides, audioKeyOf, ensureWorkerPool]);
647
657
  useEffect2(() => {
648
658
  if (tracks.length === 0) return;
649
659
  const currentKeys = /* @__PURE__ */ new Map();
650
- const currentFFTKeys = /* @__PURE__ */ new Map();
651
660
  tracks.forEach((track) => {
652
661
  const override = trackSpectrogramOverrides.get(track.id);
653
662
  const mode = resolveRenderMode(override, track.renderMode);
@@ -655,54 +664,28 @@ var SpectrogramProvider = ({
655
664
  const cfg = override?.config ?? track.spectrogramConfig ?? spectrogramConfig;
656
665
  const cm = override?.colorMap ?? track.spectrogramColorMap ?? spectrogramColorMap;
657
666
  currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));
658
- currentFFTKeys.set(
659
- track.id,
660
- buildFFTKey({ mode, mono, computeConfig: toComputeConfig(cfg) })
661
- );
662
667
  });
663
668
  const prevKeys = prevSpectrogramConfigRef.current;
664
- const prevFFTKeys = prevSpectrogramFFTKeyRef.current;
665
669
  const configChanged = mapsDiffer(prevKeys, currentKeys);
666
- const fftKeyChanged = mapsDiffer(prevFFTKeys, currentFFTKeys);
667
670
  const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;
668
671
  prevCanvasVersionRef.current = spectrogramCanvasVersion;
669
672
  if (!configChanged && !canvasVersionChanged) return;
670
673
  if (configChanged) {
671
674
  prevSpectrogramConfigRef.current = currentKeys;
672
- prevSpectrogramFFTKeyRef.current = currentFFTKeys;
673
675
  }
674
676
  if (backgroundRenderAbortRef.current) {
675
677
  backgroundRenderAbortRef.current.aborted = true;
676
678
  }
677
679
  const generation = ++spectrogramGenerationRef.current;
678
- if (spectrogramWorkerRef.current) {
679
- spectrogramWorkerRef.current.abortGeneration(generation);
680
- }
681
- let workerApi = spectrogramWorkerRef.current;
682
- if (!workerApi) {
683
- try {
684
- workerApi = createSpectrogramWorkerPool(
685
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import.meta.url), {
686
- type: "module"
687
- }),
688
- workerPoolSize
689
- );
690
- spectrogramWorkerRef.current = workerApi;
691
- } catch (err) {
692
- console.error(
693
- `[waveform-playlist] Spectrogram Web Worker required but unavailable: ${err instanceof Error ? err.message : String(err)}`
694
- );
695
- return;
696
- }
697
- }
698
- const clipsNeedingFFT = [];
699
- const clipsNeedingDisplayOnly = [];
700
- tracks.forEach((track, i) => {
680
+ const workerApi = ensureWorkerPool();
681
+ if (!workerApi) return;
682
+ workerApi.abortGeneration(generation);
683
+ const clipsToRender = [];
684
+ tracks.forEach((track) => {
701
685
  const override = trackSpectrogramOverrides.get(track.id);
702
686
  const mode = resolveRenderMode(override, track.renderMode);
703
687
  if (mode === "waveform") return;
704
688
  const trackConfigChanged = configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);
705
- const trackFFTChanged = fftKeyChanged && currentFFTKeys.get(track.id) !== prevFFTKeys.get(track.id);
706
689
  const hasRegisteredCanvases = canvasVersionChanged && track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));
707
690
  if (!trackConfigChanged && !hasRegisteredCanvases) return;
708
691
  const cfg = override?.config ?? track.spectrogramConfig ?? spectrogramConfig ?? {};
@@ -717,34 +700,10 @@ var SpectrogramProvider = ({
717
700
  canvasRangesRef.current
718
701
  )
719
702
  );
720
- if (!trackFFTChanged && !hasRegisteredCanvases && renderedClipIdsRef.current.has(clip.id)) {
721
- const channelDataArrays2 = [];
722
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
723
- channelDataArrays2.push(clip.audioBuffer.getChannelData(ch));
724
- }
725
- clipsNeedingDisplayOnly.push({
726
- clipId: clip.id,
727
- trackIndex: i,
728
- channelDataArrays: channelDataArrays2,
729
- config: cfg,
730
- sampleRate: clip.audioBuffer.sampleRate,
731
- offsetSamples,
732
- durationSamples,
733
- clipStartSample: clip.startSample,
734
- monoFlag,
735
- colorMap: cm,
736
- numChannels: monoFlag ? 1 : clip.audioBuffer.numberOfChannels
737
- });
738
- continue;
739
- }
740
- const channelDataArrays = [];
741
- for (let ch = 0; ch < clip.audioBuffer.numberOfChannels; ch++) {
742
- channelDataArrays.push(clip.audioBuffer.getChannelData(ch));
743
- }
744
- clipsNeedingFFT.push({
703
+ clipsToRender.push({
745
704
  clipId: clip.id,
746
- trackIndex: i,
747
- channelDataArrays,
705
+ audioKey: audioKeyOf(clip.audioBuffer),
706
+ channelDataArrays: channelData(clip.audioBuffer),
748
707
  config: cfg,
749
708
  sampleRate: clip.audioBuffer.sampleRate,
750
709
  offsetSamples,
@@ -755,7 +714,7 @@ var SpectrogramProvider = ({
755
714
  });
756
715
  }
757
716
  });
758
- if (clipsNeedingFFT.length === 0 && clipsNeedingDisplayOnly.length === 0) return;
717
+ if (clipsToRender.length === 0) return;
759
718
  const getVisibleChunkRange = (channelInfo, clipPixelOffset = 0) => {
760
719
  const container = scrollContainerRef.current;
761
720
  return classifyChunkTiers(
@@ -808,7 +767,8 @@ var SpectrogramProvider = ({
808
767
  });
809
768
  const { cacheKey } = await api.computeFFT(
810
769
  {
811
- clipId: item.clipId,
770
+ // The pool's "clip id" names the registered audio: the buffer's key.
771
+ clipId: item.audioKey,
812
772
  channelDataArrays: item.channelDataArrays,
813
773
  config: item.config,
814
774
  sampleRate: item.sampleRate,
@@ -864,7 +824,7 @@ var SpectrogramProvider = ({
864
824
  }
865
825
  return false;
866
826
  };
867
- for (const item of clipsNeedingFFT) {
827
+ for (const item of clipsToRender) {
868
828
  if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
869
829
  try {
870
830
  const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);
@@ -928,7 +888,6 @@ var SpectrogramProvider = ({
928
888
  }
929
889
  }
930
890
  }
931
- renderedClipIdsRef.current.add(item.clipId);
932
891
  if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
933
892
  if (await renderBackgroundBatches(channelRanges, item)) return;
934
893
  }
@@ -939,78 +898,6 @@ var SpectrogramProvider = ({
939
898
  );
940
899
  }
941
900
  }
942
- for (const item of clipsNeedingDisplayOnly) {
943
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
944
- const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);
945
- if (!clipCanvasInfo || clipCanvasInfo.size === 0) continue;
946
- try {
947
- const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);
948
- const channelRanges = [];
949
- for (let ch = 0; ch < item.numChannels; ch++) {
950
- const channelInfo = clipCanvasInfo.get(ch);
951
- if (!channelInfo) continue;
952
- const range = getVisibleChunkRange(channelInfo, clipPixelOffset);
953
- channelRanges.push({ ch, channelInfo, ...range });
954
- }
955
- if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {
956
- const cacheKey = await computeFFTForChunks(
957
- workerApi,
958
- channelRanges[0].channelInfo,
959
- channelRanges[0].viewportIndices,
960
- item,
961
- generation
962
- );
963
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
964
- for (const { ch, channelInfo, viewportIndices } of channelRanges) {
965
- await renderChunkSubset(
966
- workerApi,
967
- cacheKey,
968
- channelInfo,
969
- viewportIndices,
970
- item,
971
- ch,
972
- generation
973
- );
974
- }
975
- }
976
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
977
- if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {
978
- const bufferGroups = groupContiguousIndices(
979
- channelRanges[0].channelInfo,
980
- channelRanges[0].bufferIndices
981
- );
982
- for (const group of bufferGroups) {
983
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
984
- const cacheKey = await computeFFTForChunks(
985
- workerApi,
986
- channelRanges[0].channelInfo,
987
- group,
988
- item,
989
- generation
990
- );
991
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
992
- for (const { ch, channelInfo } of channelRanges) {
993
- await renderChunkSubset(
994
- workerApi,
995
- cacheKey,
996
- channelInfo,
997
- group,
998
- item,
999
- ch,
1000
- generation
1001
- );
1002
- }
1003
- }
1004
- }
1005
- if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;
1006
- if (await renderBackgroundBatches(channelRanges, item)) return;
1007
- } catch (err) {
1008
- if (err instanceof SpectrogramAbortError) return;
1009
- console.warn(
1010
- `[waveform-playlist] Spectrogram display re-render error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`
1011
- );
1012
- }
1013
- }
1014
901
  };
1015
902
  computeAsync().catch((err) => {
1016
903
  console.error(
@@ -1025,7 +912,9 @@ var SpectrogramProvider = ({
1025
912
  trackSpectrogramOverrides,
1026
913
  samplesPerPixel,
1027
914
  spectrogramCanvasVersion,
1028
- scrollContainerRef
915
+ scrollContainerRef,
916
+ audioKeyOf,
917
+ ensureWorkerPool
1029
918
  ]);
1030
919
  const setTrackRenderMode = useCallback((trackId, mode) => {
1031
920
  setTrackSpectrogramOverrides((prev) => {
@@ -1036,38 +925,20 @@ var SpectrogramProvider = ({
1036
925
  });
1037
926
  }, []);
1038
927
  const setTrackSpectrogramConfig = useCallback(
1039
- (trackId, config, colorMap) => {
928
+ (trackId, config2, colorMap2) => {
1040
929
  setTrackSpectrogramOverrides((prev) => {
1041
930
  const next = new Map(prev);
1042
931
  const existing = next.get(trackId);
1043
932
  next.set(trackId, {
1044
- renderMode: existing?.renderMode ?? "waveform",
1045
- config,
1046
- ...colorMap !== void 0 ? { colorMap } : { colorMap: existing?.colorMap }
933
+ ...existing,
934
+ config: config2,
935
+ colorMap: colorMap2 ?? existing?.colorMap
1047
936
  });
1048
937
  return next;
1049
938
  });
1050
939
  },
1051
940
  []
1052
941
  );
1053
- const ensureWorkerPool = useCallback(() => {
1054
- if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;
1055
- try {
1056
- const pool = createSpectrogramWorkerPool(
1057
- () => new Worker(new URL("@dawcore/spectrogram/worker/spectrogram.worker", import.meta.url), {
1058
- type: "module"
1059
- }),
1060
- workerPoolSize
1061
- );
1062
- spectrogramWorkerRef.current = pool;
1063
- return pool;
1064
- } catch (err) {
1065
- console.warn(
1066
- `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`
1067
- );
1068
- return null;
1069
- }
1070
- }, [workerPoolSize]);
1071
942
  const registerSpectrogramCanvas = useCallback(
1072
943
  (reg) => {
1073
944
  const pool = ensureWorkerPool();
@@ -1152,7 +1023,7 @@ var SpectrogramProvider = ({
1152
1023
  },
1153
1024
  []
1154
1025
  );
1155
- const value = useMemo(
1026
+ const value = useMemo2(
1156
1027
  () => ({
1157
1028
  trackSpectrogramOverrides,
1158
1029
  spectrogramConfig,