@waveform-playlist/spectrogram 15.0.0-next.13 → 15.0.0-next.15

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  React Provider + UI for rendering waveform-playlist tracks as FFT spectrograms — color-mapped time-frequency plots instead of (or alongside) the time-domain waveform.
4
4
 
5
- Wraps [`@dawcore/spectrogram`](https://www.npmjs.com/package/@dawcore/spectrogram), which owns the FFT computation, Web Worker, and chunked rendering. This package supplies the React layer: mount `<SpectrogramProvider>` inside `<WaveformPlaylistProvider>` from [`@waveform-playlist/browser`](https://www.npmjs.com/package/@waveform-playlist/browser).
5
+ Wraps [`@dawcore/spectrogram`](https://www.npmjs.com/package/@dawcore/spectrogram), which owns the FFT computation, Web Worker, and chunked rendering. This package supplies the React layer: mount `<SpectrogramProvider>` inside `<WebAudioProvider>` from [`@waveform-playlist/browser`](https://www.npmjs.com/package/@waveform-playlist/browser).
6
6
 
7
7
  ## Features
8
8
 
@@ -26,7 +26,7 @@ Requires `@waveform-playlist/browser`, `react`, and `styled-components` as peer
26
26
  Wrap your editor with `<SpectrogramProvider>` and set a track's `renderMode`:
27
27
 
28
28
  ```tsx
29
- import { WaveformPlaylistProvider, Waveform, useCreateArrangement } from '@waveform-playlist/browser';
29
+ import { WebAudioProvider, Waveform, useCreateArrangement } from '@waveform-playlist/browser';
30
30
  import { audioTrack } from '@waveform-playlist/core';
31
31
  import { SpectrogramProvider } from '@waveform-playlist/spectrogram';
32
32
 
@@ -36,11 +36,11 @@ function MyEditor() {
36
36
  ]);
37
37
 
38
38
  return (
39
- <WaveformPlaylistProvider arrangement={arrangement}>
39
+ <WebAudioProvider arrangement={arrangement}>
40
40
  <SpectrogramProvider config={{ fftSize: 2048, frequencyScale: 'mel' }} colorMap="viridis">
41
41
  <Waveform />
42
42
  </SpectrogramProvider>
43
- </WaveformPlaylistProvider>
43
+ </WebAudioProvider>
44
44
  );
45
45
  }
46
46
  ```
package/dist/index.js CHANGED
@@ -647,9 +647,9 @@ var SpectrogramProvider = ({
647
647
  }) => {
648
648
  const spectrogramConfig = useStableByContent(config);
649
649
  const spectrogramColorMap = useStableByContent(colorMap);
650
- const { mono } = (0, import_browser2.usePlaylistView)();
651
- const { samplesPerPixel } = (0, import_browser2.usePlaylistZoom)();
652
- const { tracks } = (0, import_browser2.usePlaylistTimeline)();
650
+ const { mono } = (0, import_browser2.useAudioSettings)();
651
+ const { samplesPerPixel } = (0, import_browser2.useZoom)();
652
+ const { tracks } = (0, import_browser2.useTimeline)();
653
653
  const { scrollContainerRef } = (0, import_browser2.usePlaybackControls)();
654
654
  const arrangement = (0, import_browser2.useArrangement)();
655
655
  const spectrogramCanvasRegistryRef = (0, import_react3.useRef)(/* @__PURE__ */ new Map());
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/components/SpectrogramMenuItems.tsx","../src/components/SpectrogramSettingsModal.tsx","../src/SpectrogramProvider.tsx","../src/spectrogram-helpers.ts","../src/audioRegistration.ts","../src/useStableByContent.ts"],"sourcesContent":["// React surface — computation/worker primitives live in @dawcore/spectrogram.\nexport { spectrogramMenuItems } from './components';\nexport type { SpectrogramMenuItemsOptions } from './components';\nexport { SpectrogramSettingsModal } from './components';\nexport type { SpectrogramSettingsModalProps } from './components';\n\nexport { SpectrogramProvider } from './SpectrogramProvider';\nexport type { SpectrogramProviderProps } from './SpectrogramProvider';\n","import React from 'react';\nimport styled from 'styled-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport type { SpectrogramIntegration } from '@waveform-playlist/browser';\n\n/** The items browser's track menu asks the spectrogram integration for:\n * ui-components' `TrackMenuItem[]`, named through the type that carries it. */\ntype MenuItems = ReturnType<NonNullable<SpectrogramIntegration['renderMenuItems']>>;\n\nconst SectionLabel = styled.div`\n font-size: 0.65rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.5;\n margin-bottom: 0.25rem;\n`;\n\nconst RadioLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n padding: 0.2rem 0;\n font-size: 0.8rem;\n cursor: pointer;\n\n &:hover {\n opacity: 0.8;\n }\n`;\n\nconst SettingsButton = styled.button`\n background: none;\n border: none;\n color: inherit;\n cursor: pointer;\n font-size: 0.8rem;\n padding: 0.35rem 0.75rem;\n width: 100%;\n text-align: left;\n\n &:hover {\n background: rgba(128, 128, 128, 0.15);\n }\n`;\n\nconst DropdownSection = styled.div`\n padding: 0.25rem 0.75rem;\n`;\n\nconst RENDER_MODES: { value: RenderMode; label: string }[] = [\n { value: 'waveform', label: 'Waveform' },\n { value: 'spectrogram', label: 'Spectrogram' },\n { value: 'both', label: 'Both' },\n];\n\nexport interface SpectrogramMenuItemsOptions {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Returns the track menu items (`TrackMenuItem[]` of ui-components) for the\n * spectrogram display mode radios and settings button.\n */\nexport function spectrogramMenuItems({\n renderMode,\n onRenderModeChange,\n onOpenSettings,\n onClose,\n}: SpectrogramMenuItemsOptions): MenuItems {\n return [\n {\n id: 'spectrogram-display',\n content: (\n <DropdownSection>\n <SectionLabel>Display</SectionLabel>\n {RENDER_MODES.map(({ value, label }) => (\n <RadioLabel key={value}>\n <input\n type=\"radio\"\n name=\"render-mode\"\n checked={renderMode === value}\n onChange={() => {\n onRenderModeChange(value);\n onClose?.();\n }}\n />\n {label}\n </RadioLabel>\n ))}\n </DropdownSection>\n ),\n },\n {\n id: 'spectrogram-settings',\n content: (\n <SettingsButton\n onClick={(e) => {\n e.stopPropagation();\n onClose?.();\n onOpenSettings();\n }}\n onMouseDown={(e) => e.stopPropagation()}\n >\n Spectrogram Settings...\n </SettingsButton>\n ),\n },\n ];\n}\n","import React, { useRef, useEffect, useId, useLayoutEffect, useState } from 'react';\nimport styled from 'styled-components';\nimport {\n SPECTROGRAM_DEFAULTS,\n type SpectrogramConfig,\n type ColorMapValue,\n type ColorMapName,\n type FFTSize,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramSettingsModalProps {\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n /**\n * Called on Apply with the config it was given plus the fields the user\n * changed, and the colour map (the one given unless the user picked one).\n * Not called when nothing was changed: Apply then only closes.\n */\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n /**\n * The sample rate of the audio. With a config that has no `maxFrequency`,\n * the field shows half of it, the top the spectrogram is drawn to.\n */\n sampleRate?: number;\n}\n\nconst StyledDialog = styled.dialog`\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 8px;\n padding: 1.5rem;\n background: ${(p) => p.theme.timescaleBackgroundColor ?? '#222'};\n color: ${(p) => p.theme.textColor ?? 'inherit'};\n min-width: 380px;\n max-width: 500px;\n overscroll-behavior: contain;\n\n &::backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n`;\n\nconst Title = styled.h3`\n margin: 0 0 1rem;\n font-size: 1rem;\n`;\n\nconst FormGrid = styled.div`\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n`;\n\nconst Field = styled.div<{ $span?: boolean }>`\n display: flex;\n flex-direction: column;\n gap: 0.2rem;\n grid-column: ${(p) => (p.$span ? '1 / -1' : 'auto')};\n`;\n\nconst Label = styled.label`\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.6;\n`;\n\nconst Select = styled.select`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n`;\n\nconst NumberInput = styled.input`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n width: 100%;\n box-sizing: border-box;\n`;\n\nconst CheckboxLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n font-size: 0.85rem;\n cursor: pointer;\n`;\n\nconst ButtonRow = styled.div`\n display: flex;\n justify-content: flex-end;\n gap: 0.5rem;\n margin-top: 1.25rem;\n`;\n\nconst ModalButton = styled.button<{ $primary?: boolean }>`\n padding: 0.4rem 1rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n cursor: pointer;\n font-size: 0.85rem;\n background: ${(p) => (p.$primary ? (p.theme.buttonBackground ?? '#0091ff') : 'transparent')};\n color: ${(p) => (p.$primary ? (p.theme.buttonText ?? '#fff') : 'inherit')};\n ${(p) => (p.$primary && p.theme.buttonBorder ? `border-color: ${p.theme.buttonBorder};` : '')}\n\n &:hover {\n ${(p) =>\n p.$primary && p.theme.buttonHoverBackground\n ? `background: ${p.theme.buttonHoverBackground};`\n : 'opacity: 0.85;'}\n }\n`;\n\nconst FFT_SIZES = [256, 512, 1024, 2048, 4096, 8192];\nconst WINDOW_FUNCTIONS = [\n 'hann',\n 'hamming',\n 'blackman',\n 'blackman-harris',\n 'bartlett',\n 'rectangular',\n] as const;\nconst FREQ_SCALES = ['linear', 'logarithmic', 'mel', 'bark', 'erb'] as const;\nconst COLOR_MAPS: ColorMapName[] = ['viridis', 'magma', 'inferno', 'grayscale', 'igray', 'roseus'];\n/** The select's value for a colour map given as an array of colours. */\nconst CUSTOM_COLOR_MAP = 'custom';\n\ntype SettingsFormProps = Omit<SpectrogramSettingsModalProps, 'open'>;\n\n/**\n * The form is a draft of the settings. It is mounted only while the dialog is\n * open, so its state starts from the props each time the dialog opens and is\n * never overwritten by a parent re-render while the user is editing.\n *\n * The draft holds only the fields the user changed (#814). A field shows its\n * edit, else the config's value, else the default; Apply sends the config it\n * was given with the edits on top, so a field the form does not show\n * (`alpha`, `labelsColor`, `labelsBackground`) and a field left at its default\n * (`maxFrequency`: half the sample rate) are not written.\n */\nconst SettingsForm: React.FC<SettingsFormProps> = ({\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const id = useId();\n const [edits, setEdits] = useState<SpectrogramConfig>({});\n const [editedColorMap, setEditedColorMap] = useState<ColorMapName | undefined>(undefined);\n\n const shown = <K extends keyof SpectrogramConfig>(key: K): SpectrogramConfig[K] =>\n key in edits ? edits[key] : config[key];\n const edit = (changes: SpectrogramConfig) => setEdits((prev) => ({ ...prev, ...changes }));\n\n const fftSize = shown('fftSize') ?? SPECTROGRAM_DEFAULTS.fftSize;\n const hopSize = shown('hopSize') ?? Math.floor(fftSize / 4);\n const zeroPadding = shown('zeroPaddingFactor') ?? SPECTROGRAM_DEFAULTS.zeroPaddingFactor;\n const windowFn = shown('windowFunction') ?? SPECTROGRAM_DEFAULTS.windowFunction;\n const freqScale = shown('frequencyScale') ?? SPECTROGRAM_DEFAULTS.frequencyScale;\n const minFreq = shown('minFrequency') ?? SPECTROGRAM_DEFAULTS.minFrequency;\n const nyquist = sampleRate !== undefined ? sampleRate / 2 : undefined;\n // An emptied field stays empty while the user types (Apply then leaves the\n // default); only an untouched one shows the default's number.\n const maxFreq = 'maxFrequency' in edits ? edits.maxFrequency : (config.maxFrequency ?? nyquist);\n const gainDb = shown('gainDb') ?? SPECTROGRAM_DEFAULTS.gainDb;\n const rangeDb = shown('rangeDb') ?? SPECTROGRAM_DEFAULTS.rangeDb;\n const showLabels = shown('labels') ?? SPECTROGRAM_DEFAULTS.labels;\n const isCustomColorMap = typeof colorMap !== 'string';\n const colorMapValue = editedColorMap ?? (isCustomColorMap ? CUSTOM_COLOR_MAP : colorMap);\n\n const handleApply = () => {\n // A field set back to the value it had is no change. With none, Apply\n // only closes: an onApply would be an undo step that changes nothing.\n const configChanged = (Object.keys(edits) as Array<keyof SpectrogramConfig>).some(\n (key) => edits[key] !== config[key]\n );\n const colorMapChanged = editedColorMap !== undefined && editedColorMap !== colorMap;\n if (configChanged || colorMapChanged) {\n onApply({ ...config, ...edits }, editedColorMap ?? colorMap);\n }\n onClose();\n };\n\n return (\n <>\n <FormGrid>\n <Field>\n <Label htmlFor={`${id}-fft-size`}>FFT Size</Label>\n <Select\n id={`${id}-fft-size`}\n value={fftSize}\n onChange={(e) => {\n const v = Number(e.target.value) as FFTSize;\n edit({ fftSize: v, hopSize: Math.floor(v / 4) });\n }}\n >\n {FFT_SIZES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-hop-size`}>Hop Size</Label>\n <Select\n id={`${id}-hop-size`}\n value={hopSize}\n onChange={(e) => edit({ hopSize: Number(e.target.value) })}\n >\n {[\n { label: `${fftSize} (no overlap)`, value: fftSize },\n { label: `${Math.floor(fftSize / 2)} (50%)`, value: Math.floor(fftSize / 2) },\n { label: `${Math.floor(fftSize / 4)} (75%)`, value: Math.floor(fftSize / 4) },\n { label: `${Math.floor(fftSize / 8)} (87.5%)`, value: Math.floor(fftSize / 8) },\n ].map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-zero-padding`}>Zero Padding</Label>\n <Select\n id={`${id}-zero-padding`}\n value={zeroPadding}\n onChange={(e) => edit({ zeroPaddingFactor: Number(e.target.value) })}\n >\n {[1, 2, 4, 8, 16].map((v) => (\n <option key={v} value={v}>\n {v}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-window-function`}>Window Function</Label>\n <Select\n id={`${id}-window-function`}\n value={windowFn}\n onChange={(e) =>\n edit({ windowFunction: e.target.value as SpectrogramConfig['windowFunction'] })\n }\n >\n {WINDOW_FUNCTIONS.map((w) => (\n <option key={w} value={w}>\n {w}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-frequency-scale`}>Frequency Scale</Label>\n <Select\n id={`${id}-frequency-scale`}\n value={freqScale}\n onChange={(e) =>\n edit({ frequencyScale: e.target.value as SpectrogramConfig['frequencyScale'] })\n }\n >\n {FREQ_SCALES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-color-map`}>Color Map</Label>\n <Select\n id={`${id}-color-map`}\n value={colorMapValue}\n onChange={(e) =>\n // \"custom\" is the colour map given (an array): no edit.\n setEditedColorMap(\n e.target.value === CUSTOM_COLOR_MAP ? undefined : (e.target.value as ColorMapName)\n )\n }\n >\n {isCustomColorMap && <option value={CUSTOM_COLOR_MAP}>{CUSTOM_COLOR_MAP}</option>}\n {COLOR_MAPS.map((c) => (\n <option key={c} value={c}>\n {c}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-min-frequency`}>Min Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-min-frequency`}\n type=\"number\"\n min={0}\n max={5000}\n step={50}\n value={minFreq}\n onChange={(e) => edit({ minFrequency: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-max-frequency`}>Max Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-max-frequency`}\n type=\"number\"\n min={1000}\n max={nyquist}\n step={50}\n value={maxFreq ?? ''}\n onChange={(e) =>\n // Emptied: back to the default, half the sample rate.\n edit({ maxFrequency: e.target.value === '' ? undefined : Number(e.target.value) })\n }\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-range-db`}>Range (dB)</Label>\n <NumberInput\n id={`${id}-range-db`}\n type=\"number\"\n min={1}\n max={120}\n step={1}\n value={rangeDb}\n onChange={(e) => edit({ rangeDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-gain-db`}>Gain (dB)</Label>\n <NumberInput\n id={`${id}-gain-db`}\n type=\"number\"\n min={-20}\n max={60}\n step={1}\n value={gainDb}\n onChange={(e) => edit({ gainDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field $span>\n <CheckboxLabel>\n <input\n type=\"checkbox\"\n checked={showLabels}\n onChange={(e) => edit({ labels: e.target.checked })}\n />\n Show Frequency Labels\n </CheckboxLabel>\n </Field>\n </FormGrid>\n\n <ButtonRow>\n <ModalButton type=\"button\" onClick={onClose}>\n Cancel\n </ModalButton>\n <ModalButton type=\"button\" $primary onClick={handleApply}>\n Apply\n </ModalButton>\n </ButtonRow>\n </>\n );\n};\n\nexport const SpectrogramSettingsModal: React.FC<SpectrogramSettingsModalProps> = ({\n open,\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const dialogRef = useRef<HTMLDialogElement>(null);\n const titleId = useId();\n\n // Latest props for the native `close` listener, so the listener is attached\n // once and not re-added whenever the parent passes a new `onClose`.\n const latestRef = useRef({ open, onClose });\n useLayoutEffect(() => {\n latestRef.current = { open, onClose };\n });\n\n // Native close (Escape key)\n useEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n const handleClose = () => {\n // Only report a close the parent did not ask for (avoids double-fire)\n if (latestRef.current.open) {\n latestRef.current.onClose();\n }\n };\n dialog.addEventListener('close', handleClose);\n return () => dialog.removeEventListener('close', handleClose);\n }, []);\n\n // Layout effect: the dialog opens and closes in the same frame as the form\n // mounts and unmounts, whatever triggered the change.\n useLayoutEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n if (open && !dialog.open) {\n dialog.showModal();\n } else if (!open && dialog.open) {\n dialog.close();\n }\n }, [open]);\n\n return (\n <StyledDialog ref={dialogRef} aria-labelledby={titleId}>\n <Title id={titleId}>Spectrogram Settings</Title>\n {open && (\n <SettingsForm\n onClose={onClose}\n config={config}\n colorMap={colorMap}\n onApply={onApply}\n sampleRate={sampleRate}\n />\n )}\n </StyledDialog>\n );\n};\n","import React, { useState, useEffect, useRef, useCallback, useMemo, type ReactNode } from 'react';\nimport {\n MAX_CANVAS_WIDTH,\n trackKind,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n type ArrangementTrack,\n type SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport {\n getColorMap,\n getFrequencyScale,\n createSpectrogramWorkerPool,\n SpectrogramAbortError,\n type SpectrogramWorkerApi,\n} from '@dawcore/spectrogram';\nimport {\n extractChunkNumber,\n parseCanvasId,\n presentChunkIndices,\n groupContiguousIndices,\n classifyChunkTiers,\n computeChunkSampleRange,\n resolveRenderMode,\n buildConfigKey,\n mapsDiffer,\n registeredClipRange,\n resolveClipRange,\n type ChunkTiers,\n type RegisteredAudioRange,\n} from './spectrogram-helpers';\nimport { createAudioKeyOf, spectrogramAudio, channelData } from './audioRegistration';\nimport { useStableByContent } from './useStableByContent';\nimport { spectrogramMenuItems } from './components';\nimport { SpectrogramSettingsModal } from './components';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '@waveform-playlist/browser';\nimport {\n useArrangement,\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n} from '@waveform-playlist/browser';\n\nexport interface SpectrogramProviderProps {\n config?: SpectrogramConfig;\n colorMap?: ColorMapValue;\n /** Number of Web Workers for parallel FFT computation. Defaults to 2 (one per stereo channel). */\n workerPoolSize?: number;\n children: ReactNode;\n}\n\nexport const SpectrogramProvider: React.FC<SpectrogramProviderProps> = ({\n config,\n colorMap,\n workerPoolSize,\n children,\n}) => {\n // By content: the guide writes `config={{ … }}` inline (#821).\n const spectrogramConfig = useStableByContent(config);\n const spectrogramColorMap = useStableByContent(colorMap);\n const { mono } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { tracks } = usePlaylistTimeline();\n const { scrollContainerRef } = usePlaybackControls();\n // The owner of each track's render mode, spectrogram config and colour map\n // (#814): the setters below change the track, and everything here reads it.\n const arrangement = useArrangement();\n\n // OffscreenCanvas registry for worker-rendered spectrograms\n const spectrogramCanvasRegistryRef = useRef<\n Map<string, Map<number, { canvasIds: string[]; canvasWidths: number[] }>>\n >(new Map());\n // The height each canvas registered with, by canvas id. The row height is an\n // option of the view (#689), so this provider, which sits above the views,\n // learns it from the canvases: a view draws at its own height, and in\n // \"both\" mode a canvas is half a row tall.\n const canvasHeightsRef = useRef<Map<string, number>>(new Map());\n // The range of the audio each canvas registered with, by canvas id: the view\n // draws a trim being dragged before the tracks have it (#812), so a clip is\n // rendered for the range its canvases were drawn for, not the track's. Kept\n // only as part of the registration and never written anywhere else.\n const canvasRangesRef = useRef<Map<string, RegisteredAudioRange>>(new Map());\n const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = useState(0);\n\n // Spectrogram refs\n const prevSpectrogramConfigRef = useRef<Map<string, string>>(new Map());\n const spectrogramWorkerRef = useRef<SpectrogramWorkerApi | null>(null);\n const spectrogramGenerationRef = useRef(0);\n const prevCanvasVersionRef = useRef(0);\n const backgroundRenderAbortRef = useRef<{ aborted: boolean } | null>(null);\n // One key per AudioBuffer: clips that share a buffer share its registration.\n const [audioKeyOf] = useState(createAudioKeyOf);\n\n // The one place the pool is made: lazily, on the first need. The pool is\n // created once; a later workerPoolSize applies only to a pool made after a\n // cleanup terminated this one.\n const ensureWorkerPool = useCallback((): SpectrogramWorkerApi | null => {\n if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;\n try {\n const pool = createSpectrogramWorkerPool(\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n }),\n workerPoolSize\n );\n spectrogramWorkerRef.current = pool;\n return pool;\n } catch (err) {\n console.warn(\n `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`\n );\n return null;\n }\n }, [workerPoolSize]);\n\n // Terminate the pool in every cleanup: an unmount, and also when React keeps\n // the component and runs its effects again (a hidden <Activity> shown again,\n // StrictMode). What the pool held goes with it; the effects below ask the\n // next pool what it holds (#821).\n useEffect(() => {\n return () => {\n spectrogramWorkerRef.current?.terminate();\n spectrogramWorkerRef.current = null;\n };\n }, []);\n\n // Pre-register with the pool the audio of every clip on a track that draws a\n // spectrogram, once per buffer, and release what no such clip uses any more.\n // The pool is the one owner of what it holds (`registeredAudioClipIds`).\n // Not gated on the playlist's isReady: a track whose audio is decoded draws\n // while others still load, and its FFT requests would carry its audio.\n useEffect(() => {\n const wanted = spectrogramAudio(tracks, audioKeyOf);\n // Nothing wanted and no pool yet: nothing to release, and no pool to make.\n const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;\n if (!pool) return;\n\n const held = new Set(pool.registeredAudioClipIds());\n for (const [key, buffer] of wanted) {\n if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);\n }\n for (const key of held) {\n if (!wanted.has(key)) pool.unregisterAudioData(key);\n }\n }, [tracks, audioKeyOf, ensureWorkerPool]);\n\n // Main spectrogram computation effect\n useEffect(() => {\n if (tracks.length === 0) return;\n\n const currentKeys = new Map<string, string>();\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n const cfg = track.spectrogramConfig ?? spectrogramConfig;\n const cm = track.spectrogramColorMap ?? spectrogramColorMap;\n currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));\n });\n\n const prevKeys = prevSpectrogramConfigRef.current;\n const configChanged = mapsDiffer(prevKeys, currentKeys);\n\n const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;\n prevCanvasVersionRef.current = spectrogramCanvasVersion;\n\n if (!configChanged && !canvasVersionChanged) return;\n\n if (configChanged) {\n prevSpectrogramConfigRef.current = currentKeys;\n }\n\n if (backgroundRenderAbortRef.current) {\n backgroundRenderAbortRef.current.aborted = true;\n }\n\n const generation = ++spectrogramGenerationRef.current;\n\n const workerApi = ensureWorkerPool();\n if (!workerApi) return;\n // Tell the worker to abort any in-flight FFT from previous generations\n workerApi.abortGeneration(generation);\n\n // Every clip of a track whose look changed or whose canvases registered.\n // A clip whose FFT the worker already has costs a cache hit, not an FFT.\n const clipsToRender: Array<{\n clipId: string;\n /** The key the clip's audio is registered under: one per AudioBuffer. */\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n clipStartSample: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }> = [];\n\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n\n const trackConfigChanged =\n configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);\n const hasRegisteredCanvases =\n canvasVersionChanged &&\n track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));\n if (!trackConfigChanged && !hasRegisteredCanvases) return;\n\n const cfg = track.spectrogramConfig ?? spectrogramConfig ?? {};\n const cm = track.spectrogramColorMap ?? spectrogramColorMap ?? 'viridis';\n\n for (const clip of track.clips) {\n if (!clip.audioBuffer) continue;\n\n const monoFlag = mono || clip.audioBuffer.numberOfChannels === 1;\n const { offsetSamples, durationSamples } = resolveClipRange(\n clip,\n registeredClipRange(\n spectrogramCanvasRegistryRef.current.get(clip.id),\n canvasRangesRef.current\n )\n );\n\n clipsToRender.push({\n clipId: clip.id,\n audioKey: audioKeyOf(clip.audioBuffer),\n channelDataArrays: channelData(clip.audioBuffer),\n config: cfg,\n sampleRate: clip.audioBuffer.sampleRate,\n offsetSamples,\n durationSamples,\n clipStartSample: clip.startSample,\n monoFlag,\n colorMap: cm,\n });\n }\n });\n\n if (clipsToRender.length === 0) return;\n\n // Three-tier chunk classification:\n // - viewportIndices: chunks intersecting the exact viewport (phase 1a — fast first paint)\n // - bufferIndices: chunks in the 1.5× overscan buffer but outside viewport (phase 1b)\n // - remainingIndices: chunks outside the buffer (phase 2 — background batches)\n const getVisibleChunkRange = (\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n clipPixelOffset = 0\n ): ChunkTiers => {\n const container = scrollContainerRef.current;\n return classifyChunkTiers(\n channelInfo,\n clipPixelOffset,\n container\n ? { scrollLeft: container.scrollLeft, viewportWidth: container.clientWidth }\n : null\n );\n };\n\n const renderChunkSubset = async (\n api: SpectrogramWorkerApi,\n cacheKey: string,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n requestedIndices: number[],\n item: { config: SpectrogramConfig; colorMap: ColorMapValue },\n channelIndex: number,\n gen: number\n ) => {\n // Indices are derived from channel 0's registry; this channel may have\n // registered fewer canvases so far (#562). Skipped chunks render on the\n // next pass — registration bumps spectrogramCanvasVersion.\n const indices = presentChunkIndices(channelInfo, requestedIndices);\n if (indices.length === 0) return;\n\n const canvasIds = indices.map((i) => channelInfo.canvasIds[i]);\n const canvasWidths = indices.map((i) => channelInfo.canvasWidths[i]);\n // The chunks of one channel are all as tall as the first.\n const canvasHeight = canvasHeightsRef.current.get(canvasIds[0]);\n if (canvasHeight === undefined) return;\n\n // Compute correct global pixel offsets by extracting chunk numbers from\n // canvas IDs. With virtual scrolling, the registry may contain non-consecutive\n // chunks (e.g., chunks 50-55), so summing widths from index 0 gives wrong offsets.\n const globalPixelOffsets: number[] = [];\n for (const idx of indices) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[idx]);\n globalPixelOffsets.push(chunkNumber * MAX_CANVAS_WIDTH);\n }\n\n const colorLUT = getColorMap(item.colorMap);\n\n await api.renderChunks(\n {\n cacheKey,\n canvasIds,\n canvasWidths,\n globalPixelOffsets,\n canvasHeight,\n devicePixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio : 1,\n samplesPerPixel,\n colorLUT,\n frequencyScale: item.config.frequencyScale ?? 'mel',\n minFrequency: item.config.minFrequency ?? 0,\n maxFrequency: item.config.maxFrequency ?? 0,\n gainDb: item.config.gainDb ?? 20,\n rangeDb: item.config.rangeDb ?? 80,\n channelIndex,\n },\n gen\n );\n };\n\n // Compute FFT for the sample range covered by a set of chunk indices.\n // Returns the cache key (data covers all channels).\n // This avoids computing a single full-clip FFT (which OOMs on 1hr+ files)\n // by computing per-batch ranges on demand.\n const computeFFTForChunks = async (\n api: SpectrogramWorkerApi,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n indices: number[],\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n },\n gen: number\n ): Promise<string> => {\n // Determine the (window-padded) sample range these chunks cover.\n const { paddedStart, paddedEnd } = computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize: item.config.fftSize ?? 2048,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n samplesPerPixel,\n });\n\n const { cacheKey } = await api.computeFFT(\n {\n // The pool's \"clip id\" names the registered audio: the buffer's key.\n clipId: item.audioKey,\n channelDataArrays: item.channelDataArrays,\n config: item.config,\n sampleRate: item.sampleRate,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n mono: item.monoFlag,\n sampleRange: { start: paddedStart, end: paddedEnd },\n },\n gen\n );\n\n return cacheKey;\n };\n\n const computeAsync = async () => {\n const abortToken = { aborted: false };\n backgroundRenderAbortRef.current = abortToken;\n\n // Render off-screen chunks in idle-callback batches, computing FFT\n // per contiguous group to avoid allocating one giant Float32Array for the\n // full clip (which OOMs on 1hr+ files — e.g., 310K frames × 2048 bins = 2.5GB).\n // Groups remaining indices into contiguous runs (e.g., [0,1,4,5] → [0,1]+[4,5])\n // so each FFT only covers the sample range actually needed.\n // Returns true if aborted (caller should return early).\n const renderBackgroundBatches = async (\n channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n remainingIndices: number[];\n }>,\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }\n ): Promise<boolean> => {\n // Collect all contiguous groups across channels, then render\n // each group for ALL channels before moving to the next group\n // (multi-channel fairness — avoids ch1 starvation).\n const allGroups: Array<{\n group: number[];\n channelRangeEntries: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n }>;\n }> = [];\n\n // Build contiguous groups from the first channel's remaining indices\n // (all channels have the same chunk layout).\n if (channelRanges.length > 0) {\n const { channelInfo, remainingIndices } = channelRanges[0];\n const groups = groupContiguousIndices(channelInfo, remainingIndices);\n for (const group of groups) {\n allGroups.push({\n group,\n channelRangeEntries: channelRanges.map(({ ch, channelInfo: ci }) => ({\n ch,\n channelInfo: ci,\n })),\n });\n }\n }\n\n for (const { group, channelRangeEntries } of allGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n await new Promise<void>((resolve) => {\n if (typeof requestIdleCallback === 'function') {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n // Compute FFT once for this contiguous group (covers all channels)\n const { channelInfo: firstChannelInfo } = channelRangeEntries[0];\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n firstChannelInfo,\n group,\n item,\n generation\n );\n\n // Render all channels from the cached FFT data\n for (const { ch, channelInfo: ci } of channelRangeEntries) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n await renderChunkSubset(workerApi!, cacheKey, ci, group, item, ch, generation);\n }\n }\n return false;\n };\n\n for (const item of clipsToRender) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n try {\n const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);\n if (clipCanvasInfo && clipCanvasInfo.size > 0) {\n const numChannels = item.monoFlag ? 1 : item.channelDataArrays.length;\n const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);\n\n // Three-phase rendering:\n // Phase 1a: viewport-only chunks (fast first paint)\n // Phase 1b: buffer-zone chunks (prevents black chunks on scroll)\n // Phase 2: off-screen chunks (background batches)\n const channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n viewportIndices: number[];\n bufferIndices: number[];\n remainingIndices: number[];\n }> = [];\n\n for (let ch = 0; ch < numChannels; ch++) {\n const channelInfo = clipCanvasInfo.get(ch);\n if (!channelInfo) continue;\n const range = getVisibleChunkRange(channelInfo, clipPixelOffset);\n channelRanges.push({ ch, channelInfo, ...range });\n }\n\n // Phase 1a: Compute FFT for viewport chunks only, render all channels\n if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n channelRanges[0].viewportIndices,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo, viewportIndices } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n viewportIndices,\n item,\n ch,\n generation\n );\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 1b: Compute FFT for buffer-zone chunks, render all channels.\n // Buffer indices may be non-contiguous (e.g., chunks [10,14,15] from\n // indices [0,3,4,5]), so group them to avoid spanning a huge FFT range.\n if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {\n const bufferGroups = groupContiguousIndices(\n channelRanges[0].channelInfo,\n channelRanges[0].bufferIndices\n );\n\n for (const group of bufferGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n group,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n group,\n item,\n ch,\n generation\n );\n }\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 2: Render off-screen chunks in background batches\n // (each batch computes its own bounded FFT range).\n if (await renderBackgroundBatches(channelRanges, item)) return;\n }\n } catch (err) {\n if (err instanceof SpectrogramAbortError) return;\n console.warn(\n `[waveform-playlist] Spectrogram worker error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n };\n\n computeAsync().catch((err) => {\n console.error(\n `[waveform-playlist] Spectrogram computation failed: ${err instanceof Error ? err.message : String(err)}`\n );\n });\n }, [\n tracks,\n mono,\n spectrogramConfig,\n spectrogramColorMap,\n samplesPerPixel,\n spectrogramCanvasVersion,\n scrollContainerRef,\n audioKeyOf,\n ensureWorkerPool,\n ]);\n\n // Setters: each a change of the track in the arrangement, so an undo step\n // (#814). Returning the track as it is changes nothing and pushes no step:\n // the mode it is already drawn with (an unset one is 'waveform'), and any\n // mode for a MIDI track, which is drawn as a piano roll (review of #930).\n const setTrackRenderMode = useCallback(\n (trackId: string, mode: RenderMode) => {\n arrangement.updateTrack(trackId, (track: ArrangementTrack) =>\n trackKind(track) === 'midi' || resolveRenderMode(track.renderMode) === mode\n ? track\n : { ...track, renderMode: mode }\n );\n },\n [arrangement]\n );\n\n const setTrackSpectrogramConfig = useCallback(\n (trackId: string, config: SpectrogramConfig, colorMap?: ColorMapValue) => {\n // The render mode is left as it is (review of #926).\n arrangement.updateTrack(trackId, (track: ArrangementTrack) => ({\n ...track,\n spectrogramConfig: config,\n spectrogramColorMap: colorMap ?? track.spectrogramColorMap,\n }));\n },\n [arrangement]\n );\n\n const registerSpectrogramCanvas = useCallback(\n (reg: SpectrogramCanvasRegistration) => {\n const pool = ensureWorkerPool();\n if (!pool) return;\n\n try {\n pool.registerCanvas(reg.canvasId, reg.canvas);\n } catch (err) {\n console.warn(\n `[waveform-playlist] registerCanvas failed for ${reg.canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n return;\n }\n\n canvasHeightsRef.current.set(reg.canvasId, reg.heightPx);\n if (reg.offsetSamples !== undefined || reg.durationSamples !== undefined) {\n canvasRangesRef.current.set(reg.canvasId, {\n offsetSamples: reg.offsetSamples,\n durationSamples: reg.durationSamples,\n });\n } else {\n canvasRangesRef.current.delete(reg.canvasId);\n }\n const registry = spectrogramCanvasRegistryRef.current;\n if (!registry.has(reg.clipId)) {\n registry.set(reg.clipId, new Map());\n }\n const perClip = registry.get(reg.clipId)!;\n const entry = perClip.get(reg.channelIndex) ?? { canvasIds: [], canvasWidths: [] };\n const existingIdx = entry.canvasIds.indexOf(reg.canvasId);\n if (existingIdx >= 0) {\n entry.canvasWidths[existingIdx] = reg.widthPx;\n } else {\n entry.canvasIds.push(reg.canvasId);\n entry.canvasWidths.push(reg.widthPx);\n }\n perClip.set(reg.channelIndex, entry);\n setSpectrogramCanvasVersion((v) => v + 1);\n },\n [ensureWorkerPool]\n );\n\n const unregisterSpectrogramCanvas = useCallback((canvasId: string) => {\n canvasHeightsRef.current.delete(canvasId);\n canvasRangesRef.current.delete(canvasId);\n const pool = spectrogramWorkerRef.current;\n if (pool) {\n try {\n pool.unregisterCanvas(canvasId);\n } catch (err) {\n console.warn(\n `[waveform-playlist] unregisterCanvas failed for ${canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Canvas IDs follow the format `${clipId}-ch${channelIndex}-chunk${n}`.\n const parsed = parseCanvasId(canvasId);\n if (!parsed) return;\n const { clipId, channelIndex } = parsed;\n\n const registry = spectrogramCanvasRegistryRef.current;\n const perClip = registry.get(clipId);\n if (!perClip) return;\n const entry = perClip.get(channelIndex);\n if (!entry) return;\n const idx = entry.canvasIds.indexOf(canvasId);\n if (idx >= 0) {\n entry.canvasIds.splice(idx, 1);\n entry.canvasWidths.splice(idx, 1);\n }\n if (entry.canvasIds.length === 0) {\n perClip.delete(channelIndex);\n }\n if (perClip.size === 0) {\n registry.delete(clipId);\n }\n setSpectrogramCanvasVersion((v) => v + 1);\n }, []);\n\n const renderMenuItems = useCallback(\n (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => {\n return spectrogramMenuItems({\n renderMode: props.renderMode as RenderMode,\n onRenderModeChange: props.onRenderModeChange,\n onOpenSettings: props.onOpenSettings,\n onClose: props.onClose,\n });\n },\n []\n );\n\n const value: SpectrogramIntegration = useMemo(\n () => ({\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n SettingsModal: SpectrogramSettingsModal,\n getColorMap,\n getFrequencyScale: getFrequencyScale as (\n name: string\n ) => (f: number, minF: number, maxF: number) => number,\n }),\n [\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n ]\n );\n\n return <SpectrogramIntegrationContext value={value}>{children}</SpectrogramIntegrationContext>;\n};\n","import {\n MAX_CANVAS_WIDTH,\n parseSpectrogramCanvasId,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n} from '@waveform-playlist/core';\nimport { computePaddedFftRange } from '@dawcore/spectrogram';\n\n/**\n * Pure, side-effect-free helpers extracted from `SpectrogramProvider`.\n *\n * These cover the geometry/key logic that the provider's worker-orchestration\n * effect depends on (chunk classification, FFT sample ranges, contiguous\n * grouping, config-change detection). Keeping them DOM-free makes them unit\n * testable in a Node environment — the provider supplies the imperative shell\n * (refs, worker calls, React state) around this functional core.\n */\n\n/** A channel's registered canvas chunks: parallel arrays of IDs and pixel widths. */\nexport interface ChannelChunkInfo {\n canvasIds: string[];\n canvasWidths: number[];\n}\n\n/** Chunk indices grouped by their relationship to the current scroll viewport. */\nexport interface ChunkTiers {\n /** Chunks intersecting the exact viewport — fast first paint. */\n viewportIndices: number[];\n /** Chunks within the 1.5× overscan buffer but outside the viewport. */\n bufferIndices: number[];\n /** Chunks outside the buffer — rendered in background batches. */\n remainingIndices: number[];\n}\n\n/** Scroll-container metrics needed to classify chunks. `null` ⇒ no container yet. */\nexport interface ViewportMetrics {\n scrollLeft: number;\n viewportWidth: number;\n}\n\n/**\n * Extract the chunk number from a canvas ID like `\"clipId-ch0-chunk5\"` → `5`.\n * Delegates to the canonical `parseSpectrogramCanvasId`; warns and returns `0`\n * when the ID doesn't match the `${clipId}-ch${channelIndex}-chunk${n}` format.\n */\nexport function extractChunkNumber(canvasId: string): number {\n const parsed = parseSpectrogramCanvasId(canvasId);\n if (!parsed) {\n console.warn(`[spectrogram] Unexpected canvas ID format: ${canvasId}`);\n return 0;\n }\n return parsed.chunkIndex;\n}\n\n/**\n * Keep only indices whose canvas is registered for THIS channel.\n *\n * Chunk indices are derived once from channel 0's registry and reused across\n * channels, but canvases register progressively per channel — a later channel\n * can briefly hold fewer entries, and indexing past its registry threw\n * `Cannot read properties of undefined (reading 'match')` (#562). Skipped\n * chunks render on the next pass: registration bumps `spectrogramCanvasVersion`.\n */\nexport function presentChunkIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[] {\n return indices.filter((i) => channelInfo.canvasIds[i] !== undefined);\n}\n\n/**\n * Parse a canvas ID of the form `${clipId}-ch${channelIndex}-chunk${n}` into its\n * clip ID and channel index. Returns `null` when the ID doesn't match.\n */\nexport function parseCanvasId(canvasId: string): { clipId: string; channelIndex: number } | null {\n const parsed = parseSpectrogramCanvasId(canvasId);\n return parsed ? { clipId: parsed.clipId, channelIndex: parsed.channelIndex } : null;\n}\n\n/**\n * Split indices into contiguous groups based on their chunk numbers, e.g.\n * indices mapping to chunks `[0,1,4,5]` → `[[0,1],[4,5]]`. Prevents computing an\n * FFT range that spans the gap between non-adjacent chunks.\n */\nexport function groupContiguousIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[][] {\n if (indices.length === 0) return [];\n const groups: number[][] = [];\n let currentGroup = [indices[0]];\n let prevChunk = extractChunkNumber(channelInfo.canvasIds[indices[0]]);\n for (let i = 1; i < indices.length; i++) {\n const chunk = extractChunkNumber(channelInfo.canvasIds[indices[i]]);\n if (chunk === prevChunk + 1) {\n currentGroup.push(indices[i]);\n } else {\n groups.push(currentGroup);\n currentGroup = [indices[i]];\n }\n prevChunk = chunk;\n }\n groups.push(currentGroup);\n return groups;\n}\n\n/**\n * Classify a channel's chunks into viewport / buffer / remaining tiers.\n *\n * The buffer uses a 1.5× viewport-width overscan to match\n * `useVisibleChunkIndices` in ScrollViewport, so FFT covers every mounted\n * canvas. When `viewport` is `null` (no scroll container yet), every chunk is\n * treated as in-viewport.\n */\nexport function classifyChunkTiers(\n channelInfo: ChannelChunkInfo,\n clipPixelOffset = 0,\n viewport: ViewportMetrics | null\n): ChunkTiers {\n if (!viewport) {\n return {\n viewportIndices: channelInfo.canvasWidths.map((_, i) => i),\n bufferIndices: [],\n remainingIndices: [],\n };\n }\n\n const { scrollLeft, viewportWidth } = viewport;\n const buffer = viewportWidth * 1.5;\n const bufferStart = Math.max(0, scrollLeft - buffer);\n const bufferEnd = scrollLeft + viewportWidth + buffer;\n\n const viewportIndices: number[] = [];\n const bufferIndices: number[] = [];\n const remainingIndices: number[] = [];\n\n for (let i = 0; i < channelInfo.canvasWidths.length; i++) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[i]);\n const chunkLeft = chunkNumber * MAX_CANVAS_WIDTH + clipPixelOffset;\n const chunkRight = chunkLeft + channelInfo.canvasWidths[i];\n if (chunkRight > scrollLeft && chunkLeft < scrollLeft + viewportWidth) {\n viewportIndices.push(i);\n } else if (chunkRight > bufferStart && chunkLeft < bufferEnd) {\n bufferIndices.push(i);\n } else {\n remainingIndices.push(i);\n }\n }\n\n return { viewportIndices, bufferIndices, remainingIndices };\n}\n\nexport interface ChunkSampleRangeParams {\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n indices: number[];\n /** FFT window size (samples) used to pad the range against edge artifacts. */\n fftSize: number;\n offsetSamples: number;\n durationSamples: number;\n samplesPerPixel: number;\n}\n\n/**\n * Compute the (window-padded, clip-clamped) sample range covered by a set of\n * chunk indices. Computing per-batch ranges on demand avoids allocating one\n * giant FFT array for a full clip (which OOMs on 1hr+ files).\n */\nexport function computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n}: ChunkSampleRangeParams): { paddedStart: number; paddedEnd: number } {\n return computePaddedFftRange({\n chunks: indices.map((i) => ({\n chunkIndex: extractChunkNumber(channelInfo.canvasIds[i]),\n widthPx: channelInfo.canvasWidths[i],\n })),\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n });\n}\n\n/** Resolve a track's effective render mode: the track's own, else `'waveform'`. */\nexport function resolveRenderMode(trackRenderMode: RenderMode | undefined): RenderMode {\n return trackRenderMode ?? 'waveform';\n}\n\n/**\n * Stable string key for a track's full spectrogram appearance (mode + config +\n * color map + mono). A change means the rendered output must be recomputed.\n */\nexport function buildConfigKey(params: {\n mode: RenderMode;\n cfg: SpectrogramConfig | undefined;\n cm: ColorMapValue | undefined;\n mono: boolean;\n}): string {\n const { mode, cfg, cm, mono } = params;\n return JSON.stringify({ mode, cfg, cm, mono });\n}\n\n/**\n * Whether two key maps differ — different size, or any key present in `current`\n * whose value doesn't match `prev`. Used to detect config/FFT changes between\n * effect runs.\n */\nexport function mapsDiffer(prev: Map<string, string>, current: Map<string, string>): boolean {\n if (current.size !== prev.size) return true;\n for (const [key, value] of current) {\n if (prev.get(key) !== value) return true;\n }\n return false;\n}\n\n/** The range of the audio a canvas registered with (`SpectrogramCanvasRegistration`). */\nexport interface RegisteredAudioRange {\n offsetSamples?: number;\n durationSamples?: number;\n}\n\n/**\n * The range a clip's canvases registered with: that of the first canvas that\n * gave one (all canvases of a clip are drawn for the same range; a new range\n * registers new canvases). `undefined` when none gave one.\n */\nexport function registeredClipRange(\n perClip: ReadonlyMap<number, ChannelChunkInfo> | undefined,\n rangeByCanvasId: ReadonlyMap<string, RegisteredAudioRange>\n): RegisteredAudioRange | undefined {\n if (!perClip) return undefined;\n for (const channelInfo of perClip.values()) {\n for (const canvasId of channelInfo.canvasIds) {\n const range = rangeByCanvasId.get(canvasId);\n if (range) return range;\n }\n }\n return undefined;\n}\n\n/**\n * The range to draw a clip for: what its canvases registered with (the view\n * may draw a clip the tracks do not have yet, a trim being dragged), field by\n * field, else the clip's own.\n */\nexport function resolveClipRange(\n clip: { offsetSamples: number; durationSamples: number },\n registered: RegisteredAudioRange | undefined\n): { offsetSamples: number; durationSamples: number } {\n return {\n offsetSamples: registered?.offsetSamples ?? clip.offsetSamples,\n durationSamples: registered?.durationSamples ?? clip.durationSamples,\n };\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\nimport { resolveRenderMode } from './spectrogram-helpers';\n\n/**\n * The key an AudioBuffer's audio is registered under in the worker pool, the\n * same for as long as the buffer lives. Clips that share a buffer share the\n * key (a split keeps one buffer for both halves), so the pool holds the audio\n * once (#821). The worker's FFT cache key also carries each clip's range, so\n * two clips over different parts of one buffer keep separate entries.\n */\nexport type AudioKeyOf = (buffer: AudioBuffer) => string;\n\nexport function createAudioKeyOf(): AudioKeyOf {\n const keys = new WeakMap<AudioBuffer, string>();\n let next = 0;\n return (buffer) => {\n const existing = keys.get(buffer);\n if (existing !== undefined) return existing;\n next += 1;\n const key = `audio-${next}`;\n keys.set(buffer, key);\n return key;\n };\n}\n\n/**\n * The audio the pool should hold, by key: each buffer that a clip on a track\n * drawing a spectrogram (`spectrogram` or `both`) uses. A waveform track's\n * audio is never computed, so it is not sent (#821).\n */\nexport function spectrogramAudio(\n tracks: readonly ClipTrack[],\n audioKeyOf: AudioKeyOf\n): Map<string, AudioBuffer> {\n const wanted = new Map<string, AudioBuffer>();\n for (const track of tracks) {\n if (resolveRenderMode(track.renderMode) === 'waveform') continue;\n for (const clip of track.clips) {\n if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);\n }\n }\n return wanted;\n}\n\n/** Every channel of a buffer, as the views `getChannelData` returns (not copies). */\nexport function channelData(buffer: AudioBuffer): Float32Array[] {\n return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));\n}\n","import { useMemo } from 'react';\n\n/**\n * The value as it was the last time its JSON content changed. For plain-data\n * props an app often writes inline (`config={{ fftSize: 2048 }}`): a new\n * object with the same content keeps the old one, so the context value and\n * the effects that depend on it do not change on every render of the app\n * (#821). Only for values JSON describes completely (no functions, no class\n * instances); a key whose value is `undefined` counts as absent.\n */\nexport function useStableByContent<T>(value: T): T {\n const content = JSON.stringify(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the content, not the identity\n return useMemo(() => value, [content]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,+BAAmB;AA6ET;AArEV,IAAM,eAAe,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS5B,IAAM,aAAa,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa1B,IAAM,iBAAiB,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAe9B,IAAM,kBAAkB,yBAAAA,QAAO;AAAA;AAAA;AAI/B,IAAM,eAAuD;AAAA,EAC3D,EAAE,OAAO,YAAY,OAAO,WAAW;AAAA,EACvC,EAAE,OAAO,eAAe,OAAO,cAAc;AAAA,EAC7C,EAAE,OAAO,QAAQ,OAAO,OAAO;AACjC;AAaO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA2C;AACzC,SAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,SACE,6CAAC,mBACC;AAAA,oDAAC,gBAAa,qBAAO;AAAA,QACpB,aAAa,IAAI,CAAC,EAAE,OAAO,MAAM,MAChC,6CAAC,cACC;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAK;AAAA,cACL,SAAS,eAAe;AAAA,cACxB,UAAU,MAAM;AACd,mCAA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Q,aAAa,IAAI;AAEjC,UAAM,WAAW,6BAA6B;AAC9C,UAAM,UAAU,SAAS,IAAI,MAAM;AACnC,QAAI,CAAC,QAAS;AACd,UAAM,QAAQ,QAAQ,IAAI,YAAY;AACtC,QAAI,CAAC,MAAO;AACZ,UAAM,MAAM,MAAM,UAAU,QAAQ,QAAQ;AAC5C,QAAI,OAAO,GAAG;AACZ,YAAM,UAAU,OAAO,KAAK,CAAC;AAC7B,YAAM,aAAa,OAAO,KAAK,CAAC;AAAA,IAClC;AACA,QAAI,MAAM,UAAU,WAAW,GAAG;AAChC,cAAQ,OAAO,YAAY;AAAA,IAC7B;AACA,QAAI,QAAQ,SAAS,GAAG;AACtB,eAAS,OAAO,MAAM;AAAA,IACxB;AACA,gCAA4B,CAAC,MAAM,IAAI,CAAC;AAAA,EAC1C,GAAG,CAAC,CAAC;AAEL,QAAM,sBAAkB;AAAA,IACtB,CAAC,UAKK;AACJ,aAAO,qBAAqB;AAAA,QAC1B,YAAY,MAAM;AAAA,QAClB,oBAAoB,MAAM;AAAA,QAC1B,gBAAgB,MAAM;AAAA,QACtB,SAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,YAAgC;AAAA,IACpC,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA,mBAAmB;AAAA,IAGrB;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,6CAAC,gDAA8B,OAAe,UAAS;AAChE;","names":["styled","import_styled_components","import_jsx_runtime","styled","import_react","import_core","import_spectrogram","import_core","import_react","import_browser","import_jsx_runtime","config","colorMap"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/components/SpectrogramMenuItems.tsx","../src/components/SpectrogramSettingsModal.tsx","../src/SpectrogramProvider.tsx","../src/spectrogram-helpers.ts","../src/audioRegistration.ts","../src/useStableByContent.ts"],"sourcesContent":["// React surface — computation/worker primitives live in @dawcore/spectrogram.\nexport { spectrogramMenuItems } from './components';\nexport type { SpectrogramMenuItemsOptions } from './components';\nexport { SpectrogramSettingsModal } from './components';\nexport type { SpectrogramSettingsModalProps } from './components';\n\nexport { SpectrogramProvider } from './SpectrogramProvider';\nexport type { SpectrogramProviderProps } from './SpectrogramProvider';\n","import React from 'react';\nimport styled from 'styled-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport type { SpectrogramIntegration } from '@waveform-playlist/browser';\n\n/** The items browser's track menu asks the spectrogram integration for:\n * ui-components' `TrackMenuItem[]`, named through the type that carries it. */\ntype MenuItems = ReturnType<NonNullable<SpectrogramIntegration['renderMenuItems']>>;\n\nconst SectionLabel = styled.div`\n font-size: 0.65rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.5;\n margin-bottom: 0.25rem;\n`;\n\nconst RadioLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n padding: 0.2rem 0;\n font-size: 0.8rem;\n cursor: pointer;\n\n &:hover {\n opacity: 0.8;\n }\n`;\n\nconst SettingsButton = styled.button`\n background: none;\n border: none;\n color: inherit;\n cursor: pointer;\n font-size: 0.8rem;\n padding: 0.35rem 0.75rem;\n width: 100%;\n text-align: left;\n\n &:hover {\n background: rgba(128, 128, 128, 0.15);\n }\n`;\n\nconst DropdownSection = styled.div`\n padding: 0.25rem 0.75rem;\n`;\n\nconst RENDER_MODES: { value: RenderMode; label: string }[] = [\n { value: 'waveform', label: 'Waveform' },\n { value: 'spectrogram', label: 'Spectrogram' },\n { value: 'both', label: 'Both' },\n];\n\nexport interface SpectrogramMenuItemsOptions {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Returns the track menu items (`TrackMenuItem[]` of ui-components) for the\n * spectrogram display mode radios and settings button.\n */\nexport function spectrogramMenuItems({\n renderMode,\n onRenderModeChange,\n onOpenSettings,\n onClose,\n}: SpectrogramMenuItemsOptions): MenuItems {\n return [\n {\n id: 'spectrogram-display',\n content: (\n <DropdownSection>\n <SectionLabel>Display</SectionLabel>\n {RENDER_MODES.map(({ value, label }) => (\n <RadioLabel key={value}>\n <input\n type=\"radio\"\n name=\"render-mode\"\n checked={renderMode === value}\n onChange={() => {\n onRenderModeChange(value);\n onClose?.();\n }}\n />\n {label}\n </RadioLabel>\n ))}\n </DropdownSection>\n ),\n },\n {\n id: 'spectrogram-settings',\n content: (\n <SettingsButton\n onClick={(e) => {\n e.stopPropagation();\n onClose?.();\n onOpenSettings();\n }}\n onMouseDown={(e) => e.stopPropagation()}\n >\n Spectrogram Settings...\n </SettingsButton>\n ),\n },\n ];\n}\n","import React, { useRef, useEffect, useId, useLayoutEffect, useState } from 'react';\nimport styled from 'styled-components';\nimport {\n SPECTROGRAM_DEFAULTS,\n type SpectrogramConfig,\n type ColorMapValue,\n type ColorMapName,\n type FFTSize,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramSettingsModalProps {\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n /**\n * Called on Apply with the config it was given plus the fields the user\n * changed, and the colour map (the one given unless the user picked one).\n * Not called when nothing was changed: Apply then only closes.\n */\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n /**\n * The sample rate of the audio. With a config that has no `maxFrequency`,\n * the field shows half of it, the top the spectrogram is drawn to.\n */\n sampleRate?: number;\n}\n\nconst StyledDialog = styled.dialog`\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 8px;\n padding: 1.5rem;\n background: ${(p) => p.theme.timescaleBackgroundColor ?? '#222'};\n color: ${(p) => p.theme.textColor ?? 'inherit'};\n min-width: 380px;\n max-width: 500px;\n overscroll-behavior: contain;\n\n &::backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n`;\n\nconst Title = styled.h3`\n margin: 0 0 1rem;\n font-size: 1rem;\n`;\n\nconst FormGrid = styled.div`\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n`;\n\nconst Field = styled.div<{ $span?: boolean }>`\n display: flex;\n flex-direction: column;\n gap: 0.2rem;\n grid-column: ${(p) => (p.$span ? '1 / -1' : 'auto')};\n`;\n\nconst Label = styled.label`\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.6;\n`;\n\nconst Select = styled.select`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n`;\n\nconst NumberInput = styled.input`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n width: 100%;\n box-sizing: border-box;\n`;\n\nconst CheckboxLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n font-size: 0.85rem;\n cursor: pointer;\n`;\n\nconst ButtonRow = styled.div`\n display: flex;\n justify-content: flex-end;\n gap: 0.5rem;\n margin-top: 1.25rem;\n`;\n\nconst ModalButton = styled.button<{ $primary?: boolean }>`\n padding: 0.4rem 1rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n cursor: pointer;\n font-size: 0.85rem;\n background: ${(p) => (p.$primary ? (p.theme.buttonBackground ?? '#0091ff') : 'transparent')};\n color: ${(p) => (p.$primary ? (p.theme.buttonText ?? '#fff') : 'inherit')};\n ${(p) => (p.$primary && p.theme.buttonBorder ? `border-color: ${p.theme.buttonBorder};` : '')}\n\n &:hover {\n ${(p) =>\n p.$primary && p.theme.buttonHoverBackground\n ? `background: ${p.theme.buttonHoverBackground};`\n : 'opacity: 0.85;'}\n }\n`;\n\nconst FFT_SIZES = [256, 512, 1024, 2048, 4096, 8192];\nconst WINDOW_FUNCTIONS = [\n 'hann',\n 'hamming',\n 'blackman',\n 'blackman-harris',\n 'bartlett',\n 'rectangular',\n] as const;\nconst FREQ_SCALES = ['linear', 'logarithmic', 'mel', 'bark', 'erb'] as const;\nconst COLOR_MAPS: ColorMapName[] = ['viridis', 'magma', 'inferno', 'grayscale', 'igray', 'roseus'];\n/** The select's value for a colour map given as an array of colours. */\nconst CUSTOM_COLOR_MAP = 'custom';\n\ntype SettingsFormProps = Omit<SpectrogramSettingsModalProps, 'open'>;\n\n/**\n * The form is a draft of the settings. It is mounted only while the dialog is\n * open, so its state starts from the props each time the dialog opens and is\n * never overwritten by a parent re-render while the user is editing.\n *\n * The draft holds only the fields the user changed (#814). A field shows its\n * edit, else the config's value, else the default; Apply sends the config it\n * was given with the edits on top, so a field the form does not show\n * (`alpha`, `labelsColor`, `labelsBackground`) and a field left at its default\n * (`maxFrequency`: half the sample rate) are not written.\n */\nconst SettingsForm: React.FC<SettingsFormProps> = ({\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const id = useId();\n const [edits, setEdits] = useState<SpectrogramConfig>({});\n const [editedColorMap, setEditedColorMap] = useState<ColorMapName | undefined>(undefined);\n\n const shown = <K extends keyof SpectrogramConfig>(key: K): SpectrogramConfig[K] =>\n key in edits ? edits[key] : config[key];\n const edit = (changes: SpectrogramConfig) => setEdits((prev) => ({ ...prev, ...changes }));\n\n const fftSize = shown('fftSize') ?? SPECTROGRAM_DEFAULTS.fftSize;\n const hopSize = shown('hopSize') ?? Math.floor(fftSize / 4);\n const zeroPadding = shown('zeroPaddingFactor') ?? SPECTROGRAM_DEFAULTS.zeroPaddingFactor;\n const windowFn = shown('windowFunction') ?? SPECTROGRAM_DEFAULTS.windowFunction;\n const freqScale = shown('frequencyScale') ?? SPECTROGRAM_DEFAULTS.frequencyScale;\n const minFreq = shown('minFrequency') ?? SPECTROGRAM_DEFAULTS.minFrequency;\n const nyquist = sampleRate !== undefined ? sampleRate / 2 : undefined;\n // An emptied field stays empty while the user types (Apply then leaves the\n // default); only an untouched one shows the default's number.\n const maxFreq = 'maxFrequency' in edits ? edits.maxFrequency : (config.maxFrequency ?? nyquist);\n const gainDb = shown('gainDb') ?? SPECTROGRAM_DEFAULTS.gainDb;\n const rangeDb = shown('rangeDb') ?? SPECTROGRAM_DEFAULTS.rangeDb;\n const showLabels = shown('labels') ?? SPECTROGRAM_DEFAULTS.labels;\n const isCustomColorMap = typeof colorMap !== 'string';\n const colorMapValue = editedColorMap ?? (isCustomColorMap ? CUSTOM_COLOR_MAP : colorMap);\n\n const handleApply = () => {\n // A field set back to the value it had is no change. With none, Apply\n // only closes: an onApply would be an undo step that changes nothing.\n const configChanged = (Object.keys(edits) as Array<keyof SpectrogramConfig>).some(\n (key) => edits[key] !== config[key]\n );\n const colorMapChanged = editedColorMap !== undefined && editedColorMap !== colorMap;\n if (configChanged || colorMapChanged) {\n onApply({ ...config, ...edits }, editedColorMap ?? colorMap);\n }\n onClose();\n };\n\n return (\n <>\n <FormGrid>\n <Field>\n <Label htmlFor={`${id}-fft-size`}>FFT Size</Label>\n <Select\n id={`${id}-fft-size`}\n value={fftSize}\n onChange={(e) => {\n const v = Number(e.target.value) as FFTSize;\n edit({ fftSize: v, hopSize: Math.floor(v / 4) });\n }}\n >\n {FFT_SIZES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-hop-size`}>Hop Size</Label>\n <Select\n id={`${id}-hop-size`}\n value={hopSize}\n onChange={(e) => edit({ hopSize: Number(e.target.value) })}\n >\n {[\n { label: `${fftSize} (no overlap)`, value: fftSize },\n { label: `${Math.floor(fftSize / 2)} (50%)`, value: Math.floor(fftSize / 2) },\n { label: `${Math.floor(fftSize / 4)} (75%)`, value: Math.floor(fftSize / 4) },\n { label: `${Math.floor(fftSize / 8)} (87.5%)`, value: Math.floor(fftSize / 8) },\n ].map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-zero-padding`}>Zero Padding</Label>\n <Select\n id={`${id}-zero-padding`}\n value={zeroPadding}\n onChange={(e) => edit({ zeroPaddingFactor: Number(e.target.value) })}\n >\n {[1, 2, 4, 8, 16].map((v) => (\n <option key={v} value={v}>\n {v}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-window-function`}>Window Function</Label>\n <Select\n id={`${id}-window-function`}\n value={windowFn}\n onChange={(e) =>\n edit({ windowFunction: e.target.value as SpectrogramConfig['windowFunction'] })\n }\n >\n {WINDOW_FUNCTIONS.map((w) => (\n <option key={w} value={w}>\n {w}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-frequency-scale`}>Frequency Scale</Label>\n <Select\n id={`${id}-frequency-scale`}\n value={freqScale}\n onChange={(e) =>\n edit({ frequencyScale: e.target.value as SpectrogramConfig['frequencyScale'] })\n }\n >\n {FREQ_SCALES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-color-map`}>Color Map</Label>\n <Select\n id={`${id}-color-map`}\n value={colorMapValue}\n onChange={(e) =>\n // \"custom\" is the colour map given (an array): no edit.\n setEditedColorMap(\n e.target.value === CUSTOM_COLOR_MAP ? undefined : (e.target.value as ColorMapName)\n )\n }\n >\n {isCustomColorMap && <option value={CUSTOM_COLOR_MAP}>{CUSTOM_COLOR_MAP}</option>}\n {COLOR_MAPS.map((c) => (\n <option key={c} value={c}>\n {c}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-min-frequency`}>Min Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-min-frequency`}\n type=\"number\"\n min={0}\n max={5000}\n step={50}\n value={minFreq}\n onChange={(e) => edit({ minFrequency: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-max-frequency`}>Max Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-max-frequency`}\n type=\"number\"\n min={1000}\n max={nyquist}\n step={50}\n value={maxFreq ?? ''}\n onChange={(e) =>\n // Emptied: back to the default, half the sample rate.\n edit({ maxFrequency: e.target.value === '' ? undefined : Number(e.target.value) })\n }\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-range-db`}>Range (dB)</Label>\n <NumberInput\n id={`${id}-range-db`}\n type=\"number\"\n min={1}\n max={120}\n step={1}\n value={rangeDb}\n onChange={(e) => edit({ rangeDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-gain-db`}>Gain (dB)</Label>\n <NumberInput\n id={`${id}-gain-db`}\n type=\"number\"\n min={-20}\n max={60}\n step={1}\n value={gainDb}\n onChange={(e) => edit({ gainDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field $span>\n <CheckboxLabel>\n <input\n type=\"checkbox\"\n checked={showLabels}\n onChange={(e) => edit({ labels: e.target.checked })}\n />\n Show Frequency Labels\n </CheckboxLabel>\n </Field>\n </FormGrid>\n\n <ButtonRow>\n <ModalButton type=\"button\" onClick={onClose}>\n Cancel\n </ModalButton>\n <ModalButton type=\"button\" $primary onClick={handleApply}>\n Apply\n </ModalButton>\n </ButtonRow>\n </>\n );\n};\n\nexport const SpectrogramSettingsModal: React.FC<SpectrogramSettingsModalProps> = ({\n open,\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const dialogRef = useRef<HTMLDialogElement>(null);\n const titleId = useId();\n\n // Latest props for the native `close` listener, so the listener is attached\n // once and not re-added whenever the parent passes a new `onClose`.\n const latestRef = useRef({ open, onClose });\n useLayoutEffect(() => {\n latestRef.current = { open, onClose };\n });\n\n // Native close (Escape key)\n useEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n const handleClose = () => {\n // Only report a close the parent did not ask for (avoids double-fire)\n if (latestRef.current.open) {\n latestRef.current.onClose();\n }\n };\n dialog.addEventListener('close', handleClose);\n return () => dialog.removeEventListener('close', handleClose);\n }, []);\n\n // Layout effect: the dialog opens and closes in the same frame as the form\n // mounts and unmounts, whatever triggered the change.\n useLayoutEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n if (open && !dialog.open) {\n dialog.showModal();\n } else if (!open && dialog.open) {\n dialog.close();\n }\n }, [open]);\n\n return (\n <StyledDialog ref={dialogRef} aria-labelledby={titleId}>\n <Title id={titleId}>Spectrogram Settings</Title>\n {open && (\n <SettingsForm\n onClose={onClose}\n config={config}\n colorMap={colorMap}\n onApply={onApply}\n sampleRate={sampleRate}\n />\n )}\n </StyledDialog>\n );\n};\n","import React, { useState, useEffect, useRef, useCallback, useMemo, type ReactNode } from 'react';\nimport {\n MAX_CANVAS_WIDTH,\n trackKind,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n type ArrangementTrack,\n type SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport {\n getColorMap,\n getFrequencyScale,\n createSpectrogramWorkerPool,\n SpectrogramAbortError,\n type SpectrogramWorkerApi,\n} from '@dawcore/spectrogram';\nimport {\n extractChunkNumber,\n parseCanvasId,\n presentChunkIndices,\n groupContiguousIndices,\n classifyChunkTiers,\n computeChunkSampleRange,\n resolveRenderMode,\n buildConfigKey,\n mapsDiffer,\n registeredClipRange,\n resolveClipRange,\n type ChunkTiers,\n type RegisteredAudioRange,\n} from './spectrogram-helpers';\nimport { createAudioKeyOf, spectrogramAudio, channelData } from './audioRegistration';\nimport { useStableByContent } from './useStableByContent';\nimport { spectrogramMenuItems } from './components';\nimport { SpectrogramSettingsModal } from './components';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '@waveform-playlist/browser';\nimport {\n useArrangement,\n usePlaybackControls,\n useAudioSettings,\n useZoom,\n useTimeline,\n} from '@waveform-playlist/browser';\n\nexport interface SpectrogramProviderProps {\n config?: SpectrogramConfig;\n colorMap?: ColorMapValue;\n /** Number of Web Workers for parallel FFT computation. Defaults to 2 (one per stereo channel). */\n workerPoolSize?: number;\n children: ReactNode;\n}\n\nexport const SpectrogramProvider: React.FC<SpectrogramProviderProps> = ({\n config,\n colorMap,\n workerPoolSize,\n children,\n}) => {\n // By content: the guide writes `config={{ … }}` inline (#821).\n const spectrogramConfig = useStableByContent(config);\n const spectrogramColorMap = useStableByContent(colorMap);\n const { mono } = useAudioSettings();\n const { samplesPerPixel } = useZoom();\n const { tracks } = useTimeline();\n const { scrollContainerRef } = usePlaybackControls();\n // The owner of each track's render mode, spectrogram config and colour map\n // (#814): the setters below change the track, and everything here reads it.\n const arrangement = useArrangement();\n\n // OffscreenCanvas registry for worker-rendered spectrograms\n const spectrogramCanvasRegistryRef = useRef<\n Map<string, Map<number, { canvasIds: string[]; canvasWidths: number[] }>>\n >(new Map());\n // The height each canvas registered with, by canvas id. The row height is an\n // option of the view (#689), so this provider, which sits above the views,\n // learns it from the canvases: a view draws at its own height, and in\n // \"both\" mode a canvas is half a row tall.\n const canvasHeightsRef = useRef<Map<string, number>>(new Map());\n // The range of the audio each canvas registered with, by canvas id: the view\n // draws a trim being dragged before the tracks have it (#812), so a clip is\n // rendered for the range its canvases were drawn for, not the track's. Kept\n // only as part of the registration and never written anywhere else.\n const canvasRangesRef = useRef<Map<string, RegisteredAudioRange>>(new Map());\n const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = useState(0);\n\n // Spectrogram refs\n const prevSpectrogramConfigRef = useRef<Map<string, string>>(new Map());\n const spectrogramWorkerRef = useRef<SpectrogramWorkerApi | null>(null);\n const spectrogramGenerationRef = useRef(0);\n const prevCanvasVersionRef = useRef(0);\n const backgroundRenderAbortRef = useRef<{ aborted: boolean } | null>(null);\n // One key per AudioBuffer: clips that share a buffer share its registration.\n const [audioKeyOf] = useState(createAudioKeyOf);\n\n // The one place the pool is made: lazily, on the first need. The pool is\n // created once; a later workerPoolSize applies only to a pool made after a\n // cleanup terminated this one.\n const ensureWorkerPool = useCallback((): SpectrogramWorkerApi | null => {\n if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;\n try {\n const pool = createSpectrogramWorkerPool(\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n }),\n workerPoolSize\n );\n spectrogramWorkerRef.current = pool;\n return pool;\n } catch (err) {\n console.warn(\n `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`\n );\n return null;\n }\n }, [workerPoolSize]);\n\n // Terminate the pool in every cleanup: an unmount, and also when React keeps\n // the component and runs its effects again (a hidden <Activity> shown again,\n // StrictMode). What the pool held goes with it; the effects below ask the\n // next pool what it holds (#821).\n useEffect(() => {\n return () => {\n spectrogramWorkerRef.current?.terminate();\n spectrogramWorkerRef.current = null;\n };\n }, []);\n\n // Pre-register with the pool the audio of every clip on a track that draws a\n // spectrogram, once per buffer, and release what no such clip uses any more.\n // The pool is the one owner of what it holds (`registeredAudioClipIds`).\n // Not gated on the playlist's isReady: a track whose audio is decoded draws\n // while others still load, and its FFT requests would carry its audio.\n useEffect(() => {\n const wanted = spectrogramAudio(tracks, audioKeyOf);\n // Nothing wanted and no pool yet: nothing to release, and no pool to make.\n const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;\n if (!pool) return;\n\n const held = new Set(pool.registeredAudioClipIds());\n for (const [key, buffer] of wanted) {\n if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);\n }\n for (const key of held) {\n if (!wanted.has(key)) pool.unregisterAudioData(key);\n }\n }, [tracks, audioKeyOf, ensureWorkerPool]);\n\n // Main spectrogram computation effect\n useEffect(() => {\n if (tracks.length === 0) return;\n\n const currentKeys = new Map<string, string>();\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n const cfg = track.spectrogramConfig ?? spectrogramConfig;\n const cm = track.spectrogramColorMap ?? spectrogramColorMap;\n currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));\n });\n\n const prevKeys = prevSpectrogramConfigRef.current;\n const configChanged = mapsDiffer(prevKeys, currentKeys);\n\n const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;\n prevCanvasVersionRef.current = spectrogramCanvasVersion;\n\n if (!configChanged && !canvasVersionChanged) return;\n\n if (configChanged) {\n prevSpectrogramConfigRef.current = currentKeys;\n }\n\n if (backgroundRenderAbortRef.current) {\n backgroundRenderAbortRef.current.aborted = true;\n }\n\n const generation = ++spectrogramGenerationRef.current;\n\n const workerApi = ensureWorkerPool();\n if (!workerApi) return;\n // Tell the worker to abort any in-flight FFT from previous generations\n workerApi.abortGeneration(generation);\n\n // Every clip of a track whose look changed or whose canvases registered.\n // A clip whose FFT the worker already has costs a cache hit, not an FFT.\n const clipsToRender: Array<{\n clipId: string;\n /** The key the clip's audio is registered under: one per AudioBuffer. */\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n clipStartSample: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }> = [];\n\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n\n const trackConfigChanged =\n configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);\n const hasRegisteredCanvases =\n canvasVersionChanged &&\n track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));\n if (!trackConfigChanged && !hasRegisteredCanvases) return;\n\n const cfg = track.spectrogramConfig ?? spectrogramConfig ?? {};\n const cm = track.spectrogramColorMap ?? spectrogramColorMap ?? 'viridis';\n\n for (const clip of track.clips) {\n if (!clip.audioBuffer) continue;\n\n const monoFlag = mono || clip.audioBuffer.numberOfChannels === 1;\n const { offsetSamples, durationSamples } = resolveClipRange(\n clip,\n registeredClipRange(\n spectrogramCanvasRegistryRef.current.get(clip.id),\n canvasRangesRef.current\n )\n );\n\n clipsToRender.push({\n clipId: clip.id,\n audioKey: audioKeyOf(clip.audioBuffer),\n channelDataArrays: channelData(clip.audioBuffer),\n config: cfg,\n sampleRate: clip.audioBuffer.sampleRate,\n offsetSamples,\n durationSamples,\n clipStartSample: clip.startSample,\n monoFlag,\n colorMap: cm,\n });\n }\n });\n\n if (clipsToRender.length === 0) return;\n\n // Three-tier chunk classification:\n // - viewportIndices: chunks intersecting the exact viewport (phase 1a — fast first paint)\n // - bufferIndices: chunks in the 1.5× overscan buffer but outside viewport (phase 1b)\n // - remainingIndices: chunks outside the buffer (phase 2 — background batches)\n const getVisibleChunkRange = (\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n clipPixelOffset = 0\n ): ChunkTiers => {\n const container = scrollContainerRef.current;\n return classifyChunkTiers(\n channelInfo,\n clipPixelOffset,\n container\n ? { scrollLeft: container.scrollLeft, viewportWidth: container.clientWidth }\n : null\n );\n };\n\n const renderChunkSubset = async (\n api: SpectrogramWorkerApi,\n cacheKey: string,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n requestedIndices: number[],\n item: { config: SpectrogramConfig; colorMap: ColorMapValue },\n channelIndex: number,\n gen: number\n ) => {\n // Indices are derived from channel 0's registry; this channel may have\n // registered fewer canvases so far (#562). Skipped chunks render on the\n // next pass — registration bumps spectrogramCanvasVersion.\n const indices = presentChunkIndices(channelInfo, requestedIndices);\n if (indices.length === 0) return;\n\n const canvasIds = indices.map((i) => channelInfo.canvasIds[i]);\n const canvasWidths = indices.map((i) => channelInfo.canvasWidths[i]);\n // The chunks of one channel are all as tall as the first.\n const canvasHeight = canvasHeightsRef.current.get(canvasIds[0]);\n if (canvasHeight === undefined) return;\n\n // Compute correct global pixel offsets by extracting chunk numbers from\n // canvas IDs. With virtual scrolling, the registry may contain non-consecutive\n // chunks (e.g., chunks 50-55), so summing widths from index 0 gives wrong offsets.\n const globalPixelOffsets: number[] = [];\n for (const idx of indices) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[idx]);\n globalPixelOffsets.push(chunkNumber * MAX_CANVAS_WIDTH);\n }\n\n const colorLUT = getColorMap(item.colorMap);\n\n await api.renderChunks(\n {\n cacheKey,\n canvasIds,\n canvasWidths,\n globalPixelOffsets,\n canvasHeight,\n devicePixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio : 1,\n samplesPerPixel,\n colorLUT,\n frequencyScale: item.config.frequencyScale ?? 'mel',\n minFrequency: item.config.minFrequency ?? 0,\n maxFrequency: item.config.maxFrequency ?? 0,\n gainDb: item.config.gainDb ?? 20,\n rangeDb: item.config.rangeDb ?? 80,\n channelIndex,\n },\n gen\n );\n };\n\n // Compute FFT for the sample range covered by a set of chunk indices.\n // Returns the cache key (data covers all channels).\n // This avoids computing a single full-clip FFT (which OOMs on 1hr+ files)\n // by computing per-batch ranges on demand.\n const computeFFTForChunks = async (\n api: SpectrogramWorkerApi,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n indices: number[],\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n },\n gen: number\n ): Promise<string> => {\n // Determine the (window-padded) sample range these chunks cover.\n const { paddedStart, paddedEnd } = computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize: item.config.fftSize ?? 2048,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n samplesPerPixel,\n });\n\n const { cacheKey } = await api.computeFFT(\n {\n // The pool's \"clip id\" names the registered audio: the buffer's key.\n clipId: item.audioKey,\n channelDataArrays: item.channelDataArrays,\n config: item.config,\n sampleRate: item.sampleRate,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n mono: item.monoFlag,\n sampleRange: { start: paddedStart, end: paddedEnd },\n },\n gen\n );\n\n return cacheKey;\n };\n\n const computeAsync = async () => {\n const abortToken = { aborted: false };\n backgroundRenderAbortRef.current = abortToken;\n\n // Render off-screen chunks in idle-callback batches, computing FFT\n // per contiguous group to avoid allocating one giant Float32Array for the\n // full clip (which OOMs on 1hr+ files — e.g., 310K frames × 2048 bins = 2.5GB).\n // Groups remaining indices into contiguous runs (e.g., [0,1,4,5] → [0,1]+[4,5])\n // so each FFT only covers the sample range actually needed.\n // Returns true if aborted (caller should return early).\n const renderBackgroundBatches = async (\n channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n remainingIndices: number[];\n }>,\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }\n ): Promise<boolean> => {\n // Collect all contiguous groups across channels, then render\n // each group for ALL channels before moving to the next group\n // (multi-channel fairness — avoids ch1 starvation).\n const allGroups: Array<{\n group: number[];\n channelRangeEntries: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n }>;\n }> = [];\n\n // Build contiguous groups from the first channel's remaining indices\n // (all channels have the same chunk layout).\n if (channelRanges.length > 0) {\n const { channelInfo, remainingIndices } = channelRanges[0];\n const groups = groupContiguousIndices(channelInfo, remainingIndices);\n for (const group of groups) {\n allGroups.push({\n group,\n channelRangeEntries: channelRanges.map(({ ch, channelInfo: ci }) => ({\n ch,\n channelInfo: ci,\n })),\n });\n }\n }\n\n for (const { group, channelRangeEntries } of allGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n await new Promise<void>((resolve) => {\n if (typeof requestIdleCallback === 'function') {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n // Compute FFT once for this contiguous group (covers all channels)\n const { channelInfo: firstChannelInfo } = channelRangeEntries[0];\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n firstChannelInfo,\n group,\n item,\n generation\n );\n\n // Render all channels from the cached FFT data\n for (const { ch, channelInfo: ci } of channelRangeEntries) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n await renderChunkSubset(workerApi!, cacheKey, ci, group, item, ch, generation);\n }\n }\n return false;\n };\n\n for (const item of clipsToRender) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n try {\n const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);\n if (clipCanvasInfo && clipCanvasInfo.size > 0) {\n const numChannels = item.monoFlag ? 1 : item.channelDataArrays.length;\n const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);\n\n // Three-phase rendering:\n // Phase 1a: viewport-only chunks (fast first paint)\n // Phase 1b: buffer-zone chunks (prevents black chunks on scroll)\n // Phase 2: off-screen chunks (background batches)\n const channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n viewportIndices: number[];\n bufferIndices: number[];\n remainingIndices: number[];\n }> = [];\n\n for (let ch = 0; ch < numChannels; ch++) {\n const channelInfo = clipCanvasInfo.get(ch);\n if (!channelInfo) continue;\n const range = getVisibleChunkRange(channelInfo, clipPixelOffset);\n channelRanges.push({ ch, channelInfo, ...range });\n }\n\n // Phase 1a: Compute FFT for viewport chunks only, render all channels\n if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n channelRanges[0].viewportIndices,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo, viewportIndices } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n viewportIndices,\n item,\n ch,\n generation\n );\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 1b: Compute FFT for buffer-zone chunks, render all channels.\n // Buffer indices may be non-contiguous (e.g., chunks [10,14,15] from\n // indices [0,3,4,5]), so group them to avoid spanning a huge FFT range.\n if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {\n const bufferGroups = groupContiguousIndices(\n channelRanges[0].channelInfo,\n channelRanges[0].bufferIndices\n );\n\n for (const group of bufferGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n group,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n group,\n item,\n ch,\n generation\n );\n }\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 2: Render off-screen chunks in background batches\n // (each batch computes its own bounded FFT range).\n if (await renderBackgroundBatches(channelRanges, item)) return;\n }\n } catch (err) {\n if (err instanceof SpectrogramAbortError) return;\n console.warn(\n `[waveform-playlist] Spectrogram worker error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n };\n\n computeAsync().catch((err) => {\n console.error(\n `[waveform-playlist] Spectrogram computation failed: ${err instanceof Error ? err.message : String(err)}`\n );\n });\n }, [\n tracks,\n mono,\n spectrogramConfig,\n spectrogramColorMap,\n samplesPerPixel,\n spectrogramCanvasVersion,\n scrollContainerRef,\n audioKeyOf,\n ensureWorkerPool,\n ]);\n\n // Setters: each a change of the track in the arrangement, so an undo step\n // (#814). Returning the track as it is changes nothing and pushes no step:\n // the mode it is already drawn with (an unset one is 'waveform'), and any\n // mode for a MIDI track, which is drawn as a piano roll (review of #930).\n const setTrackRenderMode = useCallback(\n (trackId: string, mode: RenderMode) => {\n arrangement.updateTrack(trackId, (track: ArrangementTrack) =>\n trackKind(track) === 'midi' || resolveRenderMode(track.renderMode) === mode\n ? track\n : { ...track, renderMode: mode }\n );\n },\n [arrangement]\n );\n\n const setTrackSpectrogramConfig = useCallback(\n (trackId: string, config: SpectrogramConfig, colorMap?: ColorMapValue) => {\n // The render mode is left as it is (review of #926).\n arrangement.updateTrack(trackId, (track: ArrangementTrack) => ({\n ...track,\n spectrogramConfig: config,\n spectrogramColorMap: colorMap ?? track.spectrogramColorMap,\n }));\n },\n [arrangement]\n );\n\n const registerSpectrogramCanvas = useCallback(\n (reg: SpectrogramCanvasRegistration) => {\n const pool = ensureWorkerPool();\n if (!pool) return;\n\n try {\n pool.registerCanvas(reg.canvasId, reg.canvas);\n } catch (err) {\n console.warn(\n `[waveform-playlist] registerCanvas failed for ${reg.canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n return;\n }\n\n canvasHeightsRef.current.set(reg.canvasId, reg.heightPx);\n if (reg.offsetSamples !== undefined || reg.durationSamples !== undefined) {\n canvasRangesRef.current.set(reg.canvasId, {\n offsetSamples: reg.offsetSamples,\n durationSamples: reg.durationSamples,\n });\n } else {\n canvasRangesRef.current.delete(reg.canvasId);\n }\n const registry = spectrogramCanvasRegistryRef.current;\n if (!registry.has(reg.clipId)) {\n registry.set(reg.clipId, new Map());\n }\n const perClip = registry.get(reg.clipId)!;\n const entry = perClip.get(reg.channelIndex) ?? { canvasIds: [], canvasWidths: [] };\n const existingIdx = entry.canvasIds.indexOf(reg.canvasId);\n if (existingIdx >= 0) {\n entry.canvasWidths[existingIdx] = reg.widthPx;\n } else {\n entry.canvasIds.push(reg.canvasId);\n entry.canvasWidths.push(reg.widthPx);\n }\n perClip.set(reg.channelIndex, entry);\n setSpectrogramCanvasVersion((v) => v + 1);\n },\n [ensureWorkerPool]\n );\n\n const unregisterSpectrogramCanvas = useCallback((canvasId: string) => {\n canvasHeightsRef.current.delete(canvasId);\n canvasRangesRef.current.delete(canvasId);\n const pool = spectrogramWorkerRef.current;\n if (pool) {\n try {\n pool.unregisterCanvas(canvasId);\n } catch (err) {\n console.warn(\n `[waveform-playlist] unregisterCanvas failed for ${canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Canvas IDs follow the format `${clipId}-ch${channelIndex}-chunk${n}`.\n const parsed = parseCanvasId(canvasId);\n if (!parsed) return;\n const { clipId, channelIndex } = parsed;\n\n const registry = spectrogramCanvasRegistryRef.current;\n const perClip = registry.get(clipId);\n if (!perClip) return;\n const entry = perClip.get(channelIndex);\n if (!entry) return;\n const idx = entry.canvasIds.indexOf(canvasId);\n if (idx >= 0) {\n entry.canvasIds.splice(idx, 1);\n entry.canvasWidths.splice(idx, 1);\n }\n if (entry.canvasIds.length === 0) {\n perClip.delete(channelIndex);\n }\n if (perClip.size === 0) {\n registry.delete(clipId);\n }\n setSpectrogramCanvasVersion((v) => v + 1);\n }, []);\n\n const renderMenuItems = useCallback(\n (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => {\n return spectrogramMenuItems({\n renderMode: props.renderMode as RenderMode,\n onRenderModeChange: props.onRenderModeChange,\n onOpenSettings: props.onOpenSettings,\n onClose: props.onClose,\n });\n },\n []\n );\n\n const value: SpectrogramIntegration = useMemo(\n () => ({\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n SettingsModal: SpectrogramSettingsModal,\n getColorMap,\n getFrequencyScale: getFrequencyScale as (\n name: string\n ) => (f: number, minF: number, maxF: number) => number,\n }),\n [\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n ]\n );\n\n return <SpectrogramIntegrationContext value={value}>{children}</SpectrogramIntegrationContext>;\n};\n","import {\n MAX_CANVAS_WIDTH,\n parseSpectrogramCanvasId,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n} from '@waveform-playlist/core';\nimport { computePaddedFftRange } from '@dawcore/spectrogram';\n\n/**\n * Pure, side-effect-free helpers extracted from `SpectrogramProvider`.\n *\n * These cover the geometry/key logic that the provider's worker-orchestration\n * effect depends on (chunk classification, FFT sample ranges, contiguous\n * grouping, config-change detection). Keeping them DOM-free makes them unit\n * testable in a Node environment — the provider supplies the imperative shell\n * (refs, worker calls, React state) around this functional core.\n */\n\n/** A channel's registered canvas chunks: parallel arrays of IDs and pixel widths. */\nexport interface ChannelChunkInfo {\n canvasIds: string[];\n canvasWidths: number[];\n}\n\n/** Chunk indices grouped by their relationship to the current scroll viewport. */\nexport interface ChunkTiers {\n /** Chunks intersecting the exact viewport — fast first paint. */\n viewportIndices: number[];\n /** Chunks within the 1.5× overscan buffer but outside the viewport. */\n bufferIndices: number[];\n /** Chunks outside the buffer — rendered in background batches. */\n remainingIndices: number[];\n}\n\n/** Scroll-container metrics needed to classify chunks. `null` ⇒ no container yet. */\nexport interface ViewportMetrics {\n scrollLeft: number;\n viewportWidth: number;\n}\n\n/**\n * Extract the chunk number from a canvas ID like `\"clipId-ch0-chunk5\"` → `5`.\n * Delegates to the canonical `parseSpectrogramCanvasId`; warns and returns `0`\n * when the ID doesn't match the `${clipId}-ch${channelIndex}-chunk${n}` format.\n */\nexport function extractChunkNumber(canvasId: string): number {\n const parsed = parseSpectrogramCanvasId(canvasId);\n if (!parsed) {\n console.warn(`[spectrogram] Unexpected canvas ID format: ${canvasId}`);\n return 0;\n }\n return parsed.chunkIndex;\n}\n\n/**\n * Keep only indices whose canvas is registered for THIS channel.\n *\n * Chunk indices are derived once from channel 0's registry and reused across\n * channels, but canvases register progressively per channel — a later channel\n * can briefly hold fewer entries, and indexing past its registry threw\n * `Cannot read properties of undefined (reading 'match')` (#562). Skipped\n * chunks render on the next pass: registration bumps `spectrogramCanvasVersion`.\n */\nexport function presentChunkIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[] {\n return indices.filter((i) => channelInfo.canvasIds[i] !== undefined);\n}\n\n/**\n * Parse a canvas ID of the form `${clipId}-ch${channelIndex}-chunk${n}` into its\n * clip ID and channel index. Returns `null` when the ID doesn't match.\n */\nexport function parseCanvasId(canvasId: string): { clipId: string; channelIndex: number } | null {\n const parsed = parseSpectrogramCanvasId(canvasId);\n return parsed ? { clipId: parsed.clipId, channelIndex: parsed.channelIndex } : null;\n}\n\n/**\n * Split indices into contiguous groups based on their chunk numbers, e.g.\n * indices mapping to chunks `[0,1,4,5]` → `[[0,1],[4,5]]`. Prevents computing an\n * FFT range that spans the gap between non-adjacent chunks.\n */\nexport function groupContiguousIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[][] {\n if (indices.length === 0) return [];\n const groups: number[][] = [];\n let currentGroup = [indices[0]];\n let prevChunk = extractChunkNumber(channelInfo.canvasIds[indices[0]]);\n for (let i = 1; i < indices.length; i++) {\n const chunk = extractChunkNumber(channelInfo.canvasIds[indices[i]]);\n if (chunk === prevChunk + 1) {\n currentGroup.push(indices[i]);\n } else {\n groups.push(currentGroup);\n currentGroup = [indices[i]];\n }\n prevChunk = chunk;\n }\n groups.push(currentGroup);\n return groups;\n}\n\n/**\n * Classify a channel's chunks into viewport / buffer / remaining tiers.\n *\n * The buffer uses a 1.5× viewport-width overscan to match\n * `useVisibleChunkIndices` in ScrollViewport, so FFT covers every mounted\n * canvas. When `viewport` is `null` (no scroll container yet), every chunk is\n * treated as in-viewport.\n */\nexport function classifyChunkTiers(\n channelInfo: ChannelChunkInfo,\n clipPixelOffset = 0,\n viewport: ViewportMetrics | null\n): ChunkTiers {\n if (!viewport) {\n return {\n viewportIndices: channelInfo.canvasWidths.map((_, i) => i),\n bufferIndices: [],\n remainingIndices: [],\n };\n }\n\n const { scrollLeft, viewportWidth } = viewport;\n const buffer = viewportWidth * 1.5;\n const bufferStart = Math.max(0, scrollLeft - buffer);\n const bufferEnd = scrollLeft + viewportWidth + buffer;\n\n const viewportIndices: number[] = [];\n const bufferIndices: number[] = [];\n const remainingIndices: number[] = [];\n\n for (let i = 0; i < channelInfo.canvasWidths.length; i++) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[i]);\n const chunkLeft = chunkNumber * MAX_CANVAS_WIDTH + clipPixelOffset;\n const chunkRight = chunkLeft + channelInfo.canvasWidths[i];\n if (chunkRight > scrollLeft && chunkLeft < scrollLeft + viewportWidth) {\n viewportIndices.push(i);\n } else if (chunkRight > bufferStart && chunkLeft < bufferEnd) {\n bufferIndices.push(i);\n } else {\n remainingIndices.push(i);\n }\n }\n\n return { viewportIndices, bufferIndices, remainingIndices };\n}\n\nexport interface ChunkSampleRangeParams {\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n indices: number[];\n /** FFT window size (samples) used to pad the range against edge artifacts. */\n fftSize: number;\n offsetSamples: number;\n durationSamples: number;\n samplesPerPixel: number;\n}\n\n/**\n * Compute the (window-padded, clip-clamped) sample range covered by a set of\n * chunk indices. Computing per-batch ranges on demand avoids allocating one\n * giant FFT array for a full clip (which OOMs on 1hr+ files).\n */\nexport function computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n}: ChunkSampleRangeParams): { paddedStart: number; paddedEnd: number } {\n return computePaddedFftRange({\n chunks: indices.map((i) => ({\n chunkIndex: extractChunkNumber(channelInfo.canvasIds[i]),\n widthPx: channelInfo.canvasWidths[i],\n })),\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n });\n}\n\n/** Resolve a track's effective render mode: the track's own, else `'waveform'`. */\nexport function resolveRenderMode(trackRenderMode: RenderMode | undefined): RenderMode {\n return trackRenderMode ?? 'waveform';\n}\n\n/**\n * Stable string key for a track's full spectrogram appearance (mode + config +\n * color map + mono). A change means the rendered output must be recomputed.\n */\nexport function buildConfigKey(params: {\n mode: RenderMode;\n cfg: SpectrogramConfig | undefined;\n cm: ColorMapValue | undefined;\n mono: boolean;\n}): string {\n const { mode, cfg, cm, mono } = params;\n return JSON.stringify({ mode, cfg, cm, mono });\n}\n\n/**\n * Whether two key maps differ — different size, or any key present in `current`\n * whose value doesn't match `prev`. Used to detect config/FFT changes between\n * effect runs.\n */\nexport function mapsDiffer(prev: Map<string, string>, current: Map<string, string>): boolean {\n if (current.size !== prev.size) return true;\n for (const [key, value] of current) {\n if (prev.get(key) !== value) return true;\n }\n return false;\n}\n\n/** The range of the audio a canvas registered with (`SpectrogramCanvasRegistration`). */\nexport interface RegisteredAudioRange {\n offsetSamples?: number;\n durationSamples?: number;\n}\n\n/**\n * The range a clip's canvases registered with: that of the first canvas that\n * gave one (all canvases of a clip are drawn for the same range; a new range\n * registers new canvases). `undefined` when none gave one.\n */\nexport function registeredClipRange(\n perClip: ReadonlyMap<number, ChannelChunkInfo> | undefined,\n rangeByCanvasId: ReadonlyMap<string, RegisteredAudioRange>\n): RegisteredAudioRange | undefined {\n if (!perClip) return undefined;\n for (const channelInfo of perClip.values()) {\n for (const canvasId of channelInfo.canvasIds) {\n const range = rangeByCanvasId.get(canvasId);\n if (range) return range;\n }\n }\n return undefined;\n}\n\n/**\n * The range to draw a clip for: what its canvases registered with (the view\n * may draw a clip the tracks do not have yet, a trim being dragged), field by\n * field, else the clip's own.\n */\nexport function resolveClipRange(\n clip: { offsetSamples: number; durationSamples: number },\n registered: RegisteredAudioRange | undefined\n): { offsetSamples: number; durationSamples: number } {\n return {\n offsetSamples: registered?.offsetSamples ?? clip.offsetSamples,\n durationSamples: registered?.durationSamples ?? clip.durationSamples,\n };\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\nimport { resolveRenderMode } from './spectrogram-helpers';\n\n/**\n * The key an AudioBuffer's audio is registered under in the worker pool, the\n * same for as long as the buffer lives. Clips that share a buffer share the\n * key (a split keeps one buffer for both halves), so the pool holds the audio\n * once (#821). The worker's FFT cache key also carries each clip's range, so\n * two clips over different parts of one buffer keep separate entries.\n */\nexport type AudioKeyOf = (buffer: AudioBuffer) => string;\n\nexport function createAudioKeyOf(): AudioKeyOf {\n const keys = new WeakMap<AudioBuffer, string>();\n let next = 0;\n return (buffer) => {\n const existing = keys.get(buffer);\n if (existing !== undefined) return existing;\n next += 1;\n const key = `audio-${next}`;\n keys.set(buffer, key);\n return key;\n };\n}\n\n/**\n * The audio the pool should hold, by key: each buffer that a clip on a track\n * drawing a spectrogram (`spectrogram` or `both`) uses. A waveform track's\n * audio is never computed, so it is not sent (#821).\n */\nexport function spectrogramAudio(\n tracks: readonly ClipTrack[],\n audioKeyOf: AudioKeyOf\n): Map<string, AudioBuffer> {\n const wanted = new Map<string, AudioBuffer>();\n for (const track of tracks) {\n if (resolveRenderMode(track.renderMode) === 'waveform') continue;\n for (const clip of track.clips) {\n if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);\n }\n }\n return wanted;\n}\n\n/** Every channel of a buffer, as the views `getChannelData` returns (not copies). */\nexport function channelData(buffer: AudioBuffer): Float32Array[] {\n return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));\n}\n","import { useMemo } from 'react';\n\n/**\n * The value as it was the last time its JSON content changed. For plain-data\n * props an app often writes inline (`config={{ fftSize: 2048 }}`): a new\n * object with the same content keeps the old one, so the context value and\n * the effects that depend on it do not change on every render of the app\n * (#821). Only for values JSON describes completely (no functions, no class\n * instances); a key whose value is `undefined` counts as absent.\n */\nexport function useStableByContent<T>(value: T): T {\n const content = JSON.stringify(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the content, not the identity\n return useMemo(() => value, [content]);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,+BAAmB;AA6ET;AArEV,IAAM,eAAe,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS5B,IAAM,aAAa,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa1B,IAAM,iBAAiB,yBAAAA,QAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;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oBAAoB,MAAM;AAAA,QAC1B,gBAAgB,MAAM;AAAA,QACtB,SAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,YAAgC;AAAA,IACpC,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA,mBAAmB;AAAA,IAGrB;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,6CAAC,gDAA8B,OAAe,UAAS;AAChE;","names":["styled","import_styled_components","import_jsx_runtime","styled","import_react","import_core","import_spectrogram","import_core","import_react","import_browser","import_jsx_runtime","config","colorMap"]}
package/dist/index.mjs CHANGED
@@ -616,9 +616,9 @@ import {
616
616
  import {
617
617
  useArrangement,
618
618
  usePlaybackControls,
619
- usePlaylistView,
620
- usePlaylistZoom,
621
- usePlaylistTimeline
619
+ useAudioSettings,
620
+ useZoom,
621
+ useTimeline
622
622
  } from "@waveform-playlist/browser";
623
623
  import { jsx as jsx3 } from "react/jsx-runtime";
624
624
  var SpectrogramProvider = ({
@@ -629,9 +629,9 @@ var SpectrogramProvider = ({
629
629
  }) => {
630
630
  const spectrogramConfig = useStableByContent(config);
631
631
  const spectrogramColorMap = useStableByContent(colorMap);
632
- const { mono } = usePlaylistView();
633
- const { samplesPerPixel } = usePlaylistZoom();
634
- const { tracks } = usePlaylistTimeline();
632
+ const { mono } = useAudioSettings();
633
+ const { samplesPerPixel } = useZoom();
634
+ const { tracks } = useTimeline();
635
635
  const { scrollContainerRef } = usePlaybackControls();
636
636
  const arrangement = useArrangement();
637
637
  const spectrogramCanvasRegistryRef = useRef2(/* @__PURE__ */ new Map());
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/components/SpectrogramMenuItems.tsx","../src/components/SpectrogramSettingsModal.tsx","../src/SpectrogramProvider.tsx","../src/spectrogram-helpers.ts","../src/audioRegistration.ts","../src/useStableByContent.ts"],"sourcesContent":["import React from 'react';\nimport styled from 'styled-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport type { SpectrogramIntegration } from '@waveform-playlist/browser';\n\n/** The items browser's track menu asks the spectrogram integration for:\n * ui-components' `TrackMenuItem[]`, named through the type that carries it. */\ntype MenuItems = ReturnType<NonNullable<SpectrogramIntegration['renderMenuItems']>>;\n\nconst SectionLabel = styled.div`\n font-size: 0.65rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.5;\n margin-bottom: 0.25rem;\n`;\n\nconst RadioLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n padding: 0.2rem 0;\n font-size: 0.8rem;\n cursor: pointer;\n\n &:hover {\n opacity: 0.8;\n }\n`;\n\nconst SettingsButton = styled.button`\n background: none;\n border: none;\n color: inherit;\n cursor: pointer;\n font-size: 0.8rem;\n padding: 0.35rem 0.75rem;\n width: 100%;\n text-align: left;\n\n &:hover {\n background: rgba(128, 128, 128, 0.15);\n }\n`;\n\nconst DropdownSection = styled.div`\n padding: 0.25rem 0.75rem;\n`;\n\nconst RENDER_MODES: { value: RenderMode; label: string }[] = [\n { value: 'waveform', label: 'Waveform' },\n { value: 'spectrogram', label: 'Spectrogram' },\n { value: 'both', label: 'Both' },\n];\n\nexport interface SpectrogramMenuItemsOptions {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Returns the track menu items (`TrackMenuItem[]` of ui-components) for the\n * spectrogram display mode radios and settings button.\n */\nexport function spectrogramMenuItems({\n renderMode,\n onRenderModeChange,\n onOpenSettings,\n onClose,\n}: SpectrogramMenuItemsOptions): MenuItems {\n return [\n {\n id: 'spectrogram-display',\n content: (\n <DropdownSection>\n <SectionLabel>Display</SectionLabel>\n {RENDER_MODES.map(({ value, label }) => (\n <RadioLabel key={value}>\n <input\n type=\"radio\"\n name=\"render-mode\"\n checked={renderMode === value}\n onChange={() => {\n onRenderModeChange(value);\n onClose?.();\n }}\n />\n {label}\n </RadioLabel>\n ))}\n </DropdownSection>\n ),\n },\n {\n id: 'spectrogram-settings',\n content: (\n <SettingsButton\n onClick={(e) => {\n e.stopPropagation();\n onClose?.();\n onOpenSettings();\n }}\n onMouseDown={(e) => e.stopPropagation()}\n >\n Spectrogram Settings...\n </SettingsButton>\n ),\n },\n ];\n}\n","import React, { useRef, useEffect, useId, useLayoutEffect, useState } from 'react';\nimport styled from 'styled-components';\nimport {\n SPECTROGRAM_DEFAULTS,\n type SpectrogramConfig,\n type ColorMapValue,\n type ColorMapName,\n type FFTSize,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramSettingsModalProps {\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n /**\n * Called on Apply with the config it was given plus the fields the user\n * changed, and the colour map (the one given unless the user picked one).\n * Not called when nothing was changed: Apply then only closes.\n */\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n /**\n * The sample rate of the audio. With a config that has no `maxFrequency`,\n * the field shows half of it, the top the spectrogram is drawn to.\n */\n sampleRate?: number;\n}\n\nconst StyledDialog = styled.dialog`\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 8px;\n padding: 1.5rem;\n background: ${(p) => p.theme.timescaleBackgroundColor ?? '#222'};\n color: ${(p) => p.theme.textColor ?? 'inherit'};\n min-width: 380px;\n max-width: 500px;\n overscroll-behavior: contain;\n\n &::backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n`;\n\nconst Title = styled.h3`\n margin: 0 0 1rem;\n font-size: 1rem;\n`;\n\nconst FormGrid = styled.div`\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n`;\n\nconst Field = styled.div<{ $span?: boolean }>`\n display: flex;\n flex-direction: column;\n gap: 0.2rem;\n grid-column: ${(p) => (p.$span ? '1 / -1' : 'auto')};\n`;\n\nconst Label = styled.label`\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.6;\n`;\n\nconst Select = styled.select`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n`;\n\nconst NumberInput = styled.input`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n width: 100%;\n box-sizing: border-box;\n`;\n\nconst CheckboxLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n font-size: 0.85rem;\n cursor: pointer;\n`;\n\nconst ButtonRow = styled.div`\n display: flex;\n justify-content: flex-end;\n gap: 0.5rem;\n margin-top: 1.25rem;\n`;\n\nconst ModalButton = styled.button<{ $primary?: boolean }>`\n padding: 0.4rem 1rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n cursor: pointer;\n font-size: 0.85rem;\n background: ${(p) => (p.$primary ? (p.theme.buttonBackground ?? '#0091ff') : 'transparent')};\n color: ${(p) => (p.$primary ? (p.theme.buttonText ?? '#fff') : 'inherit')};\n ${(p) => (p.$primary && p.theme.buttonBorder ? `border-color: ${p.theme.buttonBorder};` : '')}\n\n &:hover {\n ${(p) =>\n p.$primary && p.theme.buttonHoverBackground\n ? `background: ${p.theme.buttonHoverBackground};`\n : 'opacity: 0.85;'}\n }\n`;\n\nconst FFT_SIZES = [256, 512, 1024, 2048, 4096, 8192];\nconst WINDOW_FUNCTIONS = [\n 'hann',\n 'hamming',\n 'blackman',\n 'blackman-harris',\n 'bartlett',\n 'rectangular',\n] as const;\nconst FREQ_SCALES = ['linear', 'logarithmic', 'mel', 'bark', 'erb'] as const;\nconst COLOR_MAPS: ColorMapName[] = ['viridis', 'magma', 'inferno', 'grayscale', 'igray', 'roseus'];\n/** The select's value for a colour map given as an array of colours. */\nconst CUSTOM_COLOR_MAP = 'custom';\n\ntype SettingsFormProps = Omit<SpectrogramSettingsModalProps, 'open'>;\n\n/**\n * The form is a draft of the settings. It is mounted only while the dialog is\n * open, so its state starts from the props each time the dialog opens and is\n * never overwritten by a parent re-render while the user is editing.\n *\n * The draft holds only the fields the user changed (#814). A field shows its\n * edit, else the config's value, else the default; Apply sends the config it\n * was given with the edits on top, so a field the form does not show\n * (`alpha`, `labelsColor`, `labelsBackground`) and a field left at its default\n * (`maxFrequency`: half the sample rate) are not written.\n */\nconst SettingsForm: React.FC<SettingsFormProps> = ({\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const id = useId();\n const [edits, setEdits] = useState<SpectrogramConfig>({});\n const [editedColorMap, setEditedColorMap] = useState<ColorMapName | undefined>(undefined);\n\n const shown = <K extends keyof SpectrogramConfig>(key: K): SpectrogramConfig[K] =>\n key in edits ? edits[key] : config[key];\n const edit = (changes: SpectrogramConfig) => setEdits((prev) => ({ ...prev, ...changes }));\n\n const fftSize = shown('fftSize') ?? SPECTROGRAM_DEFAULTS.fftSize;\n const hopSize = shown('hopSize') ?? Math.floor(fftSize / 4);\n const zeroPadding = shown('zeroPaddingFactor') ?? SPECTROGRAM_DEFAULTS.zeroPaddingFactor;\n const windowFn = shown('windowFunction') ?? SPECTROGRAM_DEFAULTS.windowFunction;\n const freqScale = shown('frequencyScale') ?? SPECTROGRAM_DEFAULTS.frequencyScale;\n const minFreq = shown('minFrequency') ?? SPECTROGRAM_DEFAULTS.minFrequency;\n const nyquist = sampleRate !== undefined ? sampleRate / 2 : undefined;\n // An emptied field stays empty while the user types (Apply then leaves the\n // default); only an untouched one shows the default's number.\n const maxFreq = 'maxFrequency' in edits ? edits.maxFrequency : (config.maxFrequency ?? nyquist);\n const gainDb = shown('gainDb') ?? SPECTROGRAM_DEFAULTS.gainDb;\n const rangeDb = shown('rangeDb') ?? SPECTROGRAM_DEFAULTS.rangeDb;\n const showLabels = shown('labels') ?? SPECTROGRAM_DEFAULTS.labels;\n const isCustomColorMap = typeof colorMap !== 'string';\n const colorMapValue = editedColorMap ?? (isCustomColorMap ? CUSTOM_COLOR_MAP : colorMap);\n\n const handleApply = () => {\n // A field set back to the value it had is no change. With none, Apply\n // only closes: an onApply would be an undo step that changes nothing.\n const configChanged = (Object.keys(edits) as Array<keyof SpectrogramConfig>).some(\n (key) => edits[key] !== config[key]\n );\n const colorMapChanged = editedColorMap !== undefined && editedColorMap !== colorMap;\n if (configChanged || colorMapChanged) {\n onApply({ ...config, ...edits }, editedColorMap ?? colorMap);\n }\n onClose();\n };\n\n return (\n <>\n <FormGrid>\n <Field>\n <Label htmlFor={`${id}-fft-size`}>FFT Size</Label>\n <Select\n id={`${id}-fft-size`}\n value={fftSize}\n onChange={(e) => {\n const v = Number(e.target.value) as FFTSize;\n edit({ fftSize: v, hopSize: Math.floor(v / 4) });\n }}\n >\n {FFT_SIZES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-hop-size`}>Hop Size</Label>\n <Select\n id={`${id}-hop-size`}\n value={hopSize}\n onChange={(e) => edit({ hopSize: Number(e.target.value) })}\n >\n {[\n { label: `${fftSize} (no overlap)`, value: fftSize },\n { label: `${Math.floor(fftSize / 2)} (50%)`, value: Math.floor(fftSize / 2) },\n { label: `${Math.floor(fftSize / 4)} (75%)`, value: Math.floor(fftSize / 4) },\n { label: `${Math.floor(fftSize / 8)} (87.5%)`, value: Math.floor(fftSize / 8) },\n ].map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-zero-padding`}>Zero Padding</Label>\n <Select\n id={`${id}-zero-padding`}\n value={zeroPadding}\n onChange={(e) => edit({ zeroPaddingFactor: Number(e.target.value) })}\n >\n {[1, 2, 4, 8, 16].map((v) => (\n <option key={v} value={v}>\n {v}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-window-function`}>Window Function</Label>\n <Select\n id={`${id}-window-function`}\n value={windowFn}\n onChange={(e) =>\n edit({ windowFunction: e.target.value as SpectrogramConfig['windowFunction'] })\n }\n >\n {WINDOW_FUNCTIONS.map((w) => (\n <option key={w} value={w}>\n {w}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-frequency-scale`}>Frequency Scale</Label>\n <Select\n id={`${id}-frequency-scale`}\n value={freqScale}\n onChange={(e) =>\n edit({ frequencyScale: e.target.value as SpectrogramConfig['frequencyScale'] })\n }\n >\n {FREQ_SCALES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-color-map`}>Color Map</Label>\n <Select\n id={`${id}-color-map`}\n value={colorMapValue}\n onChange={(e) =>\n // \"custom\" is the colour map given (an array): no edit.\n setEditedColorMap(\n e.target.value === CUSTOM_COLOR_MAP ? undefined : (e.target.value as ColorMapName)\n )\n }\n >\n {isCustomColorMap && <option value={CUSTOM_COLOR_MAP}>{CUSTOM_COLOR_MAP}</option>}\n {COLOR_MAPS.map((c) => (\n <option key={c} value={c}>\n {c}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-min-frequency`}>Min Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-min-frequency`}\n type=\"number\"\n min={0}\n max={5000}\n step={50}\n value={minFreq}\n onChange={(e) => edit({ minFrequency: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-max-frequency`}>Max Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-max-frequency`}\n type=\"number\"\n min={1000}\n max={nyquist}\n step={50}\n value={maxFreq ?? ''}\n onChange={(e) =>\n // Emptied: back to the default, half the sample rate.\n edit({ maxFrequency: e.target.value === '' ? undefined : Number(e.target.value) })\n }\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-range-db`}>Range (dB)</Label>\n <NumberInput\n id={`${id}-range-db`}\n type=\"number\"\n min={1}\n max={120}\n step={1}\n value={rangeDb}\n onChange={(e) => edit({ rangeDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-gain-db`}>Gain (dB)</Label>\n <NumberInput\n id={`${id}-gain-db`}\n type=\"number\"\n min={-20}\n max={60}\n step={1}\n value={gainDb}\n onChange={(e) => edit({ gainDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field $span>\n <CheckboxLabel>\n <input\n type=\"checkbox\"\n checked={showLabels}\n onChange={(e) => edit({ labels: e.target.checked })}\n />\n Show Frequency Labels\n </CheckboxLabel>\n </Field>\n </FormGrid>\n\n <ButtonRow>\n <ModalButton type=\"button\" onClick={onClose}>\n Cancel\n </ModalButton>\n <ModalButton type=\"button\" $primary onClick={handleApply}>\n Apply\n </ModalButton>\n </ButtonRow>\n </>\n );\n};\n\nexport const SpectrogramSettingsModal: React.FC<SpectrogramSettingsModalProps> = ({\n open,\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const dialogRef = useRef<HTMLDialogElement>(null);\n const titleId = useId();\n\n // Latest props for the native `close` listener, so the listener is attached\n // once and not re-added whenever the parent passes a new `onClose`.\n const latestRef = useRef({ open, onClose });\n useLayoutEffect(() => {\n latestRef.current = { open, onClose };\n });\n\n // Native close (Escape key)\n useEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n const handleClose = () => {\n // Only report a close the parent did not ask for (avoids double-fire)\n if (latestRef.current.open) {\n latestRef.current.onClose();\n }\n };\n dialog.addEventListener('close', handleClose);\n return () => dialog.removeEventListener('close', handleClose);\n }, []);\n\n // Layout effect: the dialog opens and closes in the same frame as the form\n // mounts and unmounts, whatever triggered the change.\n useLayoutEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n if (open && !dialog.open) {\n dialog.showModal();\n } else if (!open && dialog.open) {\n dialog.close();\n }\n }, [open]);\n\n return (\n <StyledDialog ref={dialogRef} aria-labelledby={titleId}>\n <Title id={titleId}>Spectrogram Settings</Title>\n {open && (\n <SettingsForm\n onClose={onClose}\n config={config}\n colorMap={colorMap}\n onApply={onApply}\n sampleRate={sampleRate}\n />\n )}\n </StyledDialog>\n );\n};\n","import React, { useState, useEffect, useRef, useCallback, useMemo, type ReactNode } from 'react';\nimport {\n MAX_CANVAS_WIDTH,\n trackKind,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n type ArrangementTrack,\n type SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport {\n getColorMap,\n getFrequencyScale,\n createSpectrogramWorkerPool,\n SpectrogramAbortError,\n type SpectrogramWorkerApi,\n} from '@dawcore/spectrogram';\nimport {\n extractChunkNumber,\n parseCanvasId,\n presentChunkIndices,\n groupContiguousIndices,\n classifyChunkTiers,\n computeChunkSampleRange,\n resolveRenderMode,\n buildConfigKey,\n mapsDiffer,\n registeredClipRange,\n resolveClipRange,\n type ChunkTiers,\n type RegisteredAudioRange,\n} from './spectrogram-helpers';\nimport { createAudioKeyOf, spectrogramAudio, channelData } from './audioRegistration';\nimport { useStableByContent } from './useStableByContent';\nimport { spectrogramMenuItems } from './components';\nimport { SpectrogramSettingsModal } from './components';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '@waveform-playlist/browser';\nimport {\n useArrangement,\n usePlaybackControls,\n usePlaylistView,\n usePlaylistZoom,\n usePlaylistTimeline,\n} from '@waveform-playlist/browser';\n\nexport interface SpectrogramProviderProps {\n config?: SpectrogramConfig;\n colorMap?: ColorMapValue;\n /** Number of Web Workers for parallel FFT computation. Defaults to 2 (one per stereo channel). */\n workerPoolSize?: number;\n children: ReactNode;\n}\n\nexport const SpectrogramProvider: React.FC<SpectrogramProviderProps> = ({\n config,\n colorMap,\n workerPoolSize,\n children,\n}) => {\n // By content: the guide writes `config={{ … }}` inline (#821).\n const spectrogramConfig = useStableByContent(config);\n const spectrogramColorMap = useStableByContent(colorMap);\n const { mono } = usePlaylistView();\n const { samplesPerPixel } = usePlaylistZoom();\n const { tracks } = usePlaylistTimeline();\n const { scrollContainerRef } = usePlaybackControls();\n // The owner of each track's render mode, spectrogram config and colour map\n // (#814): the setters below change the track, and everything here reads it.\n const arrangement = useArrangement();\n\n // OffscreenCanvas registry for worker-rendered spectrograms\n const spectrogramCanvasRegistryRef = useRef<\n Map<string, Map<number, { canvasIds: string[]; canvasWidths: number[] }>>\n >(new Map());\n // The height each canvas registered with, by canvas id. The row height is an\n // option of the view (#689), so this provider, which sits above the views,\n // learns it from the canvases: a view draws at its own height, and in\n // \"both\" mode a canvas is half a row tall.\n const canvasHeightsRef = useRef<Map<string, number>>(new Map());\n // The range of the audio each canvas registered with, by canvas id: the view\n // draws a trim being dragged before the tracks have it (#812), so a clip is\n // rendered for the range its canvases were drawn for, not the track's. Kept\n // only as part of the registration and never written anywhere else.\n const canvasRangesRef = useRef<Map<string, RegisteredAudioRange>>(new Map());\n const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = useState(0);\n\n // Spectrogram refs\n const prevSpectrogramConfigRef = useRef<Map<string, string>>(new Map());\n const spectrogramWorkerRef = useRef<SpectrogramWorkerApi | null>(null);\n const spectrogramGenerationRef = useRef(0);\n const prevCanvasVersionRef = useRef(0);\n const backgroundRenderAbortRef = useRef<{ aborted: boolean } | null>(null);\n // One key per AudioBuffer: clips that share a buffer share its registration.\n const [audioKeyOf] = useState(createAudioKeyOf);\n\n // The one place the pool is made: lazily, on the first need. The pool is\n // created once; a later workerPoolSize applies only to a pool made after a\n // cleanup terminated this one.\n const ensureWorkerPool = useCallback((): SpectrogramWorkerApi | null => {\n if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;\n try {\n const pool = createSpectrogramWorkerPool(\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n }),\n workerPoolSize\n );\n spectrogramWorkerRef.current = pool;\n return pool;\n } catch (err) {\n console.warn(\n `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`\n );\n return null;\n }\n }, [workerPoolSize]);\n\n // Terminate the pool in every cleanup: an unmount, and also when React keeps\n // the component and runs its effects again (a hidden <Activity> shown again,\n // StrictMode). What the pool held goes with it; the effects below ask the\n // next pool what it holds (#821).\n useEffect(() => {\n return () => {\n spectrogramWorkerRef.current?.terminate();\n spectrogramWorkerRef.current = null;\n };\n }, []);\n\n // Pre-register with the pool the audio of every clip on a track that draws a\n // spectrogram, once per buffer, and release what no such clip uses any more.\n // The pool is the one owner of what it holds (`registeredAudioClipIds`).\n // Not gated on the playlist's isReady: a track whose audio is decoded draws\n // while others still load, and its FFT requests would carry its audio.\n useEffect(() => {\n const wanted = spectrogramAudio(tracks, audioKeyOf);\n // Nothing wanted and no pool yet: nothing to release, and no pool to make.\n const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;\n if (!pool) return;\n\n const held = new Set(pool.registeredAudioClipIds());\n for (const [key, buffer] of wanted) {\n if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);\n }\n for (const key of held) {\n if (!wanted.has(key)) pool.unregisterAudioData(key);\n }\n }, [tracks, audioKeyOf, ensureWorkerPool]);\n\n // Main spectrogram computation effect\n useEffect(() => {\n if (tracks.length === 0) return;\n\n const currentKeys = new Map<string, string>();\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n const cfg = track.spectrogramConfig ?? spectrogramConfig;\n const cm = track.spectrogramColorMap ?? spectrogramColorMap;\n currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));\n });\n\n const prevKeys = prevSpectrogramConfigRef.current;\n const configChanged = mapsDiffer(prevKeys, currentKeys);\n\n const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;\n prevCanvasVersionRef.current = spectrogramCanvasVersion;\n\n if (!configChanged && !canvasVersionChanged) return;\n\n if (configChanged) {\n prevSpectrogramConfigRef.current = currentKeys;\n }\n\n if (backgroundRenderAbortRef.current) {\n backgroundRenderAbortRef.current.aborted = true;\n }\n\n const generation = ++spectrogramGenerationRef.current;\n\n const workerApi = ensureWorkerPool();\n if (!workerApi) return;\n // Tell the worker to abort any in-flight FFT from previous generations\n workerApi.abortGeneration(generation);\n\n // Every clip of a track whose look changed or whose canvases registered.\n // A clip whose FFT the worker already has costs a cache hit, not an FFT.\n const clipsToRender: Array<{\n clipId: string;\n /** The key the clip's audio is registered under: one per AudioBuffer. */\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n clipStartSample: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }> = [];\n\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n\n const trackConfigChanged =\n configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);\n const hasRegisteredCanvases =\n canvasVersionChanged &&\n track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));\n if (!trackConfigChanged && !hasRegisteredCanvases) return;\n\n const cfg = track.spectrogramConfig ?? spectrogramConfig ?? {};\n const cm = track.spectrogramColorMap ?? spectrogramColorMap ?? 'viridis';\n\n for (const clip of track.clips) {\n if (!clip.audioBuffer) continue;\n\n const monoFlag = mono || clip.audioBuffer.numberOfChannels === 1;\n const { offsetSamples, durationSamples } = resolveClipRange(\n clip,\n registeredClipRange(\n spectrogramCanvasRegistryRef.current.get(clip.id),\n canvasRangesRef.current\n )\n );\n\n clipsToRender.push({\n clipId: clip.id,\n audioKey: audioKeyOf(clip.audioBuffer),\n channelDataArrays: channelData(clip.audioBuffer),\n config: cfg,\n sampleRate: clip.audioBuffer.sampleRate,\n offsetSamples,\n durationSamples,\n clipStartSample: clip.startSample,\n monoFlag,\n colorMap: cm,\n });\n }\n });\n\n if (clipsToRender.length === 0) return;\n\n // Three-tier chunk classification:\n // - viewportIndices: chunks intersecting the exact viewport (phase 1a — fast first paint)\n // - bufferIndices: chunks in the 1.5× overscan buffer but outside viewport (phase 1b)\n // - remainingIndices: chunks outside the buffer (phase 2 — background batches)\n const getVisibleChunkRange = (\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n clipPixelOffset = 0\n ): ChunkTiers => {\n const container = scrollContainerRef.current;\n return classifyChunkTiers(\n channelInfo,\n clipPixelOffset,\n container\n ? { scrollLeft: container.scrollLeft, viewportWidth: container.clientWidth }\n : null\n );\n };\n\n const renderChunkSubset = async (\n api: SpectrogramWorkerApi,\n cacheKey: string,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n requestedIndices: number[],\n item: { config: SpectrogramConfig; colorMap: ColorMapValue },\n channelIndex: number,\n gen: number\n ) => {\n // Indices are derived from channel 0's registry; this channel may have\n // registered fewer canvases so far (#562). Skipped chunks render on the\n // next pass — registration bumps spectrogramCanvasVersion.\n const indices = presentChunkIndices(channelInfo, requestedIndices);\n if (indices.length === 0) return;\n\n const canvasIds = indices.map((i) => channelInfo.canvasIds[i]);\n const canvasWidths = indices.map((i) => channelInfo.canvasWidths[i]);\n // The chunks of one channel are all as tall as the first.\n const canvasHeight = canvasHeightsRef.current.get(canvasIds[0]);\n if (canvasHeight === undefined) return;\n\n // Compute correct global pixel offsets by extracting chunk numbers from\n // canvas IDs. With virtual scrolling, the registry may contain non-consecutive\n // chunks (e.g., chunks 50-55), so summing widths from index 0 gives wrong offsets.\n const globalPixelOffsets: number[] = [];\n for (const idx of indices) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[idx]);\n globalPixelOffsets.push(chunkNumber * MAX_CANVAS_WIDTH);\n }\n\n const colorLUT = getColorMap(item.colorMap);\n\n await api.renderChunks(\n {\n cacheKey,\n canvasIds,\n canvasWidths,\n globalPixelOffsets,\n canvasHeight,\n devicePixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio : 1,\n samplesPerPixel,\n colorLUT,\n frequencyScale: item.config.frequencyScale ?? 'mel',\n minFrequency: item.config.minFrequency ?? 0,\n maxFrequency: item.config.maxFrequency ?? 0,\n gainDb: item.config.gainDb ?? 20,\n rangeDb: item.config.rangeDb ?? 80,\n channelIndex,\n },\n gen\n );\n };\n\n // Compute FFT for the sample range covered by a set of chunk indices.\n // Returns the cache key (data covers all channels).\n // This avoids computing a single full-clip FFT (which OOMs on 1hr+ files)\n // by computing per-batch ranges on demand.\n const computeFFTForChunks = async (\n api: SpectrogramWorkerApi,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n indices: number[],\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n },\n gen: number\n ): Promise<string> => {\n // Determine the (window-padded) sample range these chunks cover.\n const { paddedStart, paddedEnd } = computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize: item.config.fftSize ?? 2048,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n samplesPerPixel,\n });\n\n const { cacheKey } = await api.computeFFT(\n {\n // The pool's \"clip id\" names the registered audio: the buffer's key.\n clipId: item.audioKey,\n channelDataArrays: item.channelDataArrays,\n config: item.config,\n sampleRate: item.sampleRate,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n mono: item.monoFlag,\n sampleRange: { start: paddedStart, end: paddedEnd },\n },\n gen\n );\n\n return cacheKey;\n };\n\n const computeAsync = async () => {\n const abortToken = { aborted: false };\n backgroundRenderAbortRef.current = abortToken;\n\n // Render off-screen chunks in idle-callback batches, computing FFT\n // per contiguous group to avoid allocating one giant Float32Array for the\n // full clip (which OOMs on 1hr+ files — e.g., 310K frames × 2048 bins = 2.5GB).\n // Groups remaining indices into contiguous runs (e.g., [0,1,4,5] → [0,1]+[4,5])\n // so each FFT only covers the sample range actually needed.\n // Returns true if aborted (caller should return early).\n const renderBackgroundBatches = async (\n channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n remainingIndices: number[];\n }>,\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }\n ): Promise<boolean> => {\n // Collect all contiguous groups across channels, then render\n // each group for ALL channels before moving to the next group\n // (multi-channel fairness — avoids ch1 starvation).\n const allGroups: Array<{\n group: number[];\n channelRangeEntries: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n }>;\n }> = [];\n\n // Build contiguous groups from the first channel's remaining indices\n // (all channels have the same chunk layout).\n if (channelRanges.length > 0) {\n const { channelInfo, remainingIndices } = channelRanges[0];\n const groups = groupContiguousIndices(channelInfo, remainingIndices);\n for (const group of groups) {\n allGroups.push({\n group,\n channelRangeEntries: channelRanges.map(({ ch, channelInfo: ci }) => ({\n ch,\n channelInfo: ci,\n })),\n });\n }\n }\n\n for (const { group, channelRangeEntries } of allGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n await new Promise<void>((resolve) => {\n if (typeof requestIdleCallback === 'function') {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n // Compute FFT once for this contiguous group (covers all channels)\n const { channelInfo: firstChannelInfo } = channelRangeEntries[0];\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n firstChannelInfo,\n group,\n item,\n generation\n );\n\n // Render all channels from the cached FFT data\n for (const { ch, channelInfo: ci } of channelRangeEntries) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n await renderChunkSubset(workerApi!, cacheKey, ci, group, item, ch, generation);\n }\n }\n return false;\n };\n\n for (const item of clipsToRender) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n try {\n const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);\n if (clipCanvasInfo && clipCanvasInfo.size > 0) {\n const numChannels = item.monoFlag ? 1 : item.channelDataArrays.length;\n const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);\n\n // Three-phase rendering:\n // Phase 1a: viewport-only chunks (fast first paint)\n // Phase 1b: buffer-zone chunks (prevents black chunks on scroll)\n // Phase 2: off-screen chunks (background batches)\n const channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n viewportIndices: number[];\n bufferIndices: number[];\n remainingIndices: number[];\n }> = [];\n\n for (let ch = 0; ch < numChannels; ch++) {\n const channelInfo = clipCanvasInfo.get(ch);\n if (!channelInfo) continue;\n const range = getVisibleChunkRange(channelInfo, clipPixelOffset);\n channelRanges.push({ ch, channelInfo, ...range });\n }\n\n // Phase 1a: Compute FFT for viewport chunks only, render all channels\n if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n channelRanges[0].viewportIndices,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo, viewportIndices } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n viewportIndices,\n item,\n ch,\n generation\n );\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 1b: Compute FFT for buffer-zone chunks, render all channels.\n // Buffer indices may be non-contiguous (e.g., chunks [10,14,15] from\n // indices [0,3,4,5]), so group them to avoid spanning a huge FFT range.\n if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {\n const bufferGroups = groupContiguousIndices(\n channelRanges[0].channelInfo,\n channelRanges[0].bufferIndices\n );\n\n for (const group of bufferGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n group,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n group,\n item,\n ch,\n generation\n );\n }\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 2: Render off-screen chunks in background batches\n // (each batch computes its own bounded FFT range).\n if (await renderBackgroundBatches(channelRanges, item)) return;\n }\n } catch (err) {\n if (err instanceof SpectrogramAbortError) return;\n console.warn(\n `[waveform-playlist] Spectrogram worker error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n };\n\n computeAsync().catch((err) => {\n console.error(\n `[waveform-playlist] Spectrogram computation failed: ${err instanceof Error ? err.message : String(err)}`\n );\n });\n }, [\n tracks,\n mono,\n spectrogramConfig,\n spectrogramColorMap,\n samplesPerPixel,\n spectrogramCanvasVersion,\n scrollContainerRef,\n audioKeyOf,\n ensureWorkerPool,\n ]);\n\n // Setters: each a change of the track in the arrangement, so an undo step\n // (#814). Returning the track as it is changes nothing and pushes no step:\n // the mode it is already drawn with (an unset one is 'waveform'), and any\n // mode for a MIDI track, which is drawn as a piano roll (review of #930).\n const setTrackRenderMode = useCallback(\n (trackId: string, mode: RenderMode) => {\n arrangement.updateTrack(trackId, (track: ArrangementTrack) =>\n trackKind(track) === 'midi' || resolveRenderMode(track.renderMode) === mode\n ? track\n : { ...track, renderMode: mode }\n );\n },\n [arrangement]\n );\n\n const setTrackSpectrogramConfig = useCallback(\n (trackId: string, config: SpectrogramConfig, colorMap?: ColorMapValue) => {\n // The render mode is left as it is (review of #926).\n arrangement.updateTrack(trackId, (track: ArrangementTrack) => ({\n ...track,\n spectrogramConfig: config,\n spectrogramColorMap: colorMap ?? track.spectrogramColorMap,\n }));\n },\n [arrangement]\n );\n\n const registerSpectrogramCanvas = useCallback(\n (reg: SpectrogramCanvasRegistration) => {\n const pool = ensureWorkerPool();\n if (!pool) return;\n\n try {\n pool.registerCanvas(reg.canvasId, reg.canvas);\n } catch (err) {\n console.warn(\n `[waveform-playlist] registerCanvas failed for ${reg.canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n return;\n }\n\n canvasHeightsRef.current.set(reg.canvasId, reg.heightPx);\n if (reg.offsetSamples !== undefined || reg.durationSamples !== undefined) {\n canvasRangesRef.current.set(reg.canvasId, {\n offsetSamples: reg.offsetSamples,\n durationSamples: reg.durationSamples,\n });\n } else {\n canvasRangesRef.current.delete(reg.canvasId);\n }\n const registry = spectrogramCanvasRegistryRef.current;\n if (!registry.has(reg.clipId)) {\n registry.set(reg.clipId, new Map());\n }\n const perClip = registry.get(reg.clipId)!;\n const entry = perClip.get(reg.channelIndex) ?? { canvasIds: [], canvasWidths: [] };\n const existingIdx = entry.canvasIds.indexOf(reg.canvasId);\n if (existingIdx >= 0) {\n entry.canvasWidths[existingIdx] = reg.widthPx;\n } else {\n entry.canvasIds.push(reg.canvasId);\n entry.canvasWidths.push(reg.widthPx);\n }\n perClip.set(reg.channelIndex, entry);\n setSpectrogramCanvasVersion((v) => v + 1);\n },\n [ensureWorkerPool]\n );\n\n const unregisterSpectrogramCanvas = useCallback((canvasId: string) => {\n canvasHeightsRef.current.delete(canvasId);\n canvasRangesRef.current.delete(canvasId);\n const pool = spectrogramWorkerRef.current;\n if (pool) {\n try {\n pool.unregisterCanvas(canvasId);\n } catch (err) {\n console.warn(\n `[waveform-playlist] unregisterCanvas failed for ${canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Canvas IDs follow the format `${clipId}-ch${channelIndex}-chunk${n}`.\n const parsed = parseCanvasId(canvasId);\n if (!parsed) return;\n const { clipId, channelIndex } = parsed;\n\n const registry = spectrogramCanvasRegistryRef.current;\n const perClip = registry.get(clipId);\n if (!perClip) return;\n const entry = perClip.get(channelIndex);\n if (!entry) return;\n const idx = entry.canvasIds.indexOf(canvasId);\n if (idx >= 0) {\n entry.canvasIds.splice(idx, 1);\n entry.canvasWidths.splice(idx, 1);\n }\n if (entry.canvasIds.length === 0) {\n perClip.delete(channelIndex);\n }\n if (perClip.size === 0) {\n registry.delete(clipId);\n }\n setSpectrogramCanvasVersion((v) => v + 1);\n }, []);\n\n const renderMenuItems = useCallback(\n (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => {\n return spectrogramMenuItems({\n renderMode: props.renderMode as RenderMode,\n onRenderModeChange: props.onRenderModeChange,\n onOpenSettings: props.onOpenSettings,\n onClose: props.onClose,\n });\n },\n []\n );\n\n const value: SpectrogramIntegration = useMemo(\n () => ({\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n SettingsModal: SpectrogramSettingsModal,\n getColorMap,\n getFrequencyScale: getFrequencyScale as (\n name: string\n ) => (f: number, minF: number, maxF: number) => number,\n }),\n [\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n ]\n );\n\n return <SpectrogramIntegrationContext value={value}>{children}</SpectrogramIntegrationContext>;\n};\n","import {\n MAX_CANVAS_WIDTH,\n parseSpectrogramCanvasId,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n} from '@waveform-playlist/core';\nimport { computePaddedFftRange } from '@dawcore/spectrogram';\n\n/**\n * Pure, side-effect-free helpers extracted from `SpectrogramProvider`.\n *\n * These cover the geometry/key logic that the provider's worker-orchestration\n * effect depends on (chunk classification, FFT sample ranges, contiguous\n * grouping, config-change detection). Keeping them DOM-free makes them unit\n * testable in a Node environment — the provider supplies the imperative shell\n * (refs, worker calls, React state) around this functional core.\n */\n\n/** A channel's registered canvas chunks: parallel arrays of IDs and pixel widths. */\nexport interface ChannelChunkInfo {\n canvasIds: string[];\n canvasWidths: number[];\n}\n\n/** Chunk indices grouped by their relationship to the current scroll viewport. */\nexport interface ChunkTiers {\n /** Chunks intersecting the exact viewport — fast first paint. */\n viewportIndices: number[];\n /** Chunks within the 1.5× overscan buffer but outside the viewport. */\n bufferIndices: number[];\n /** Chunks outside the buffer — rendered in background batches. */\n remainingIndices: number[];\n}\n\n/** Scroll-container metrics needed to classify chunks. `null` ⇒ no container yet. */\nexport interface ViewportMetrics {\n scrollLeft: number;\n viewportWidth: number;\n}\n\n/**\n * Extract the chunk number from a canvas ID like `\"clipId-ch0-chunk5\"` → `5`.\n * Delegates to the canonical `parseSpectrogramCanvasId`; warns and returns `0`\n * when the ID doesn't match the `${clipId}-ch${channelIndex}-chunk${n}` format.\n */\nexport function extractChunkNumber(canvasId: string): number {\n const parsed = parseSpectrogramCanvasId(canvasId);\n if (!parsed) {\n console.warn(`[spectrogram] Unexpected canvas ID format: ${canvasId}`);\n return 0;\n }\n return parsed.chunkIndex;\n}\n\n/**\n * Keep only indices whose canvas is registered for THIS channel.\n *\n * Chunk indices are derived once from channel 0's registry and reused across\n * channels, but canvases register progressively per channel — a later channel\n * can briefly hold fewer entries, and indexing past its registry threw\n * `Cannot read properties of undefined (reading 'match')` (#562). Skipped\n * chunks render on the next pass: registration bumps `spectrogramCanvasVersion`.\n */\nexport function presentChunkIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[] {\n return indices.filter((i) => channelInfo.canvasIds[i] !== undefined);\n}\n\n/**\n * Parse a canvas ID of the form `${clipId}-ch${channelIndex}-chunk${n}` into its\n * clip ID and channel index. Returns `null` when the ID doesn't match.\n */\nexport function parseCanvasId(canvasId: string): { clipId: string; channelIndex: number } | null {\n const parsed = parseSpectrogramCanvasId(canvasId);\n return parsed ? { clipId: parsed.clipId, channelIndex: parsed.channelIndex } : null;\n}\n\n/**\n * Split indices into contiguous groups based on their chunk numbers, e.g.\n * indices mapping to chunks `[0,1,4,5]` → `[[0,1],[4,5]]`. Prevents computing an\n * FFT range that spans the gap between non-adjacent chunks.\n */\nexport function groupContiguousIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[][] {\n if (indices.length === 0) return [];\n const groups: number[][] = [];\n let currentGroup = [indices[0]];\n let prevChunk = extractChunkNumber(channelInfo.canvasIds[indices[0]]);\n for (let i = 1; i < indices.length; i++) {\n const chunk = extractChunkNumber(channelInfo.canvasIds[indices[i]]);\n if (chunk === prevChunk + 1) {\n currentGroup.push(indices[i]);\n } else {\n groups.push(currentGroup);\n currentGroup = [indices[i]];\n }\n prevChunk = chunk;\n }\n groups.push(currentGroup);\n return groups;\n}\n\n/**\n * Classify a channel's chunks into viewport / buffer / remaining tiers.\n *\n * The buffer uses a 1.5× viewport-width overscan to match\n * `useVisibleChunkIndices` in ScrollViewport, so FFT covers every mounted\n * canvas. When `viewport` is `null` (no scroll container yet), every chunk is\n * treated as in-viewport.\n */\nexport function classifyChunkTiers(\n channelInfo: ChannelChunkInfo,\n clipPixelOffset = 0,\n viewport: ViewportMetrics | null\n): ChunkTiers {\n if (!viewport) {\n return {\n viewportIndices: channelInfo.canvasWidths.map((_, i) => i),\n bufferIndices: [],\n remainingIndices: [],\n };\n }\n\n const { scrollLeft, viewportWidth } = viewport;\n const buffer = viewportWidth * 1.5;\n const bufferStart = Math.max(0, scrollLeft - buffer);\n const bufferEnd = scrollLeft + viewportWidth + buffer;\n\n const viewportIndices: number[] = [];\n const bufferIndices: number[] = [];\n const remainingIndices: number[] = [];\n\n for (let i = 0; i < channelInfo.canvasWidths.length; i++) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[i]);\n const chunkLeft = chunkNumber * MAX_CANVAS_WIDTH + clipPixelOffset;\n const chunkRight = chunkLeft + channelInfo.canvasWidths[i];\n if (chunkRight > scrollLeft && chunkLeft < scrollLeft + viewportWidth) {\n viewportIndices.push(i);\n } else if (chunkRight > bufferStart && chunkLeft < bufferEnd) {\n bufferIndices.push(i);\n } else {\n remainingIndices.push(i);\n }\n }\n\n return { viewportIndices, bufferIndices, remainingIndices };\n}\n\nexport interface ChunkSampleRangeParams {\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n indices: number[];\n /** FFT window size (samples) used to pad the range against edge artifacts. */\n fftSize: number;\n offsetSamples: number;\n durationSamples: number;\n samplesPerPixel: number;\n}\n\n/**\n * Compute the (window-padded, clip-clamped) sample range covered by a set of\n * chunk indices. Computing per-batch ranges on demand avoids allocating one\n * giant FFT array for a full clip (which OOMs on 1hr+ files).\n */\nexport function computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n}: ChunkSampleRangeParams): { paddedStart: number; paddedEnd: number } {\n return computePaddedFftRange({\n chunks: indices.map((i) => ({\n chunkIndex: extractChunkNumber(channelInfo.canvasIds[i]),\n widthPx: channelInfo.canvasWidths[i],\n })),\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n });\n}\n\n/** Resolve a track's effective render mode: the track's own, else `'waveform'`. */\nexport function resolveRenderMode(trackRenderMode: RenderMode | undefined): RenderMode {\n return trackRenderMode ?? 'waveform';\n}\n\n/**\n * Stable string key for a track's full spectrogram appearance (mode + config +\n * color map + mono). A change means the rendered output must be recomputed.\n */\nexport function buildConfigKey(params: {\n mode: RenderMode;\n cfg: SpectrogramConfig | undefined;\n cm: ColorMapValue | undefined;\n mono: boolean;\n}): string {\n const { mode, cfg, cm, mono } = params;\n return JSON.stringify({ mode, cfg, cm, mono });\n}\n\n/**\n * Whether two key maps differ — different size, or any key present in `current`\n * whose value doesn't match `prev`. Used to detect config/FFT changes between\n * effect runs.\n */\nexport function mapsDiffer(prev: Map<string, string>, current: Map<string, string>): boolean {\n if (current.size !== prev.size) return true;\n for (const [key, value] of current) {\n if (prev.get(key) !== value) return true;\n }\n return false;\n}\n\n/** The range of the audio a canvas registered with (`SpectrogramCanvasRegistration`). */\nexport interface RegisteredAudioRange {\n offsetSamples?: number;\n durationSamples?: number;\n}\n\n/**\n * The range a clip's canvases registered with: that of the first canvas that\n * gave one (all canvases of a clip are drawn for the same range; a new range\n * registers new canvases). `undefined` when none gave one.\n */\nexport function registeredClipRange(\n perClip: ReadonlyMap<number, ChannelChunkInfo> | undefined,\n rangeByCanvasId: ReadonlyMap<string, RegisteredAudioRange>\n): RegisteredAudioRange | undefined {\n if (!perClip) return undefined;\n for (const channelInfo of perClip.values()) {\n for (const canvasId of channelInfo.canvasIds) {\n const range = rangeByCanvasId.get(canvasId);\n if (range) return range;\n }\n }\n return undefined;\n}\n\n/**\n * The range to draw a clip for: what its canvases registered with (the view\n * may draw a clip the tracks do not have yet, a trim being dragged), field by\n * field, else the clip's own.\n */\nexport function resolveClipRange(\n clip: { offsetSamples: number; durationSamples: number },\n registered: RegisteredAudioRange | undefined\n): { offsetSamples: number; durationSamples: number } {\n return {\n offsetSamples: registered?.offsetSamples ?? clip.offsetSamples,\n durationSamples: registered?.durationSamples ?? clip.durationSamples,\n };\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\nimport { resolveRenderMode } from './spectrogram-helpers';\n\n/**\n * The key an AudioBuffer's audio is registered under in the worker pool, the\n * same for as long as the buffer lives. Clips that share a buffer share the\n * key (a split keeps one buffer for both halves), so the pool holds the audio\n * once (#821). The worker's FFT cache key also carries each clip's range, so\n * two clips over different parts of one buffer keep separate entries.\n */\nexport type AudioKeyOf = (buffer: AudioBuffer) => string;\n\nexport function createAudioKeyOf(): AudioKeyOf {\n const keys = new WeakMap<AudioBuffer, string>();\n let next = 0;\n return (buffer) => {\n const existing = keys.get(buffer);\n if (existing !== undefined) return existing;\n next += 1;\n const key = `audio-${next}`;\n keys.set(buffer, key);\n return key;\n };\n}\n\n/**\n * The audio the pool should hold, by key: each buffer that a clip on a track\n * drawing a spectrogram (`spectrogram` or `both`) uses. A waveform track's\n * audio is never computed, so it is not sent (#821).\n */\nexport function spectrogramAudio(\n tracks: readonly ClipTrack[],\n audioKeyOf: AudioKeyOf\n): Map<string, AudioBuffer> {\n const wanted = new Map<string, AudioBuffer>();\n for (const track of tracks) {\n if (resolveRenderMode(track.renderMode) === 'waveform') continue;\n for (const clip of track.clips) {\n if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);\n }\n }\n return wanted;\n}\n\n/** Every channel of a buffer, as the views `getChannelData` returns (not copies). */\nexport function channelData(buffer: AudioBuffer): Float32Array[] {\n return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));\n}\n","import { useMemo } from 'react';\n\n/**\n * The value as it was the last time its JSON content changed. For plain-data\n * props an app often writes inline (`config={{ fftSize: 2048 }}`): a new\n * object with the same content keeps the old one, so the context value and\n * the effects that depend on it do not change on every render of the app\n * (#821). Only for values JSON describes completely (no functions, no class\n * instances); a key whose value is `undefined` counts as absent.\n */\nexport function useStableByContent<T>(value: T): T {\n const content = JSON.stringify(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the content, not the identity\n return useMemo(() => value, [content]);\n}\n"],"mappings":";AACA,OAAO,YAAY;AA6ET,cAEE,YAFF;AArEV,IAAM,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS5B,IAAM,aAAa,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa1B,IAAM,iBAAiB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAe9B,IAAM,kBAAkB,OAAO;AAAA;AAAA;AAI/B,IAAM,eAAuD;AAAA,EAC3D,EAAE,OAAO,YAAY,OAAO,WAAW;AAAA,EACvC,EAAE,OAAO,eAAe,OAAO,cAAc;AAAA,EAC7C,EAAE,OAAO,QAAQ,OAAO,OAAO;AACjC;AAaO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,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cAAQ,OAAO,YAAY;AAAA,IAC7B;AACA,QAAI,QAAQ,SAAS,GAAG;AACtB,eAAS,OAAO,MAAM;AAAA,IACxB;AACA,gCAA4B,CAAC,MAAM,IAAI,CAAC;AAAA,EAC1C,GAAG,CAAC,CAAC;AAEL,QAAM,kBAAkB;AAAA,IACtB,CAAC,UAKK;AACJ,aAAO,qBAAqB;AAAA,QAC1B,YAAY,MAAM;AAAA,QAClB,oBAAoB,MAAM;AAAA,QAC1B,gBAAgB,MAAM;AAAA,QACtB,SAAS,MAAM;AAAA,MACjB,CAAC;AAAA,IACH;AAAA,IACA,CAAC;AAAA,EACH;AAEA,QAAM,QAAgCC;AAAA,IACpC,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA;AAAA,IAGF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,gBAAAP,KAAC,iCAA8B,OAAe,UAAS;AAChE;","names":["styled","jsx","jsxs","useState","useEffect","useRef","useMemo","MAX_CANVAS_WIDTH","jsx","useRef","useState","useEffect","MAX_CANVAS_WIDTH","config","colorMap","useMemo"]}
1
+ {"version":3,"sources":["../src/components/SpectrogramMenuItems.tsx","../src/components/SpectrogramSettingsModal.tsx","../src/SpectrogramProvider.tsx","../src/spectrogram-helpers.ts","../src/audioRegistration.ts","../src/useStableByContent.ts"],"sourcesContent":["import React from 'react';\nimport styled from 'styled-components';\nimport type { RenderMode } from '@waveform-playlist/core';\nimport type { SpectrogramIntegration } from '@waveform-playlist/browser';\n\n/** The items browser's track menu asks the spectrogram integration for:\n * ui-components' `TrackMenuItem[]`, named through the type that carries it. */\ntype MenuItems = ReturnType<NonNullable<SpectrogramIntegration['renderMenuItems']>>;\n\nconst SectionLabel = styled.div`\n font-size: 0.65rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.5;\n margin-bottom: 0.25rem;\n`;\n\nconst RadioLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n padding: 0.2rem 0;\n font-size: 0.8rem;\n cursor: pointer;\n\n &:hover {\n opacity: 0.8;\n }\n`;\n\nconst SettingsButton = styled.button`\n background: none;\n border: none;\n color: inherit;\n cursor: pointer;\n font-size: 0.8rem;\n padding: 0.35rem 0.75rem;\n width: 100%;\n text-align: left;\n\n &:hover {\n background: rgba(128, 128, 128, 0.15);\n }\n`;\n\nconst DropdownSection = styled.div`\n padding: 0.25rem 0.75rem;\n`;\n\nconst RENDER_MODES: { value: RenderMode; label: string }[] = [\n { value: 'waveform', label: 'Waveform' },\n { value: 'spectrogram', label: 'Spectrogram' },\n { value: 'both', label: 'Both' },\n];\n\nexport interface SpectrogramMenuItemsOptions {\n renderMode: RenderMode;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n}\n\n/**\n * Returns the track menu items (`TrackMenuItem[]` of ui-components) for the\n * spectrogram display mode radios and settings button.\n */\nexport function spectrogramMenuItems({\n renderMode,\n onRenderModeChange,\n onOpenSettings,\n onClose,\n}: SpectrogramMenuItemsOptions): MenuItems {\n return [\n {\n id: 'spectrogram-display',\n content: (\n <DropdownSection>\n <SectionLabel>Display</SectionLabel>\n {RENDER_MODES.map(({ value, label }) => (\n <RadioLabel key={value}>\n <input\n type=\"radio\"\n name=\"render-mode\"\n checked={renderMode === value}\n onChange={() => {\n onRenderModeChange(value);\n onClose?.();\n }}\n />\n {label}\n </RadioLabel>\n ))}\n </DropdownSection>\n ),\n },\n {\n id: 'spectrogram-settings',\n content: (\n <SettingsButton\n onClick={(e) => {\n e.stopPropagation();\n onClose?.();\n onOpenSettings();\n }}\n onMouseDown={(e) => e.stopPropagation()}\n >\n Spectrogram Settings...\n </SettingsButton>\n ),\n },\n ];\n}\n","import React, { useRef, useEffect, useId, useLayoutEffect, useState } from 'react';\nimport styled from 'styled-components';\nimport {\n SPECTROGRAM_DEFAULTS,\n type SpectrogramConfig,\n type ColorMapValue,\n type ColorMapName,\n type FFTSize,\n} from '@waveform-playlist/core';\n\nexport interface SpectrogramSettingsModalProps {\n open: boolean;\n onClose: () => void;\n config: SpectrogramConfig;\n colorMap: ColorMapValue;\n /**\n * Called on Apply with the config it was given plus the fields the user\n * changed, and the colour map (the one given unless the user picked one).\n * Not called when nothing was changed: Apply then only closes.\n */\n onApply: (config: SpectrogramConfig, colorMap: ColorMapValue) => void;\n /**\n * The sample rate of the audio. With a config that has no `maxFrequency`,\n * the field shows half of it, the top the spectrogram is drawn to.\n */\n sampleRate?: number;\n}\n\nconst StyledDialog = styled.dialog`\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 8px;\n padding: 1.5rem;\n background: ${(p) => p.theme.timescaleBackgroundColor ?? '#222'};\n color: ${(p) => p.theme.textColor ?? 'inherit'};\n min-width: 380px;\n max-width: 500px;\n overscroll-behavior: contain;\n\n &::backdrop {\n background: rgba(0, 0, 0, 0.5);\n }\n`;\n\nconst Title = styled.h3`\n margin: 0 0 1rem;\n font-size: 1rem;\n`;\n\nconst FormGrid = styled.div`\n display: grid;\n grid-template-columns: 1fr 1fr;\n gap: 0.75rem;\n`;\n\nconst Field = styled.div<{ $span?: boolean }>`\n display: flex;\n flex-direction: column;\n gap: 0.2rem;\n grid-column: ${(p) => (p.$span ? '1 / -1' : 'auto')};\n`;\n\nconst Label = styled.label`\n font-size: 0.7rem;\n font-weight: 600;\n text-transform: uppercase;\n letter-spacing: 0.05em;\n opacity: 0.6;\n`;\n\nconst Select = styled.select`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n`;\n\nconst NumberInput = styled.input`\n padding: 0.3rem 0.4rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n background: rgba(128, 128, 128, 0.15);\n color: inherit;\n font-size: 0.85rem;\n width: 100%;\n box-sizing: border-box;\n`;\n\nconst CheckboxLabel = styled.label`\n display: flex;\n align-items: center;\n gap: 0.4rem;\n font-size: 0.85rem;\n cursor: pointer;\n`;\n\nconst ButtonRow = styled.div`\n display: flex;\n justify-content: flex-end;\n gap: 0.5rem;\n margin-top: 1.25rem;\n`;\n\nconst ModalButton = styled.button<{ $primary?: boolean }>`\n padding: 0.4rem 1rem;\n border: 1px solid rgba(128, 128, 128, 0.4);\n border-radius: 4px;\n cursor: pointer;\n font-size: 0.85rem;\n background: ${(p) => (p.$primary ? (p.theme.buttonBackground ?? '#0091ff') : 'transparent')};\n color: ${(p) => (p.$primary ? (p.theme.buttonText ?? '#fff') : 'inherit')};\n ${(p) => (p.$primary && p.theme.buttonBorder ? `border-color: ${p.theme.buttonBorder};` : '')}\n\n &:hover {\n ${(p) =>\n p.$primary && p.theme.buttonHoverBackground\n ? `background: ${p.theme.buttonHoverBackground};`\n : 'opacity: 0.85;'}\n }\n`;\n\nconst FFT_SIZES = [256, 512, 1024, 2048, 4096, 8192];\nconst WINDOW_FUNCTIONS = [\n 'hann',\n 'hamming',\n 'blackman',\n 'blackman-harris',\n 'bartlett',\n 'rectangular',\n] as const;\nconst FREQ_SCALES = ['linear', 'logarithmic', 'mel', 'bark', 'erb'] as const;\nconst COLOR_MAPS: ColorMapName[] = ['viridis', 'magma', 'inferno', 'grayscale', 'igray', 'roseus'];\n/** The select's value for a colour map given as an array of colours. */\nconst CUSTOM_COLOR_MAP = 'custom';\n\ntype SettingsFormProps = Omit<SpectrogramSettingsModalProps, 'open'>;\n\n/**\n * The form is a draft of the settings. It is mounted only while the dialog is\n * open, so its state starts from the props each time the dialog opens and is\n * never overwritten by a parent re-render while the user is editing.\n *\n * The draft holds only the fields the user changed (#814). A field shows its\n * edit, else the config's value, else the default; Apply sends the config it\n * was given with the edits on top, so a field the form does not show\n * (`alpha`, `labelsColor`, `labelsBackground`) and a field left at its default\n * (`maxFrequency`: half the sample rate) are not written.\n */\nconst SettingsForm: React.FC<SettingsFormProps> = ({\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const id = useId();\n const [edits, setEdits] = useState<SpectrogramConfig>({});\n const [editedColorMap, setEditedColorMap] = useState<ColorMapName | undefined>(undefined);\n\n const shown = <K extends keyof SpectrogramConfig>(key: K): SpectrogramConfig[K] =>\n key in edits ? edits[key] : config[key];\n const edit = (changes: SpectrogramConfig) => setEdits((prev) => ({ ...prev, ...changes }));\n\n const fftSize = shown('fftSize') ?? SPECTROGRAM_DEFAULTS.fftSize;\n const hopSize = shown('hopSize') ?? Math.floor(fftSize / 4);\n const zeroPadding = shown('zeroPaddingFactor') ?? SPECTROGRAM_DEFAULTS.zeroPaddingFactor;\n const windowFn = shown('windowFunction') ?? SPECTROGRAM_DEFAULTS.windowFunction;\n const freqScale = shown('frequencyScale') ?? SPECTROGRAM_DEFAULTS.frequencyScale;\n const minFreq = shown('minFrequency') ?? SPECTROGRAM_DEFAULTS.minFrequency;\n const nyquist = sampleRate !== undefined ? sampleRate / 2 : undefined;\n // An emptied field stays empty while the user types (Apply then leaves the\n // default); only an untouched one shows the default's number.\n const maxFreq = 'maxFrequency' in edits ? edits.maxFrequency : (config.maxFrequency ?? nyquist);\n const gainDb = shown('gainDb') ?? SPECTROGRAM_DEFAULTS.gainDb;\n const rangeDb = shown('rangeDb') ?? SPECTROGRAM_DEFAULTS.rangeDb;\n const showLabels = shown('labels') ?? SPECTROGRAM_DEFAULTS.labels;\n const isCustomColorMap = typeof colorMap !== 'string';\n const colorMapValue = editedColorMap ?? (isCustomColorMap ? CUSTOM_COLOR_MAP : colorMap);\n\n const handleApply = () => {\n // A field set back to the value it had is no change. With none, Apply\n // only closes: an onApply would be an undo step that changes nothing.\n const configChanged = (Object.keys(edits) as Array<keyof SpectrogramConfig>).some(\n (key) => edits[key] !== config[key]\n );\n const colorMapChanged = editedColorMap !== undefined && editedColorMap !== colorMap;\n if (configChanged || colorMapChanged) {\n onApply({ ...config, ...edits }, editedColorMap ?? colorMap);\n }\n onClose();\n };\n\n return (\n <>\n <FormGrid>\n <Field>\n <Label htmlFor={`${id}-fft-size`}>FFT Size</Label>\n <Select\n id={`${id}-fft-size`}\n value={fftSize}\n onChange={(e) => {\n const v = Number(e.target.value) as FFTSize;\n edit({ fftSize: v, hopSize: Math.floor(v / 4) });\n }}\n >\n {FFT_SIZES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-hop-size`}>Hop Size</Label>\n <Select\n id={`${id}-hop-size`}\n value={hopSize}\n onChange={(e) => edit({ hopSize: Number(e.target.value) })}\n >\n {[\n { label: `${fftSize} (no overlap)`, value: fftSize },\n { label: `${Math.floor(fftSize / 2)} (50%)`, value: Math.floor(fftSize / 2) },\n { label: `${Math.floor(fftSize / 4)} (75%)`, value: Math.floor(fftSize / 4) },\n { label: `${Math.floor(fftSize / 8)} (87.5%)`, value: Math.floor(fftSize / 8) },\n ].map((o) => (\n <option key={o.value} value={o.value}>\n {o.label}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-zero-padding`}>Zero Padding</Label>\n <Select\n id={`${id}-zero-padding`}\n value={zeroPadding}\n onChange={(e) => edit({ zeroPaddingFactor: Number(e.target.value) })}\n >\n {[1, 2, 4, 8, 16].map((v) => (\n <option key={v} value={v}>\n {v}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-window-function`}>Window Function</Label>\n <Select\n id={`${id}-window-function`}\n value={windowFn}\n onChange={(e) =>\n edit({ windowFunction: e.target.value as SpectrogramConfig['windowFunction'] })\n }\n >\n {WINDOW_FUNCTIONS.map((w) => (\n <option key={w} value={w}>\n {w}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-frequency-scale`}>Frequency Scale</Label>\n <Select\n id={`${id}-frequency-scale`}\n value={freqScale}\n onChange={(e) =>\n edit({ frequencyScale: e.target.value as SpectrogramConfig['frequencyScale'] })\n }\n >\n {FREQ_SCALES.map((s) => (\n <option key={s} value={s}>\n {s}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-color-map`}>Color Map</Label>\n <Select\n id={`${id}-color-map`}\n value={colorMapValue}\n onChange={(e) =>\n // \"custom\" is the colour map given (an array): no edit.\n setEditedColorMap(\n e.target.value === CUSTOM_COLOR_MAP ? undefined : (e.target.value as ColorMapName)\n )\n }\n >\n {isCustomColorMap && <option value={CUSTOM_COLOR_MAP}>{CUSTOM_COLOR_MAP}</option>}\n {COLOR_MAPS.map((c) => (\n <option key={c} value={c}>\n {c}\n </option>\n ))}\n </Select>\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-min-frequency`}>Min Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-min-frequency`}\n type=\"number\"\n min={0}\n max={5000}\n step={50}\n value={minFreq}\n onChange={(e) => edit({ minFrequency: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-max-frequency`}>Max Frequency (Hz)</Label>\n <NumberInput\n id={`${id}-max-frequency`}\n type=\"number\"\n min={1000}\n max={nyquist}\n step={50}\n value={maxFreq ?? ''}\n onChange={(e) =>\n // Emptied: back to the default, half the sample rate.\n edit({ maxFrequency: e.target.value === '' ? undefined : Number(e.target.value) })\n }\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-range-db`}>Range (dB)</Label>\n <NumberInput\n id={`${id}-range-db`}\n type=\"number\"\n min={1}\n max={120}\n step={1}\n value={rangeDb}\n onChange={(e) => edit({ rangeDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field>\n <Label htmlFor={`${id}-gain-db`}>Gain (dB)</Label>\n <NumberInput\n id={`${id}-gain-db`}\n type=\"number\"\n min={-20}\n max={60}\n step={1}\n value={gainDb}\n onChange={(e) => edit({ gainDb: Number(e.target.value) })}\n />\n </Field>\n\n <Field $span>\n <CheckboxLabel>\n <input\n type=\"checkbox\"\n checked={showLabels}\n onChange={(e) => edit({ labels: e.target.checked })}\n />\n Show Frequency Labels\n </CheckboxLabel>\n </Field>\n </FormGrid>\n\n <ButtonRow>\n <ModalButton type=\"button\" onClick={onClose}>\n Cancel\n </ModalButton>\n <ModalButton type=\"button\" $primary onClick={handleApply}>\n Apply\n </ModalButton>\n </ButtonRow>\n </>\n );\n};\n\nexport const SpectrogramSettingsModal: React.FC<SpectrogramSettingsModalProps> = ({\n open,\n onClose,\n config,\n colorMap,\n onApply,\n sampleRate,\n}) => {\n const dialogRef = useRef<HTMLDialogElement>(null);\n const titleId = useId();\n\n // Latest props for the native `close` listener, so the listener is attached\n // once and not re-added whenever the parent passes a new `onClose`.\n const latestRef = useRef({ open, onClose });\n useLayoutEffect(() => {\n latestRef.current = { open, onClose };\n });\n\n // Native close (Escape key)\n useEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n const handleClose = () => {\n // Only report a close the parent did not ask for (avoids double-fire)\n if (latestRef.current.open) {\n latestRef.current.onClose();\n }\n };\n dialog.addEventListener('close', handleClose);\n return () => dialog.removeEventListener('close', handleClose);\n }, []);\n\n // Layout effect: the dialog opens and closes in the same frame as the form\n // mounts and unmounts, whatever triggered the change.\n useLayoutEffect(() => {\n const dialog = dialogRef.current;\n if (!dialog) return;\n if (open && !dialog.open) {\n dialog.showModal();\n } else if (!open && dialog.open) {\n dialog.close();\n }\n }, [open]);\n\n return (\n <StyledDialog ref={dialogRef} aria-labelledby={titleId}>\n <Title id={titleId}>Spectrogram Settings</Title>\n {open && (\n <SettingsForm\n onClose={onClose}\n config={config}\n colorMap={colorMap}\n onApply={onApply}\n sampleRate={sampleRate}\n />\n )}\n </StyledDialog>\n );\n};\n","import React, { useState, useEffect, useRef, useCallback, useMemo, type ReactNode } from 'react';\nimport {\n MAX_CANVAS_WIDTH,\n trackKind,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n type ArrangementTrack,\n type SpectrogramCanvasRegistration,\n} from '@waveform-playlist/core';\nimport {\n getColorMap,\n getFrequencyScale,\n createSpectrogramWorkerPool,\n SpectrogramAbortError,\n type SpectrogramWorkerApi,\n} from '@dawcore/spectrogram';\nimport {\n extractChunkNumber,\n parseCanvasId,\n presentChunkIndices,\n groupContiguousIndices,\n classifyChunkTiers,\n computeChunkSampleRange,\n resolveRenderMode,\n buildConfigKey,\n mapsDiffer,\n registeredClipRange,\n resolveClipRange,\n type ChunkTiers,\n type RegisteredAudioRange,\n} from './spectrogram-helpers';\nimport { createAudioKeyOf, spectrogramAudio, channelData } from './audioRegistration';\nimport { useStableByContent } from './useStableByContent';\nimport { spectrogramMenuItems } from './components';\nimport { SpectrogramSettingsModal } from './components';\nimport {\n SpectrogramIntegrationContext,\n type SpectrogramIntegration,\n} from '@waveform-playlist/browser';\nimport {\n useArrangement,\n usePlaybackControls,\n useAudioSettings,\n useZoom,\n useTimeline,\n} from '@waveform-playlist/browser';\n\nexport interface SpectrogramProviderProps {\n config?: SpectrogramConfig;\n colorMap?: ColorMapValue;\n /** Number of Web Workers for parallel FFT computation. Defaults to 2 (one per stereo channel). */\n workerPoolSize?: number;\n children: ReactNode;\n}\n\nexport const SpectrogramProvider: React.FC<SpectrogramProviderProps> = ({\n config,\n colorMap,\n workerPoolSize,\n children,\n}) => {\n // By content: the guide writes `config={{ … }}` inline (#821).\n const spectrogramConfig = useStableByContent(config);\n const spectrogramColorMap = useStableByContent(colorMap);\n const { mono } = useAudioSettings();\n const { samplesPerPixel } = useZoom();\n const { tracks } = useTimeline();\n const { scrollContainerRef } = usePlaybackControls();\n // The owner of each track's render mode, spectrogram config and colour map\n // (#814): the setters below change the track, and everything here reads it.\n const arrangement = useArrangement();\n\n // OffscreenCanvas registry for worker-rendered spectrograms\n const spectrogramCanvasRegistryRef = useRef<\n Map<string, Map<number, { canvasIds: string[]; canvasWidths: number[] }>>\n >(new Map());\n // The height each canvas registered with, by canvas id. The row height is an\n // option of the view (#689), so this provider, which sits above the views,\n // learns it from the canvases: a view draws at its own height, and in\n // \"both\" mode a canvas is half a row tall.\n const canvasHeightsRef = useRef<Map<string, number>>(new Map());\n // The range of the audio each canvas registered with, by canvas id: the view\n // draws a trim being dragged before the tracks have it (#812), so a clip is\n // rendered for the range its canvases were drawn for, not the track's. Kept\n // only as part of the registration and never written anywhere else.\n const canvasRangesRef = useRef<Map<string, RegisteredAudioRange>>(new Map());\n const [spectrogramCanvasVersion, setSpectrogramCanvasVersion] = useState(0);\n\n // Spectrogram refs\n const prevSpectrogramConfigRef = useRef<Map<string, string>>(new Map());\n const spectrogramWorkerRef = useRef<SpectrogramWorkerApi | null>(null);\n const spectrogramGenerationRef = useRef(0);\n const prevCanvasVersionRef = useRef(0);\n const backgroundRenderAbortRef = useRef<{ aborted: boolean } | null>(null);\n // One key per AudioBuffer: clips that share a buffer share its registration.\n const [audioKeyOf] = useState(createAudioKeyOf);\n\n // The one place the pool is made: lazily, on the first need. The pool is\n // created once; a later workerPoolSize applies only to a pool made after a\n // cleanup terminated this one.\n const ensureWorkerPool = useCallback((): SpectrogramWorkerApi | null => {\n if (spectrogramWorkerRef.current) return spectrogramWorkerRef.current;\n try {\n const pool = createSpectrogramWorkerPool(\n () =>\n new Worker(new URL('@dawcore/spectrogram/worker/spectrogram.worker', import.meta.url), {\n type: 'module',\n }),\n workerPoolSize\n );\n spectrogramWorkerRef.current = pool;\n return pool;\n } catch (err) {\n console.warn(\n `[waveform-playlist] Spectrogram Web Worker unavailable: ${err instanceof Error ? err.message : String(err)}`\n );\n return null;\n }\n }, [workerPoolSize]);\n\n // Terminate the pool in every cleanup: an unmount, and also when React keeps\n // the component and runs its effects again (a hidden <Activity> shown again,\n // StrictMode). What the pool held goes with it; the effects below ask the\n // next pool what it holds (#821).\n useEffect(() => {\n return () => {\n spectrogramWorkerRef.current?.terminate();\n spectrogramWorkerRef.current = null;\n };\n }, []);\n\n // Pre-register with the pool the audio of every clip on a track that draws a\n // spectrogram, once per buffer, and release what no such clip uses any more.\n // The pool is the one owner of what it holds (`registeredAudioClipIds`).\n // Not gated on the playlist's isReady: a track whose audio is decoded draws\n // while others still load, and its FFT requests would carry its audio.\n useEffect(() => {\n const wanted = spectrogramAudio(tracks, audioKeyOf);\n // Nothing wanted and no pool yet: nothing to release, and no pool to make.\n const pool = wanted.size > 0 ? ensureWorkerPool() : spectrogramWorkerRef.current;\n if (!pool) return;\n\n const held = new Set(pool.registeredAudioClipIds());\n for (const [key, buffer] of wanted) {\n if (!held.has(key)) pool.registerAudioData(key, channelData(buffer), buffer.sampleRate);\n }\n for (const key of held) {\n if (!wanted.has(key)) pool.unregisterAudioData(key);\n }\n }, [tracks, audioKeyOf, ensureWorkerPool]);\n\n // Main spectrogram computation effect\n useEffect(() => {\n if (tracks.length === 0) return;\n\n const currentKeys = new Map<string, string>();\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n const cfg = track.spectrogramConfig ?? spectrogramConfig;\n const cm = track.spectrogramColorMap ?? spectrogramColorMap;\n currentKeys.set(track.id, buildConfigKey({ mode, cfg, cm, mono }));\n });\n\n const prevKeys = prevSpectrogramConfigRef.current;\n const configChanged = mapsDiffer(prevKeys, currentKeys);\n\n const canvasVersionChanged = spectrogramCanvasVersion !== prevCanvasVersionRef.current;\n prevCanvasVersionRef.current = spectrogramCanvasVersion;\n\n if (!configChanged && !canvasVersionChanged) return;\n\n if (configChanged) {\n prevSpectrogramConfigRef.current = currentKeys;\n }\n\n if (backgroundRenderAbortRef.current) {\n backgroundRenderAbortRef.current.aborted = true;\n }\n\n const generation = ++spectrogramGenerationRef.current;\n\n const workerApi = ensureWorkerPool();\n if (!workerApi) return;\n // Tell the worker to abort any in-flight FFT from previous generations\n workerApi.abortGeneration(generation);\n\n // Every clip of a track whose look changed or whose canvases registered.\n // A clip whose FFT the worker already has costs a cache hit, not an FFT.\n const clipsToRender: Array<{\n clipId: string;\n /** The key the clip's audio is registered under: one per AudioBuffer. */\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n clipStartSample: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }> = [];\n\n tracks.forEach((track) => {\n const mode = resolveRenderMode(track.renderMode);\n if (mode === 'waveform') return;\n\n const trackConfigChanged =\n configChanged && currentKeys.get(track.id) !== prevKeys.get(track.id);\n const hasRegisteredCanvases =\n canvasVersionChanged &&\n track.clips.some((clip) => spectrogramCanvasRegistryRef.current.has(clip.id));\n if (!trackConfigChanged && !hasRegisteredCanvases) return;\n\n const cfg = track.spectrogramConfig ?? spectrogramConfig ?? {};\n const cm = track.spectrogramColorMap ?? spectrogramColorMap ?? 'viridis';\n\n for (const clip of track.clips) {\n if (!clip.audioBuffer) continue;\n\n const monoFlag = mono || clip.audioBuffer.numberOfChannels === 1;\n const { offsetSamples, durationSamples } = resolveClipRange(\n clip,\n registeredClipRange(\n spectrogramCanvasRegistryRef.current.get(clip.id),\n canvasRangesRef.current\n )\n );\n\n clipsToRender.push({\n clipId: clip.id,\n audioKey: audioKeyOf(clip.audioBuffer),\n channelDataArrays: channelData(clip.audioBuffer),\n config: cfg,\n sampleRate: clip.audioBuffer.sampleRate,\n offsetSamples,\n durationSamples,\n clipStartSample: clip.startSample,\n monoFlag,\n colorMap: cm,\n });\n }\n });\n\n if (clipsToRender.length === 0) return;\n\n // Three-tier chunk classification:\n // - viewportIndices: chunks intersecting the exact viewport (phase 1a — fast first paint)\n // - bufferIndices: chunks in the 1.5× overscan buffer but outside viewport (phase 1b)\n // - remainingIndices: chunks outside the buffer (phase 2 — background batches)\n const getVisibleChunkRange = (\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n clipPixelOffset = 0\n ): ChunkTiers => {\n const container = scrollContainerRef.current;\n return classifyChunkTiers(\n channelInfo,\n clipPixelOffset,\n container\n ? { scrollLeft: container.scrollLeft, viewportWidth: container.clientWidth }\n : null\n );\n };\n\n const renderChunkSubset = async (\n api: SpectrogramWorkerApi,\n cacheKey: string,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n requestedIndices: number[],\n item: { config: SpectrogramConfig; colorMap: ColorMapValue },\n channelIndex: number,\n gen: number\n ) => {\n // Indices are derived from channel 0's registry; this channel may have\n // registered fewer canvases so far (#562). Skipped chunks render on the\n // next pass — registration bumps spectrogramCanvasVersion.\n const indices = presentChunkIndices(channelInfo, requestedIndices);\n if (indices.length === 0) return;\n\n const canvasIds = indices.map((i) => channelInfo.canvasIds[i]);\n const canvasWidths = indices.map((i) => channelInfo.canvasWidths[i]);\n // The chunks of one channel are all as tall as the first.\n const canvasHeight = canvasHeightsRef.current.get(canvasIds[0]);\n if (canvasHeight === undefined) return;\n\n // Compute correct global pixel offsets by extracting chunk numbers from\n // canvas IDs. With virtual scrolling, the registry may contain non-consecutive\n // chunks (e.g., chunks 50-55), so summing widths from index 0 gives wrong offsets.\n const globalPixelOffsets: number[] = [];\n for (const idx of indices) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[idx]);\n globalPixelOffsets.push(chunkNumber * MAX_CANVAS_WIDTH);\n }\n\n const colorLUT = getColorMap(item.colorMap);\n\n await api.renderChunks(\n {\n cacheKey,\n canvasIds,\n canvasWidths,\n globalPixelOffsets,\n canvasHeight,\n devicePixelRatio: typeof window !== 'undefined' ? window.devicePixelRatio : 1,\n samplesPerPixel,\n colorLUT,\n frequencyScale: item.config.frequencyScale ?? 'mel',\n minFrequency: item.config.minFrequency ?? 0,\n maxFrequency: item.config.maxFrequency ?? 0,\n gainDb: item.config.gainDb ?? 20,\n rangeDb: item.config.rangeDb ?? 80,\n channelIndex,\n },\n gen\n );\n };\n\n // Compute FFT for the sample range covered by a set of chunk indices.\n // Returns the cache key (data covers all channels).\n // This avoids computing a single full-clip FFT (which OOMs on 1hr+ files)\n // by computing per-batch ranges on demand.\n const computeFFTForChunks = async (\n api: SpectrogramWorkerApi,\n channelInfo: { canvasIds: string[]; canvasWidths: number[] },\n indices: number[],\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n },\n gen: number\n ): Promise<string> => {\n // Determine the (window-padded) sample range these chunks cover.\n const { paddedStart, paddedEnd } = computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize: item.config.fftSize ?? 2048,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n samplesPerPixel,\n });\n\n const { cacheKey } = await api.computeFFT(\n {\n // The pool's \"clip id\" names the registered audio: the buffer's key.\n clipId: item.audioKey,\n channelDataArrays: item.channelDataArrays,\n config: item.config,\n sampleRate: item.sampleRate,\n offsetSamples: item.offsetSamples,\n durationSamples: item.durationSamples,\n mono: item.monoFlag,\n sampleRange: { start: paddedStart, end: paddedEnd },\n },\n gen\n );\n\n return cacheKey;\n };\n\n const computeAsync = async () => {\n const abortToken = { aborted: false };\n backgroundRenderAbortRef.current = abortToken;\n\n // Render off-screen chunks in idle-callback batches, computing FFT\n // per contiguous group to avoid allocating one giant Float32Array for the\n // full clip (which OOMs on 1hr+ files — e.g., 310K frames × 2048 bins = 2.5GB).\n // Groups remaining indices into contiguous runs (e.g., [0,1,4,5] → [0,1]+[4,5])\n // so each FFT only covers the sample range actually needed.\n // Returns true if aborted (caller should return early).\n const renderBackgroundBatches = async (\n channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n remainingIndices: number[];\n }>,\n item: {\n audioKey: string;\n channelDataArrays: Float32Array[];\n config: SpectrogramConfig;\n sampleRate: number;\n offsetSamples: number;\n durationSamples: number;\n monoFlag: boolean;\n colorMap: ColorMapValue;\n }\n ): Promise<boolean> => {\n // Collect all contiguous groups across channels, then render\n // each group for ALL channels before moving to the next group\n // (multi-channel fairness — avoids ch1 starvation).\n const allGroups: Array<{\n group: number[];\n channelRangeEntries: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n }>;\n }> = [];\n\n // Build contiguous groups from the first channel's remaining indices\n // (all channels have the same chunk layout).\n if (channelRanges.length > 0) {\n const { channelInfo, remainingIndices } = channelRanges[0];\n const groups = groupContiguousIndices(channelInfo, remainingIndices);\n for (const group of groups) {\n allGroups.push({\n group,\n channelRangeEntries: channelRanges.map(({ ch, channelInfo: ci }) => ({\n ch,\n channelInfo: ci,\n })),\n });\n }\n }\n\n for (const { group, channelRangeEntries } of allGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n await new Promise<void>((resolve) => {\n if (typeof requestIdleCallback === 'function') {\n requestIdleCallback(() => resolve());\n } else {\n setTimeout(resolve, 0);\n }\n });\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n\n // Compute FFT once for this contiguous group (covers all channels)\n const { channelInfo: firstChannelInfo } = channelRangeEntries[0];\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n firstChannelInfo,\n group,\n item,\n generation\n );\n\n // Render all channels from the cached FFT data\n for (const { ch, channelInfo: ci } of channelRangeEntries) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return true;\n await renderChunkSubset(workerApi!, cacheKey, ci, group, item, ch, generation);\n }\n }\n return false;\n };\n\n for (const item of clipsToRender) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n try {\n const clipCanvasInfo = spectrogramCanvasRegistryRef.current.get(item.clipId);\n if (clipCanvasInfo && clipCanvasInfo.size > 0) {\n const numChannels = item.monoFlag ? 1 : item.channelDataArrays.length;\n const clipPixelOffset = Math.floor(item.clipStartSample / samplesPerPixel);\n\n // Three-phase rendering:\n // Phase 1a: viewport-only chunks (fast first paint)\n // Phase 1b: buffer-zone chunks (prevents black chunks on scroll)\n // Phase 2: off-screen chunks (background batches)\n const channelRanges: Array<{\n ch: number;\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n viewportIndices: number[];\n bufferIndices: number[];\n remainingIndices: number[];\n }> = [];\n\n for (let ch = 0; ch < numChannels; ch++) {\n const channelInfo = clipCanvasInfo.get(ch);\n if (!channelInfo) continue;\n const range = getVisibleChunkRange(channelInfo, clipPixelOffset);\n channelRanges.push({ ch, channelInfo, ...range });\n }\n\n // Phase 1a: Compute FFT for viewport chunks only, render all channels\n if (channelRanges.length > 0 && channelRanges[0].viewportIndices.length > 0) {\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n channelRanges[0].viewportIndices,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo, viewportIndices } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n viewportIndices,\n item,\n ch,\n generation\n );\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 1b: Compute FFT for buffer-zone chunks, render all channels.\n // Buffer indices may be non-contiguous (e.g., chunks [10,14,15] from\n // indices [0,3,4,5]), so group them to avoid spanning a huge FFT range.\n if (channelRanges.length > 0 && channelRanges[0].bufferIndices.length > 0) {\n const bufferGroups = groupContiguousIndices(\n channelRanges[0].channelInfo,\n channelRanges[0].bufferIndices\n );\n\n for (const group of bufferGroups) {\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n const cacheKey = await computeFFTForChunks(\n workerApi!,\n channelRanges[0].channelInfo,\n group,\n item,\n generation\n );\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n for (const { ch, channelInfo } of channelRanges) {\n await renderChunkSubset(\n workerApi!,\n cacheKey,\n channelInfo,\n group,\n item,\n ch,\n generation\n );\n }\n }\n }\n\n if (spectrogramGenerationRef.current !== generation || abortToken.aborted) return;\n\n // Phase 2: Render off-screen chunks in background batches\n // (each batch computes its own bounded FFT range).\n if (await renderBackgroundBatches(channelRanges, item)) return;\n }\n } catch (err) {\n if (err instanceof SpectrogramAbortError) return;\n console.warn(\n `[waveform-playlist] Spectrogram worker error for clip ${item.clipId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n };\n\n computeAsync().catch((err) => {\n console.error(\n `[waveform-playlist] Spectrogram computation failed: ${err instanceof Error ? err.message : String(err)}`\n );\n });\n }, [\n tracks,\n mono,\n spectrogramConfig,\n spectrogramColorMap,\n samplesPerPixel,\n spectrogramCanvasVersion,\n scrollContainerRef,\n audioKeyOf,\n ensureWorkerPool,\n ]);\n\n // Setters: each a change of the track in the arrangement, so an undo step\n // (#814). Returning the track as it is changes nothing and pushes no step:\n // the mode it is already drawn with (an unset one is 'waveform'), and any\n // mode for a MIDI track, which is drawn as a piano roll (review of #930).\n const setTrackRenderMode = useCallback(\n (trackId: string, mode: RenderMode) => {\n arrangement.updateTrack(trackId, (track: ArrangementTrack) =>\n trackKind(track) === 'midi' || resolveRenderMode(track.renderMode) === mode\n ? track\n : { ...track, renderMode: mode }\n );\n },\n [arrangement]\n );\n\n const setTrackSpectrogramConfig = useCallback(\n (trackId: string, config: SpectrogramConfig, colorMap?: ColorMapValue) => {\n // The render mode is left as it is (review of #926).\n arrangement.updateTrack(trackId, (track: ArrangementTrack) => ({\n ...track,\n spectrogramConfig: config,\n spectrogramColorMap: colorMap ?? track.spectrogramColorMap,\n }));\n },\n [arrangement]\n );\n\n const registerSpectrogramCanvas = useCallback(\n (reg: SpectrogramCanvasRegistration) => {\n const pool = ensureWorkerPool();\n if (!pool) return;\n\n try {\n pool.registerCanvas(reg.canvasId, reg.canvas);\n } catch (err) {\n console.warn(\n `[waveform-playlist] registerCanvas failed for ${reg.canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n return;\n }\n\n canvasHeightsRef.current.set(reg.canvasId, reg.heightPx);\n if (reg.offsetSamples !== undefined || reg.durationSamples !== undefined) {\n canvasRangesRef.current.set(reg.canvasId, {\n offsetSamples: reg.offsetSamples,\n durationSamples: reg.durationSamples,\n });\n } else {\n canvasRangesRef.current.delete(reg.canvasId);\n }\n const registry = spectrogramCanvasRegistryRef.current;\n if (!registry.has(reg.clipId)) {\n registry.set(reg.clipId, new Map());\n }\n const perClip = registry.get(reg.clipId)!;\n const entry = perClip.get(reg.channelIndex) ?? { canvasIds: [], canvasWidths: [] };\n const existingIdx = entry.canvasIds.indexOf(reg.canvasId);\n if (existingIdx >= 0) {\n entry.canvasWidths[existingIdx] = reg.widthPx;\n } else {\n entry.canvasIds.push(reg.canvasId);\n entry.canvasWidths.push(reg.widthPx);\n }\n perClip.set(reg.channelIndex, entry);\n setSpectrogramCanvasVersion((v) => v + 1);\n },\n [ensureWorkerPool]\n );\n\n const unregisterSpectrogramCanvas = useCallback((canvasId: string) => {\n canvasHeightsRef.current.delete(canvasId);\n canvasRangesRef.current.delete(canvasId);\n const pool = spectrogramWorkerRef.current;\n if (pool) {\n try {\n pool.unregisterCanvas(canvasId);\n } catch (err) {\n console.warn(\n `[waveform-playlist] unregisterCanvas failed for ${canvasId}: ${err instanceof Error ? err.message : String(err)}`\n );\n }\n }\n\n // Canvas IDs follow the format `${clipId}-ch${channelIndex}-chunk${n}`.\n const parsed = parseCanvasId(canvasId);\n if (!parsed) return;\n const { clipId, channelIndex } = parsed;\n\n const registry = spectrogramCanvasRegistryRef.current;\n const perClip = registry.get(clipId);\n if (!perClip) return;\n const entry = perClip.get(channelIndex);\n if (!entry) return;\n const idx = entry.canvasIds.indexOf(canvasId);\n if (idx >= 0) {\n entry.canvasIds.splice(idx, 1);\n entry.canvasWidths.splice(idx, 1);\n }\n if (entry.canvasIds.length === 0) {\n perClip.delete(channelIndex);\n }\n if (perClip.size === 0) {\n registry.delete(clipId);\n }\n setSpectrogramCanvasVersion((v) => v + 1);\n }, []);\n\n const renderMenuItems = useCallback(\n (props: {\n renderMode: string;\n onRenderModeChange: (mode: RenderMode) => void;\n onOpenSettings: () => void;\n onClose?: () => void;\n }) => {\n return spectrogramMenuItems({\n renderMode: props.renderMode as RenderMode,\n onRenderModeChange: props.onRenderModeChange,\n onOpenSettings: props.onOpenSettings,\n onClose: props.onClose,\n });\n },\n []\n );\n\n const value: SpectrogramIntegration = useMemo(\n () => ({\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n SettingsModal: SpectrogramSettingsModal,\n getColorMap,\n getFrequencyScale: getFrequencyScale as (\n name: string\n ) => (f: number, minF: number, maxF: number) => number,\n }),\n [\n spectrogramConfig,\n spectrogramColorMap,\n setTrackRenderMode,\n setTrackSpectrogramConfig,\n registerSpectrogramCanvas,\n unregisterSpectrogramCanvas,\n renderMenuItems,\n ]\n );\n\n return <SpectrogramIntegrationContext value={value}>{children}</SpectrogramIntegrationContext>;\n};\n","import {\n MAX_CANVAS_WIDTH,\n parseSpectrogramCanvasId,\n type SpectrogramConfig,\n type ColorMapValue,\n type RenderMode,\n} from '@waveform-playlist/core';\nimport { computePaddedFftRange } from '@dawcore/spectrogram';\n\n/**\n * Pure, side-effect-free helpers extracted from `SpectrogramProvider`.\n *\n * These cover the geometry/key logic that the provider's worker-orchestration\n * effect depends on (chunk classification, FFT sample ranges, contiguous\n * grouping, config-change detection). Keeping them DOM-free makes them unit\n * testable in a Node environment — the provider supplies the imperative shell\n * (refs, worker calls, React state) around this functional core.\n */\n\n/** A channel's registered canvas chunks: parallel arrays of IDs and pixel widths. */\nexport interface ChannelChunkInfo {\n canvasIds: string[];\n canvasWidths: number[];\n}\n\n/** Chunk indices grouped by their relationship to the current scroll viewport. */\nexport interface ChunkTiers {\n /** Chunks intersecting the exact viewport — fast first paint. */\n viewportIndices: number[];\n /** Chunks within the 1.5× overscan buffer but outside the viewport. */\n bufferIndices: number[];\n /** Chunks outside the buffer — rendered in background batches. */\n remainingIndices: number[];\n}\n\n/** Scroll-container metrics needed to classify chunks. `null` ⇒ no container yet. */\nexport interface ViewportMetrics {\n scrollLeft: number;\n viewportWidth: number;\n}\n\n/**\n * Extract the chunk number from a canvas ID like `\"clipId-ch0-chunk5\"` → `5`.\n * Delegates to the canonical `parseSpectrogramCanvasId`; warns and returns `0`\n * when the ID doesn't match the `${clipId}-ch${channelIndex}-chunk${n}` format.\n */\nexport function extractChunkNumber(canvasId: string): number {\n const parsed = parseSpectrogramCanvasId(canvasId);\n if (!parsed) {\n console.warn(`[spectrogram] Unexpected canvas ID format: ${canvasId}`);\n return 0;\n }\n return parsed.chunkIndex;\n}\n\n/**\n * Keep only indices whose canvas is registered for THIS channel.\n *\n * Chunk indices are derived once from channel 0's registry and reused across\n * channels, but canvases register progressively per channel — a later channel\n * can briefly hold fewer entries, and indexing past its registry threw\n * `Cannot read properties of undefined (reading 'match')` (#562). Skipped\n * chunks render on the next pass: registration bumps `spectrogramCanvasVersion`.\n */\nexport function presentChunkIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[] {\n return indices.filter((i) => channelInfo.canvasIds[i] !== undefined);\n}\n\n/**\n * Parse a canvas ID of the form `${clipId}-ch${channelIndex}-chunk${n}` into its\n * clip ID and channel index. Returns `null` when the ID doesn't match.\n */\nexport function parseCanvasId(canvasId: string): { clipId: string; channelIndex: number } | null {\n const parsed = parseSpectrogramCanvasId(canvasId);\n return parsed ? { clipId: parsed.clipId, channelIndex: parsed.channelIndex } : null;\n}\n\n/**\n * Split indices into contiguous groups based on their chunk numbers, e.g.\n * indices mapping to chunks `[0,1,4,5]` → `[[0,1],[4,5]]`. Prevents computing an\n * FFT range that spans the gap between non-adjacent chunks.\n */\nexport function groupContiguousIndices(\n channelInfo: { canvasIds: string[] },\n indices: number[]\n): number[][] {\n if (indices.length === 0) return [];\n const groups: number[][] = [];\n let currentGroup = [indices[0]];\n let prevChunk = extractChunkNumber(channelInfo.canvasIds[indices[0]]);\n for (let i = 1; i < indices.length; i++) {\n const chunk = extractChunkNumber(channelInfo.canvasIds[indices[i]]);\n if (chunk === prevChunk + 1) {\n currentGroup.push(indices[i]);\n } else {\n groups.push(currentGroup);\n currentGroup = [indices[i]];\n }\n prevChunk = chunk;\n }\n groups.push(currentGroup);\n return groups;\n}\n\n/**\n * Classify a channel's chunks into viewport / buffer / remaining tiers.\n *\n * The buffer uses a 1.5× viewport-width overscan to match\n * `useVisibleChunkIndices` in ScrollViewport, so FFT covers every mounted\n * canvas. When `viewport` is `null` (no scroll container yet), every chunk is\n * treated as in-viewport.\n */\nexport function classifyChunkTiers(\n channelInfo: ChannelChunkInfo,\n clipPixelOffset = 0,\n viewport: ViewportMetrics | null\n): ChunkTiers {\n if (!viewport) {\n return {\n viewportIndices: channelInfo.canvasWidths.map((_, i) => i),\n bufferIndices: [],\n remainingIndices: [],\n };\n }\n\n const { scrollLeft, viewportWidth } = viewport;\n const buffer = viewportWidth * 1.5;\n const bufferStart = Math.max(0, scrollLeft - buffer);\n const bufferEnd = scrollLeft + viewportWidth + buffer;\n\n const viewportIndices: number[] = [];\n const bufferIndices: number[] = [];\n const remainingIndices: number[] = [];\n\n for (let i = 0; i < channelInfo.canvasWidths.length; i++) {\n const chunkNumber = extractChunkNumber(channelInfo.canvasIds[i]);\n const chunkLeft = chunkNumber * MAX_CANVAS_WIDTH + clipPixelOffset;\n const chunkRight = chunkLeft + channelInfo.canvasWidths[i];\n if (chunkRight > scrollLeft && chunkLeft < scrollLeft + viewportWidth) {\n viewportIndices.push(i);\n } else if (chunkRight > bufferStart && chunkLeft < bufferEnd) {\n bufferIndices.push(i);\n } else {\n remainingIndices.push(i);\n }\n }\n\n return { viewportIndices, bufferIndices, remainingIndices };\n}\n\nexport interface ChunkSampleRangeParams {\n channelInfo: { canvasIds: string[]; canvasWidths: number[] };\n indices: number[];\n /** FFT window size (samples) used to pad the range against edge artifacts. */\n fftSize: number;\n offsetSamples: number;\n durationSamples: number;\n samplesPerPixel: number;\n}\n\n/**\n * Compute the (window-padded, clip-clamped) sample range covered by a set of\n * chunk indices. Computing per-batch ranges on demand avoids allocating one\n * giant FFT array for a full clip (which OOMs on 1hr+ files).\n */\nexport function computeChunkSampleRange({\n channelInfo,\n indices,\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n}: ChunkSampleRangeParams): { paddedStart: number; paddedEnd: number } {\n return computePaddedFftRange({\n chunks: indices.map((i) => ({\n chunkIndex: extractChunkNumber(channelInfo.canvasIds[i]),\n widthPx: channelInfo.canvasWidths[i],\n })),\n fftSize,\n offsetSamples,\n durationSamples,\n samplesPerPixel,\n });\n}\n\n/** Resolve a track's effective render mode: the track's own, else `'waveform'`. */\nexport function resolveRenderMode(trackRenderMode: RenderMode | undefined): RenderMode {\n return trackRenderMode ?? 'waveform';\n}\n\n/**\n * Stable string key for a track's full spectrogram appearance (mode + config +\n * color map + mono). A change means the rendered output must be recomputed.\n */\nexport function buildConfigKey(params: {\n mode: RenderMode;\n cfg: SpectrogramConfig | undefined;\n cm: ColorMapValue | undefined;\n mono: boolean;\n}): string {\n const { mode, cfg, cm, mono } = params;\n return JSON.stringify({ mode, cfg, cm, mono });\n}\n\n/**\n * Whether two key maps differ — different size, or any key present in `current`\n * whose value doesn't match `prev`. Used to detect config/FFT changes between\n * effect runs.\n */\nexport function mapsDiffer(prev: Map<string, string>, current: Map<string, string>): boolean {\n if (current.size !== prev.size) return true;\n for (const [key, value] of current) {\n if (prev.get(key) !== value) return true;\n }\n return false;\n}\n\n/** The range of the audio a canvas registered with (`SpectrogramCanvasRegistration`). */\nexport interface RegisteredAudioRange {\n offsetSamples?: number;\n durationSamples?: number;\n}\n\n/**\n * The range a clip's canvases registered with: that of the first canvas that\n * gave one (all canvases of a clip are drawn for the same range; a new range\n * registers new canvases). `undefined` when none gave one.\n */\nexport function registeredClipRange(\n perClip: ReadonlyMap<number, ChannelChunkInfo> | undefined,\n rangeByCanvasId: ReadonlyMap<string, RegisteredAudioRange>\n): RegisteredAudioRange | undefined {\n if (!perClip) return undefined;\n for (const channelInfo of perClip.values()) {\n for (const canvasId of channelInfo.canvasIds) {\n const range = rangeByCanvasId.get(canvasId);\n if (range) return range;\n }\n }\n return undefined;\n}\n\n/**\n * The range to draw a clip for: what its canvases registered with (the view\n * may draw a clip the tracks do not have yet, a trim being dragged), field by\n * field, else the clip's own.\n */\nexport function resolveClipRange(\n clip: { offsetSamples: number; durationSamples: number },\n registered: RegisteredAudioRange | undefined\n): { offsetSamples: number; durationSamples: number } {\n return {\n offsetSamples: registered?.offsetSamples ?? clip.offsetSamples,\n durationSamples: registered?.durationSamples ?? clip.durationSamples,\n };\n}\n","import type { ClipTrack } from '@waveform-playlist/core';\nimport { resolveRenderMode } from './spectrogram-helpers';\n\n/**\n * The key an AudioBuffer's audio is registered under in the worker pool, the\n * same for as long as the buffer lives. Clips that share a buffer share the\n * key (a split keeps one buffer for both halves), so the pool holds the audio\n * once (#821). The worker's FFT cache key also carries each clip's range, so\n * two clips over different parts of one buffer keep separate entries.\n */\nexport type AudioKeyOf = (buffer: AudioBuffer) => string;\n\nexport function createAudioKeyOf(): AudioKeyOf {\n const keys = new WeakMap<AudioBuffer, string>();\n let next = 0;\n return (buffer) => {\n const existing = keys.get(buffer);\n if (existing !== undefined) return existing;\n next += 1;\n const key = `audio-${next}`;\n keys.set(buffer, key);\n return key;\n };\n}\n\n/**\n * The audio the pool should hold, by key: each buffer that a clip on a track\n * drawing a spectrogram (`spectrogram` or `both`) uses. A waveform track's\n * audio is never computed, so it is not sent (#821).\n */\nexport function spectrogramAudio(\n tracks: readonly ClipTrack[],\n audioKeyOf: AudioKeyOf\n): Map<string, AudioBuffer> {\n const wanted = new Map<string, AudioBuffer>();\n for (const track of tracks) {\n if (resolveRenderMode(track.renderMode) === 'waveform') continue;\n for (const clip of track.clips) {\n if (clip.audioBuffer) wanted.set(audioKeyOf(clip.audioBuffer), clip.audioBuffer);\n }\n }\n return wanted;\n}\n\n/** Every channel of a buffer, as the views `getChannelData` returns (not copies). */\nexport function channelData(buffer: AudioBuffer): Float32Array[] {\n return Array.from({ length: buffer.numberOfChannels }, (_, ch) => buffer.getChannelData(ch));\n}\n","import { useMemo } from 'react';\n\n/**\n * The value as it was the last time its JSON content changed. For plain-data\n * props an app often writes inline (`config={{ fftSize: 2048 }}`): a new\n * object with the same content keeps the old one, so the context value and\n * the effects that depend on it do not change on every render of the app\n * (#821). Only for values JSON describes completely (no functions, no class\n * instances); a key whose value is `undefined` counts as absent.\n */\nexport function useStableByContent<T>(value: T): T {\n const content = JSON.stringify(value);\n // eslint-disable-next-line react-hooks/exhaustive-deps -- keyed on the content, not the identity\n return useMemo(() => value, [content]);\n}\n"],"mappings":";AACA,OAAO,YAAY;AA6ET,cAEE,YAFF;AArEV,IAAM,eAAe,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAS5B,IAAM,aAAa,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAa1B,IAAM,iBAAiB,OAAO;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAe9B,IAAM,kBAAkB,OAAO;AAAA;AAAA;AAI/B,IAAM,eAAuD;AAAA,EAC3D,EAAE,OAAO,YAAY,OAAO,WAAW;AAAA,EACvC,EAAE,OAAO,eAAe,OAAO,cAAc;AAAA,EAC7C,EAAE,OAAO,QAAQ,OAAO,OAAO;AACjC;AAaO,SAAS,qBAAqB;AAAA,EACnC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF,GAA2C;AACzC,SAAO;AAAA,IACL;AAAA,MACE,IAAI;AAAA,MACJ,SACE,qBAAC,mBACC;AAAA,4BAAC,gBAAa,qBAAO;AAAA,QACpB,aAAa,IAAI,CAAC,EAAE,OAAO,MAAM,MAChC,qBAAC,cACC;AAAA;AAAA,YAAC;AAAA;AAAA,cACC,MAAK;AAAA,cACL,MAAK;AAAA,cACL,SAAS,eAAe;AAAA,cACxB,UAAU,MAAM;AACd,mCAAmB,KAAK;AACxB,0BAAU;AAAA,cACZ;AAAA;AAAA,UACF;AAAA,UACC;AA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,CAAC;AAAA,EACH;AAEA,QAAM,QAAgCC;AAAA,IACpC,OAAO;AAAA,MACL;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA,eAAe;AAAA,MACf;AAAA,MACA;AAAA,IAGF;AAAA,IACA;AAAA,MACE;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,MACA;AAAA,IACF;AAAA,EACF;AAEA,SAAO,gBAAAP,KAAC,iCAA8B,OAAe,UAAS;AAChE;","names":["styled","jsx","jsxs","useState","useEffect","useRef","useMemo","MAX_CANVAS_WIDTH","jsx","useRef","useState","useEffect","MAX_CANVAS_WIDTH","config","colorMap","useMemo"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waveform-playlist/spectrogram",
3
- "version": "15.0.0-next.13",
3
+ "version": "15.0.0-next.15",
4
4
  "description": "React Provider + UI for spectrograms — wraps @dawcore/spectrogram",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -46,16 +46,16 @@
46
46
  "tsup": "^8.5.1",
47
47
  "typescript": "^5.9.3",
48
48
  "vitest": "^5.0.3",
49
- "@waveform-playlist/browser": "17.0.0-next.27"
49
+ "@waveform-playlist/browser": "17.0.0-next.29"
50
50
  },
51
51
  "dependencies": {
52
- "@dawcore/spectrogram": "0.0.9-next.12",
53
- "@waveform-playlist/core": "13.0.0-next.10"
52
+ "@dawcore/spectrogram": "0.0.9-next.14",
53
+ "@waveform-playlist/core": "13.0.0-next.12"
54
54
  },
55
55
  "peerDependencies": {
56
56
  "react": "^19.0.0",
57
57
  "styled-components": "^6.0.0",
58
- "@waveform-playlist/browser": "^17.0.0-next.27"
58
+ "@waveform-playlist/browser": "^17.0.0-next.29"
59
59
  },
60
60
  "scripts": {
61
61
  "build": "tsup",