@waveform-playlist/core 13.0.0-next.8 → 13.0.0-next.9

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/types/clip.ts","../src/types/index.ts","../src/utils/conversions.ts","../src/utils/beatsAndBars.ts","../src/utils/dBUtils.ts","../src/utils/musicalTicks.ts","../src/utils/meterDetection.ts","../src/utils/peaksGenerator.ts","../src/utils/audioBufferUtils.ts","../src/utils/latency.ts","../src/utils/spectrogram-defaults.ts","../src/utils/carveClipRange.ts","../src/utils/meterLevels.ts","../src/clipTimeHelpers.ts","../src/trackKind.ts","../src/spectrogramCanvasId.ts","../src/fades.ts","../src/keyboard.ts","../src/probeRangeSupport.ts","../src/enumerateMicrophones.ts","../src/annotations/boundaries.ts","../src/annotations/shortcuts.ts","../src/annotations/devFreeze.ts","../src/annotations/store.ts","../src/annotations/bounds.ts","../src/panStage.ts","../src/valueSource.ts","../src/sourceLoader.ts","../src/audioTrack.ts","../src/mixerGesture.ts","../src/effects/registry.ts"],"sourcesContent":["export * from './constants';\nexport * from './types';\nexport * from './utils';\nexport * from './clipTimeHelpers';\nexport * from './trackKind';\nexport * from './spectrogramCanvasId';\nexport * from './fades';\nexport * from './keyboard';\nexport * from './probeRangeSupport';\nexport * from './enumerateMicrophones';\nexport * from './annotations/boundaries';\nexport * from './annotations/shortcuts';\nexport * from './annotations/store';\nexport * from './annotations/bounds';\nexport * from './panStage';\nexport * from './valueSource';\nexport * from './sourceLoader';\nexport * from './audioTrack';\nexport { createMixerGesture } from './mixerGesture';\nexport type { MixerGesture } from './mixerGesture';\nexport * from './effects/registry';\n","/**\n * Maximum width in CSS pixels for a single canvas chunk.\n * Canvas elements are split into chunks of this width to enable\n * horizontal virtual scrolling — only visible chunks are mounted.\n */\nexport const MAX_CANVAS_WIDTH = 1000;\n","/**\n * Clip-Based Model Types\n *\n * These types support a professional multi-track editing model where:\n * - Each track can contain multiple audio clips\n * - Clips can be positioned anywhere on the timeline\n * - Clips have independent trim points (offset/duration)\n * - Gaps between clips are silent\n * - Clips can overlap (for crossfades)\n */\n\nimport { Fade } from './index';\nimport type { RenderMode, SpectrogramConfig, ColorMapValue } from './spectrogram';\n\n/**\n * WaveformData object from waveform-data.js library.\n * Supports resample() and slice() for dynamic zoom levels.\n * See: https://github.com/bbc/waveform-data.js\n */\nexport interface WaveformDataObject {\n /** Sample rate of the original audio */\n readonly sample_rate: number;\n /** Number of audio samples per pixel */\n readonly scale: number;\n /** Length of waveform data in pixels */\n readonly length: number;\n /** Bit depth (8 or 16) */\n readonly bits: number;\n /** Duration in seconds */\n readonly duration: number;\n /** Number of channels */\n readonly channels: number;\n /** Get channel data */\n channel: (index: number) => {\n min_array: () => number[];\n max_array: () => number[];\n };\n /** Resample to different scale */\n resample: (options: { scale: number } | { width: number }) => WaveformDataObject;\n /** Slice a portion of the waveform */\n slice: (\n options: { startTime: number; endTime: number } | { startIndex: number; endIndex: number }\n ) => WaveformDataObject;\n}\n\n/**\n * Represents a single audio clip on the timeline\n *\n * IMPORTANT: All positions/durations are stored as SAMPLE COUNTS (integers)\n * to avoid floating-point precision errors. Convert to seconds only when\n * needed for playback using: seconds = samples / sampleRate\n *\n * Clips can be created with just waveformData (for instant visual rendering)\n * and have audioBuffer added later when audio finishes loading.\n */\nexport interface AudioClip {\n /** Unique identifier for this clip */\n id: string;\n\n /**\n * The audio buffer containing the audio data.\n * Optional for peaks-first rendering - can be added later.\n * Required for playback and editing operations.\n */\n audioBuffer?: AudioBuffer;\n\n /** Position on timeline where this clip starts (in samples at timeline sampleRate) */\n startSample: number;\n\n /**\n * Position on timeline in ticks (authoritative when present).\n * When set, startSample is a derived cache recomputed from startTick via TempoMap.\n * Optional for backwards compatibility — engine enriches clips without startTick on ingestion.\n */\n startTick?: number;\n\n /** Duration of this clip (in samples) - how much of the audio buffer to play */\n durationSamples: number;\n\n /** Offset into the audio buffer where playback starts (in samples) - the \"trim start\" point */\n offsetSamples: number;\n\n /**\n * Sample rate for this clip's audio.\n * Required when audioBuffer is not provided (for peaks-first rendering).\n * When audioBuffer is present, this should match audioBuffer.sampleRate.\n */\n sampleRate: number;\n\n /**\n * Total duration of the source audio in samples.\n * Required when audioBuffer is not provided (for trim bounds calculation).\n * When audioBuffer is present, this should equal audioBuffer.length.\n */\n sourceDurationSamples: number;\n\n /** Optional fade in effect */\n fadeIn?: Fade;\n\n /** Optional fade out effect */\n fadeOut?: Fade;\n\n /** Clip-specific gain/volume multiplier (0.0 to 1.0+) */\n gain: number;\n\n /** Optional label/name for this clip */\n name?: string;\n\n /** Optional color for visual distinction */\n color?: string;\n\n /**\n * Pre-computed waveform data from waveform-data.js library.\n * When provided, the library will use this instead of computing peaks from the audioBuffer.\n * Supports resampling to different zoom levels and slicing for clip trimming.\n * Load with: `const waveformData = await loadWaveformData('/path/to/peaks.dat')`\n */\n waveformData?: WaveformDataObject;\n\n /**\n * MIDI note data — when present, this clip plays MIDI instead of audio.\n * The playout adapter uses this field to detect MIDI clips and route them\n * to MidiToneTrack (PolySynth) instead of ToneTrack (AudioBufferSourceNode).\n */\n midiNotes?: MidiNoteData[];\n\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n\n /** MIDI program number (0-127). GM instrument number for SoundFont playback. */\n midiProgram?: number;\n\n /** The source this clip's audio came from (a URL, Blob or File), when it is known. */\n src?: ClipSource;\n}\n\n/** What a loading clip names. A string is a URL; a Blob or File is keyed by identity. */\nexport type ClipSource = string | Blob;\n\n/**\n * A clip whose audio is not loaded yet. Times are in seconds; whatever loads\n * `src` turns it into an `AudioClip` (integer samples).\n */\nexport interface LoadingClip {\n /** Unique identifier for this clip */\n id: string;\n\n /** The audio to load */\n src: ClipSource;\n\n /** Position on the timeline, in seconds. Default 0. */\n start?: number;\n\n /** Duration in seconds. Default: the whole source from `offset`. */\n duration?: number;\n\n /** Start within the source, in seconds. Default 0. */\n offset?: number;\n\n name?: string;\n gain?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n color?: string;\n\n /** Pre-computed peaks, drawn while the audio loads */\n waveformData?: WaveformDataObject;\n}\n\n/**\n * The fields of a track that say how it is drawn, not how it plays. An\n * adapter is never given them (`PlayoutTrack`), and the engine makes no\n * adapter call for a change of these fields alone: on the native transport an\n * `updateTrack` stops the track's playing sources (silent until its next\n * clip), so a render-mode choice during playback silenced it (review of #930). The one list; the engine reads it.\n */\nexport const TRACK_VIEW_FIELDS = [\n 'name',\n 'color',\n 'height',\n 'renderMode',\n 'spectrogramConfig',\n 'spectrogramColorMap',\n] as const satisfies readonly (keyof ClipTrack)[];\n\n/** A field of `TRACK_VIEW_FIELDS`. */\nexport type TrackViewField = (typeof TRACK_VIEW_FIELDS)[number];\n\n/** A track as a playout adapter is given it: a `ClipTrack` without the view fields. */\nexport type PlayoutTrack = Omit<ClipTrack, TrackViewField>;\n\n/** A track whose clips are loaded (`AudioClip`) or not loaded yet (`LoadingClip`). */\nexport type ArrangementTrack = Omit<ClipTrack, 'clips'> & {\n clips: (AudioClip | LoadingClip)[];\n};\n\n/** True for a clip whose audio is not loaded yet (it has no `sampleRate`). */\nexport function isLoadingClip(clip: AudioClip | LoadingClip): clip is LoadingClip {\n return !('sampleRate' in clip) || clip.sampleRate == null;\n}\n\n/** What a track holds: audio clips or MIDI clips. A track never holds both. */\nexport type TrackKind = 'audio' | 'midi';\n\n/**\n * Represents a track containing multiple clips of one kind\n */\nexport interface ClipTrack {\n /** Unique identifier for this track */\n id: string;\n\n /**\n * What the track holds. Every clip on an audio track is an audio clip and\n * every clip on a MIDI track has `midiNotes`; the engine throws on a track\n * that breaks this. An empty track has a kind too, which decides what may be\n * recorded or added to it. A MIDI track is drawn as a piano roll.\n */\n kind: TrackKind;\n\n /** Display name for this track */\n name: string;\n\n /** Array of audio clips on this track */\n clips: AudioClip[];\n\n /** Whether this track is muted */\n muted: boolean;\n\n /** Whether this track is soloed */\n soloed: boolean;\n\n /** Track volume (0.0 to 1.0+) */\n volume: number;\n\n /** Stereo pan (-1.0 = left, 0 = center, 1.0 = right) */\n pan: number;\n\n /** Optional track color for visual distinction */\n color?: string;\n\n /** Track height in pixels (for UI) */\n height?: number;\n\n /** Visualization render mode. Default: 'waveform' */\n renderMode?: RenderMode;\n\n /** Per-track spectrogram configuration (FFT size, window, frequency scale, etc.) */\n spectrogramConfig?: SpectrogramConfig;\n\n /** Per-track spectrogram color map name or custom color array */\n spectrogramColorMap?: ColorMapValue;\n}\n\n/**\n * Represents the entire timeline/project\n */\nexport interface Timeline {\n /** All tracks in the timeline */\n tracks: ClipTrack[];\n\n /** Total timeline duration in seconds */\n duration: number;\n\n /** Sample rate for all audio (typically 44100 or 48000) */\n sampleRate: number;\n\n /** Optional project name */\n name?: string;\n\n /** Optional tempo (BPM) for grid snapping */\n tempo?: number;\n\n /** Optional time signature for grid snapping */\n timeSignature?: {\n numerator: number;\n denominator: number;\n };\n}\n\n/**\n * Options for creating a new audio clip (using sample counts)\n *\n * Either audioBuffer OR (sampleRate + sourceDurationSamples + waveformData) must be provided.\n * Providing waveformData without audioBuffer enables peaks-first rendering.\n */\nexport interface CreateClipOptions {\n /** Audio buffer - optional for peaks-first rendering */\n audioBuffer?: AudioBuffer;\n startSample: number; // Position on timeline (in samples)\n startTick?: number; // Timeline position in ticks (optional)\n durationSamples?: number; // Defaults to full buffer/source duration (in samples)\n offsetSamples?: number; // Defaults to 0\n gain?: number; // Defaults to 1.0\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Pre-computed waveform data from waveform-data.js (e.g., from BBC audiowaveform) */\n waveformData?: WaveformDataObject;\n /** Sample rate - required if audioBuffer not provided */\n sampleRate?: number;\n /** Total source audio duration in samples - required if audioBuffer not provided */\n sourceDurationSamples?: number;\n /** MIDI note data — passed through to the created AudioClip */\n midiNotes?: MidiNoteData[];\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n /** MIDI program number (0-127). GM instrument for SoundFont playback. */\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\n/**\n * Options for creating a new audio clip (using seconds for convenience)\n *\n * Either audioBuffer OR (sampleRate + sourceDuration + waveformData) must be provided.\n * Providing waveformData without audioBuffer enables peaks-first rendering.\n */\nexport interface CreateClipOptionsSeconds {\n /** Audio buffer - optional for peaks-first rendering */\n audioBuffer?: AudioBuffer;\n startTime: number; // Position on timeline (in seconds)\n startTick?: number; // Timeline position in ticks (optional)\n duration?: number; // Defaults to full buffer/source duration (in seconds)\n offset?: number; // Defaults to 0 (in seconds)\n gain?: number; // Defaults to 1.0\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Pre-computed waveform data from waveform-data.js (e.g., from BBC audiowaveform) */\n waveformData?: WaveformDataObject;\n /** Sample rate - required if audioBuffer not provided */\n sampleRate?: number;\n /** Total source audio duration in seconds - required if audioBuffer not provided */\n sourceDuration?: number;\n /** MIDI note data — passed through to the created AudioClip */\n midiNotes?: MidiNoteData[];\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n /** MIDI program number (0-127). GM instrument for SoundFont playback. */\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\n/**\n * Options for creating a new audio clip from tick position.\n * startTick is authoritative; startSample is derived.\n *\n * Provide either:\n * - ticksToSeconds callback (for variable-tempo / multi-tempo), or\n * - bpm + ppqn (for single-tempo convenience)\n */\nexport interface CreateClipOptionsTicks {\n startTick: number;\n ticksToSeconds?: (tick: number) => number;\n bpm?: number;\n ppqn?: number;\n audioBuffer?: AudioBuffer;\n durationSamples?: number;\n offsetSamples?: number;\n gain?: number;\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n waveformData?: WaveformDataObject;\n sampleRate?: number;\n sourceDurationSamples?: number;\n midiNotes?: MidiNoteData[];\n midiChannel?: number;\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\nexport function createClipFromTicks(options: CreateClipOptionsTicks): AudioClip {\n const { startTick, ticksToSeconds, bpm, ppqn } = options;\n\n if (startTick < 0) {\n throw new Error('createClipFromTicks: startTick must be non-negative');\n }\n\n let toSeconds: (tick: number) => number;\n if (ticksToSeconds) {\n toSeconds = ticksToSeconds;\n } else if (bpm !== undefined && ppqn !== undefined) {\n toSeconds = (tick: number) => (tick * 60) / (ppqn * bpm);\n } else {\n throw new Error(\n 'createClipFromTicks: either ticksToSeconds callback or both bpm and ppqn are required'\n );\n }\n\n const sampleRate =\n options.audioBuffer?.sampleRate ?? options.sampleRate ?? options.waveformData?.sample_rate;\n if (sampleRate === undefined) {\n throw new Error('createClipFromTicks: sampleRate is required when audioBuffer is not provided');\n }\n\n const startSample = Math.round(toSeconds(startTick) * sampleRate);\n\n return createClip({\n audioBuffer: options.audioBuffer,\n startSample,\n startTick,\n durationSamples: options.durationSamples,\n offsetSamples: options.offsetSamples,\n gain: options.gain,\n name: options.name,\n color: options.color,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n waveformData: options.waveformData,\n sampleRate: options.sampleRate,\n sourceDurationSamples: options.sourceDurationSamples,\n midiNotes: options.midiNotes,\n midiChannel: options.midiChannel,\n midiProgram: options.midiProgram,\n src: options.src,\n });\n}\n\n/**\n * Options for creating a new track\n */\nexport interface CreateTrackOptions {\n name: string;\n /** What the track holds. Default: 'audio'. */\n kind?: TrackKind;\n clips?: AudioClip[];\n muted?: boolean;\n soloed?: boolean;\n volume?: number;\n pan?: number;\n color?: string;\n height?: number;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n}\n\n/**\n * Creates a new AudioClip with sensible defaults (using sample counts)\n *\n * For peaks-first rendering (no audioBuffer), sampleRate and sourceDurationSamples can be:\n * - Provided explicitly via options\n * - Derived from waveformData (sample_rate and duration properties)\n */\nexport function createClip(options: CreateClipOptions): AudioClip {\n const {\n audioBuffer,\n startSample,\n startTick,\n offsetSamples = 0,\n gain = 1.0,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n } = options;\n\n // Determine sample rate: audioBuffer > explicit option > waveformData\n const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;\n\n // Determine source duration: audioBuffer > explicit option > waveformData (converted to samples)\n const sourceDurationSamples =\n audioBuffer?.length ??\n options.sourceDurationSamples ??\n (waveformData && sampleRate ? Math.ceil(waveformData.duration * sampleRate) : undefined);\n\n if (sampleRate === undefined) {\n throw new Error(\n 'createClip: sampleRate is required when audioBuffer is not provided (can use waveformData.sample_rate)'\n );\n }\n if (sourceDurationSamples === undefined) {\n throw new Error(\n 'createClip: sourceDurationSamples is required when audioBuffer is not provided (can use waveformData.duration)'\n );\n }\n\n if (audioBuffer && waveformData && audioBuffer.sampleRate !== waveformData.sample_rate) {\n console.warn(\n '[waveform-playlist] \"' +\n (name ?? 'unnamed') +\n '\": pre-computed peaks at ' +\n waveformData.sample_rate +\n ' Hz do not match decoded audio at ' +\n audioBuffer.sampleRate +\n ' Hz — peaks may be recomputed from decoded audio'\n );\n }\n\n // Default duration to full source duration\n const durationSamples = options.durationSamples ?? sourceDurationSamples;\n\n return {\n id: generateId(),\n audioBuffer,\n startSample,\n startTick,\n durationSamples,\n offsetSamples,\n sampleRate,\n sourceDurationSamples,\n gain,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n ...(src !== undefined ? { src } : {}),\n };\n}\n\n/**\n * Creates a new AudioClip from time-based values (convenience function)\n * Converts seconds to samples using the audioBuffer's sampleRate or explicit sampleRate\n *\n * For peaks-first rendering (no audioBuffer), sampleRate and sourceDuration can be:\n * - Provided explicitly via options\n * - Derived from waveformData (sample_rate and duration properties)\n */\nexport function createClipFromSeconds(options: CreateClipOptionsSeconds): AudioClip {\n const {\n audioBuffer,\n startTime,\n offset = 0,\n gain = 1.0,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n } = options;\n\n // Determine sample rate: audioBuffer > explicit option > waveformData\n const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;\n if (sampleRate === undefined) {\n throw new Error(\n 'createClipFromSeconds: sampleRate is required when audioBuffer is not provided (can use waveformData.sample_rate)'\n );\n }\n\n // Determine source duration: audioBuffer > explicit option > waveformData\n const sourceDuration = audioBuffer?.duration ?? options.sourceDuration ?? waveformData?.duration;\n if (sourceDuration === undefined) {\n throw new Error(\n 'createClipFromSeconds: sourceDuration is required when audioBuffer is not provided (can use waveformData.duration)'\n );\n }\n\n // Note: audioBuffer and waveformData may have different sample rates (e.g., Opus at 48000\n // decoded on 44100 hardware). This is expected — callers fall back to worker to recompute peaks.\n\n // Default clip duration to full source duration\n const duration = options.duration ?? sourceDuration;\n\n return createClip({\n audioBuffer,\n startSample: Math.round(startTime * sampleRate),\n startTick: options.startTick,\n durationSamples: Math.round(duration * sampleRate),\n offsetSamples: Math.round(offset * sampleRate),\n sampleRate,\n sourceDurationSamples: Math.ceil(sourceDuration * sampleRate),\n gain,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n });\n}\n\n/**\n * Creates a new ClipTrack with sensible defaults\n */\nexport function createTrack(options: CreateTrackOptions): ClipTrack {\n const {\n name,\n kind = 'audio',\n clips = [],\n muted = false,\n soloed = false,\n volume = 1.0,\n pan = 0,\n color,\n height,\n spectrogramConfig,\n spectrogramColorMap,\n } = options;\n\n return {\n id: generateId(),\n kind,\n name,\n clips,\n muted,\n soloed,\n volume,\n pan,\n color,\n height,\n spectrogramConfig,\n spectrogramColorMap,\n };\n}\n\n/**\n * Creates a new Timeline with sensible defaults\n */\nexport function createTimeline(\n tracks: ClipTrack[],\n sampleRate: number = 44100,\n options?: {\n name?: string;\n tempo?: number;\n timeSignature?: { numerator: number; denominator: number };\n }\n): Timeline {\n // Calculate total duration from all clips across all tracks (in seconds)\n const durationSamples = tracks.reduce((maxSamples, track) => {\n const trackSamples = track.clips.reduce((max, clip) => {\n return Math.max(max, clip.startSample + clip.durationSamples);\n }, 0);\n return Math.max(maxSamples, trackSamples);\n }, 0);\n\n const duration = durationSamples / sampleRate;\n\n return {\n tracks,\n duration,\n sampleRate,\n name: options?.name,\n tempo: options?.tempo,\n timeSignature: options?.timeSignature,\n };\n}\n\n/**\n * Generates a unique ID for clips and tracks\n */\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\n/**\n * MIDI note data for clips that play MIDI instead of audio.\n * When present on an AudioClip, the clip is treated as a MIDI clip\n * by the playout adapter.\n */\nexport interface MidiNoteData {\n /** MIDI note number (0-127) */\n midi: number;\n /** Note name in scientific pitch notation (\"C4\", \"G#3\") */\n name: string;\n /** Start time in seconds, relative to clip start */\n time: number;\n /** Duration in seconds */\n duration: number;\n /** Velocity (0-1 normalized) */\n velocity: number;\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. Enables per-note routing in flattened tracks. */\n channel?: number;\n}\n\n/**\n * Utility: Get all clips within a sample range\n */\nexport function getClipsInRange(\n track: ClipTrack,\n startSample: number,\n endSample: number\n): AudioClip[] {\n return track.clips.filter((clip) => {\n const clipEnd = clip.startSample + clip.durationSamples;\n // Clip overlaps with range if:\n // - Clip starts before range ends AND\n // - Clip ends after range starts\n return clip.startSample < endSample && clipEnd > startSample;\n });\n}\n\n/**\n * Utility: Get all clips at a specific sample position\n */\nexport function getClipsAtSample(track: ClipTrack, sample: number): AudioClip[] {\n return track.clips.filter((clip) => {\n const clipEnd = clip.startSample + clip.durationSamples;\n return sample >= clip.startSample && sample < clipEnd;\n });\n}\n\n/**\n * Utility: Check if two clips overlap\n */\nexport function clipsOverlap(clip1: AudioClip, clip2: AudioClip): boolean {\n const clip1End = clip1.startSample + clip1.durationSamples;\n const clip2End = clip2.startSample + clip2.durationSamples;\n\n return clip1.startSample < clip2End && clip1End > clip2.startSample;\n}\n\n/**\n * Utility: Sort clips by startSample\n */\nexport function sortClipsByTime(clips: AudioClip[]): AudioClip[] {\n return [...clips].sort((a, b) => a.startSample - b.startSample);\n}\n\n/**\n * Utility: Find gaps between clips (silent regions)\n */\nexport interface Gap {\n startSample: number;\n endSample: number;\n durationSamples: number;\n}\n\nexport function findGaps(track: ClipTrack): Gap[] {\n if (track.clips.length === 0) return [];\n\n const sorted = sortClipsByTime(track.clips);\n const gaps: Gap[] = [];\n\n for (let i = 0; i < sorted.length - 1; i++) {\n const currentClipEnd = sorted[i].startSample + sorted[i].durationSamples;\n const nextClipStart = sorted[i + 1].startSample;\n\n if (nextClipStart > currentClipEnd) {\n gaps.push({\n startSample: currentClipEnd,\n endSample: nextClipStart,\n durationSamples: nextClipStart - currentClipEnd,\n });\n }\n }\n\n return gaps;\n}\n","/**\n * Peaks type - represents a typed array of interleaved min/max peak data\n */\nexport type Peaks = Int8Array | Int16Array;\n\n/**\n * Bits type - number of bits for peak data\n */\nexport type Bits = 8 | 16;\n\n/**\n * PeakData - result of peak extraction\n */\nexport interface PeakData {\n /** Number of peak pairs extracted */\n length: number;\n /** Array of peak data for each channel (interleaved min/max) */\n data: Peaks[];\n /** Bit depth of peak data */\n bits: Bits;\n}\n\nexport interface WaveformConfig {\n sampleRate: number;\n samplesPerPixel: number;\n waveHeight?: number;\n waveOutlineColor?: string;\n waveFillColor?: string;\n waveProgressColor?: string;\n}\n\nexport interface AudioBuffer {\n length: number;\n duration: number;\n numberOfChannels: number;\n sampleRate: number;\n getChannelData(channel: number): Float32Array;\n}\n\nexport interface Track {\n id: string;\n name: string;\n src?: string | AudioBuffer; // Support both URL strings and AudioBuffer objects\n gain: number;\n muted: boolean;\n soloed: boolean;\n stereoPan: number;\n startTime: number;\n endTime?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n cueIn?: number;\n cueOut?: number;\n}\n\n/**\n * Simple fade configuration\n */\nexport interface Fade {\n /** Duration of the fade in seconds */\n duration: number;\n /** Type of fade curve (default: 'linear') */\n type?: FadeType;\n}\n\nexport type FadeType = 'logarithmic' | 'linear' | 'sCurve' | 'exponential';\n\n/**\n * Alias for Fade — used by media-element-playout and playout packages\n */\nexport type FadeConfig = Fade;\n\nexport interface PlaylistConfig {\n samplesPerPixel?: number;\n waveHeight?: number;\n container?: HTMLElement;\n isAutomaticScroll?: boolean;\n timescale?: boolean;\n colors?: {\n waveOutlineColor?: string;\n waveFillColor?: string;\n waveProgressColor?: string;\n };\n controls?: {\n show?: boolean;\n width?: number;\n };\n zoomLevels?: number[];\n}\n\nexport interface PlayoutState {\n isPlaying: boolean;\n isPaused: boolean;\n cursor: number;\n duration: number;\n}\n\nexport interface TimeSelection {\n start: number;\n end: number;\n}\n\nexport enum InteractionState {\n Cursor = 'cursor',\n Select = 'select',\n Shift = 'shift',\n FadeIn = 'fadein',\n FadeOut = 'fadeout',\n}\n\n// Export clip-based model types\nexport * from './clip';\n\n// Export spectrogram types\nexport * from './spectrogram';\n\n// Export annotation types\nexport * from './annotations';\n","export function samplesToSeconds(samples: number, sampleRate: number): number {\n return samples / sampleRate;\n}\n\nexport function secondsToSamples(seconds: number, sampleRate: number): number {\n return Math.ceil(seconds * sampleRate);\n}\n\nexport function samplesToPixels(samples: number, samplesPerPixel: number): number {\n return Math.floor(samples / samplesPerPixel);\n}\n\nexport function pixelsToSamples(pixels: number, samplesPerPixel: number): number {\n return Math.floor(pixels * samplesPerPixel);\n}\n\nexport function pixelsToSeconds(\n pixels: number,\n samplesPerPixel: number,\n sampleRate: number\n): number {\n return (pixels * samplesPerPixel) / sampleRate;\n}\n\nexport function secondsToPixels(\n seconds: number,\n samplesPerPixel: number,\n sampleRate: number\n): number {\n return Math.ceil((seconds * sampleRate) / samplesPerPixel);\n}\n","/** Default PPQN matching Tone.js Transport (192 ticks per quarter note) */\nexport const PPQN = 192;\n\n/** Number of PPQN ticks per beat for the given time signature. */\nexport function ticksPerBeat(timeSignature: [number, number], ppqn = PPQN): number {\n const [, denominator] = timeSignature;\n return ppqn * (4 / denominator);\n}\n\n/** Number of PPQN ticks per bar for the given time signature. */\nexport function ticksPerBar(timeSignature: [number, number], ppqn = PPQN): number {\n const [numerator] = timeSignature;\n return numerator * ticksPerBeat(timeSignature, ppqn);\n}\n\n/** Convert PPQN ticks to sample count. Uses Math.round for integer sample alignment. */\nexport function ticksToSamples(\n ticks: number,\n bpm: number,\n sampleRate: number,\n ppqn = PPQN\n): number {\n return Math.round((ticks * 60 * sampleRate) / (bpm * ppqn));\n}\n\n/** Convert sample count to PPQN ticks. Inverse of ticksToSamples. */\nexport function samplesToTicks(\n samples: number,\n bpm: number,\n sampleRate: number,\n ppqn = PPQN\n): number {\n return Math.round((samples * ppqn * bpm) / (60 * sampleRate));\n}\n\n/** Snap a tick position to the nearest grid line (rounds to nearest). */\nexport function snapToGrid(ticks: number, gridSizeTicks: number): number {\n return Math.round(ticks / gridSizeTicks) * gridSizeTicks;\n}\n","const DEFAULT_FLOOR = -100;\n\n/**\n * Convert a dB value to a normalized range.\n *\n * Maps dB values linearly: floor → 0, 0 dB → 1.\n * Values above 0 dB map to > 1 (e.g., +5 dB → 1.05 with default floor).\n *\n * @param dB - Decibel value (typically -Infinity to +5)\n * @param floor - Minimum dB value mapped to 0. Default: -100 (Firefox compat)\n * @returns Normalized value (0 at floor, 1 at 0 dB, >1 above 0 dB)\n */\nexport function dBToNormalized(dB: number, floor: number = DEFAULT_FLOOR): number {\n if (Number.isNaN(dB)) {\n console.warn('[waveform-playlist] dBToNormalized received NaN');\n return 0;\n }\n if (floor >= 0) {\n console.warn('[waveform-playlist] dBToNormalized floor must be negative, got:', floor);\n return 0;\n }\n if (!isFinite(dB) || dB <= floor) return 0;\n return (dB - floor) / -floor;\n}\n\n/**\n * Convert a normalized value back to dB.\n *\n * Maps linearly: 0 → floor, 1 → 0 dB.\n * Values above 1 map to positive dB (e.g., 1.05 → +5 dB with default floor).\n *\n * @param normalized - Normalized value (0 = floor, 1 = 0 dB)\n * @param floor - Minimum dB value (maps from 0). Must be negative. Default: -100\n * @returns dB value (floor at 0, 0 dB at 1, positive dB above 1)\n */\nexport function normalizedToDb(normalized: number, floor: number = DEFAULT_FLOOR): number {\n if (!isFinite(normalized)) return floor;\n if (floor >= 0) {\n console.warn('[waveform-playlist] normalizedToDb floor must be negative, got:', floor);\n return DEFAULT_FLOOR;\n }\n const clamped = Math.max(0, normalized);\n return clamped * -floor + floor;\n}\n\n/**\n * Convert a linear gain value to decibels.\n *\n * @param gain - Linear gain (0 = silence, 1 = unity)\n * @returns Decibel value (e.g., 0.5 → ≈ -6.02 dB)\n */\nexport function gainToDb(gain: number): number {\n return 20 * Math.log10(Math.max(gain, 0.0001));\n}\n\n/**\n * Convert a linear gain value (0-1+) to normalized 0-1 via dB.\n *\n * Combines gain-to-dB (20 * log10) with dBToNormalized for a consistent\n * mapping from raw AudioWorklet peak/RMS values to the 0-1 range used\n * by UI meter components.\n *\n * @param gain - Linear gain value (typically 0 to 1, can exceed 1)\n * @param floor - Minimum dB value mapped to 0. Default: -100\n * @returns Normalized value (0 at silence/floor, 1 at 0 dB, >1 above 0 dB)\n */\nexport function gainToNormalized(gain: number, floor: number = DEFAULT_FLOOR): number {\n if (gain <= 0) return 0;\n // Use raw log10 (no clamp) — gain > 0 is guaranteed above,\n // and dBToNormalized handles -Infinity via its floor check.\n const db = 20 * Math.log10(gain);\n return dBToNormalized(db, floor);\n}\n","import { ticksPerBeat, ticksPerBar } from './beatsAndBars';\nimport type { MeterEntry } from './meterDetection';\n\nexport type { MeterEntry } from './meterDetection';\n\n/** All supported snap-to-grid values. */\nexport type SnapTo =\n | 'bar'\n | 'beat'\n | '1/2'\n | '1/4'\n | '1/8'\n | '1/16'\n | '1/32'\n | '1/2T'\n | '1/4T'\n | '1/8T'\n | '1/16T'\n | 'off';\n\n/**\n * Returns the tick interval for the given SnapTo value.\n *\n * Straight subdivisions (1/2, 1/4, 1/8, 1/16, 1/32) are always expressed as\n * fractions of a quarter note (ppqn), independent of the time signature\n * denominator. Triplet subdivisions use × 2/3 of the corresponding straight\n * value. 'bar' and 'beat' depend on the `timeSignature` argument (the\n * caller passes the meter entry active at the position).\n * 'off' returns 0.\n */\nexport function snapToTicks(snapTo: SnapTo, timeSignature: [number, number], ppqn = 960): number {\n const ts = timeSignature;\n switch (snapTo) {\n case 'bar':\n return ticksPerBar(ts, ppqn);\n case 'beat':\n return ticksPerBeat(ts, ppqn);\n case '1/2':\n return ppqn * 2;\n case '1/4':\n return ppqn;\n case '1/8':\n return ppqn / 2;\n case '1/16':\n return ppqn / 4;\n case '1/32':\n return ppqn / 8;\n case '1/2T':\n return Math.round((ppqn * 2 * 2) / 3);\n case '1/4T':\n return Math.round((ppqn * 2) / 3);\n case '1/8T':\n return Math.round((ppqn * 2) / 6);\n case '1/16T':\n return Math.round((ppqn * 2) / 12);\n case 'off':\n return 0;\n }\n}\n\n/**\n * Three-tier tick hierarchy (following Audacity's model):\n * major — Bar boundaries. Always labeled, strongest grid lines.\n * minor — Beat boundaries. Labeled when wide enough, medium grid lines.\n * minorMinor — Subdivisions (eighths, sixteenths). Never labeled, ruler ticks only (no grid).\n */\nexport type TickType = 'major' | 'minor' | 'minorMinor';\n\n/** Zoom level category used to select which subdivision to iterate at. */\nexport type ZoomLevel = 'coarse' | 'bar' | 'beat' | 'eighth' | 'sixteenth';\n\n/** A single musical tick with rendering metadata. */\nexport interface MusicalTick {\n /** Pixel position of the tick in the timeline. */\n pixel: number;\n /** Three-tier type: major (bar), minor (beat), minorMinor (subdivision). */\n type: TickType;\n /** Human-readable label. Present for major ticks always; minor ticks when zoomed in. */\n label?: string;\n /** 0-based global bar index (for alternating bar-level striping). */\n barIndex: number;\n}\n\n/** Result of computeMusicalTicks(). */\nexport interface MusicalTickData {\n ticks: MusicalTick[];\n pixelsPerQuarterNote: number;\n zoomLevel: ZoomLevel;\n /** At 'coarse' zoom: how many quarter notes between rendered tick lines. */\n coarseQuarterNoteStep?: number;\n}\n\n/** Parameters for computeMusicalTicks(). */\nexport interface MusicalTickParams {\n meterEntries: MeterEntry[];\n /** Ticks per pixel (zoom level — lower value = more zoomed in). */\n ticksPerPixel: number;\n startPixel: number;\n endPixel: number;\n /** Pulses per quarter note. Defaults to 960. */\n ppqn?: number;\n}\n\n/** Minimum pixels per musical unit before switching to a coarser zoom level. */\nexport const MIN_PIXELS_PER_UNIT = 8;\n\n/** Minimum pixels between beat labels for readable text. */\nconst MIN_PIXELS_PER_LABEL = 60;\n\n/**\n * Determines the zoom level and computes which tick lines to render for a\n * given viewport. Pure tick arithmetic — no BPM or sample rate required.\n *\n * Walks meter entries in segments, so bar/beat boundaries and labels are\n * correct across meter changes.\n */\nexport function computeMusicalTicks(params: MusicalTickParams): MusicalTickData {\n const { meterEntries, ticksPerPixel, startPixel, endPixel, ppqn = 960 } = params;\n\n const firstMeter = meterEntries[0] ?? { tick: 0, numerator: 4, denominator: 4 };\n\n // Guard against invalid inputs that would cause division by zero or infinite loops\n if (ticksPerPixel <= 0 || ppqn <= 0 || firstMeter.denominator <= 0) {\n return { ticks: [], pixelsPerQuarterNote: 0, zoomLevel: 'coarse' };\n }\n\n // pixelsPerQuarterNote is constant across meters — only depends on ppqn and zoom\n const pixelsPerQuarterNote = ppqn / ticksPerPixel;\n\n // All zoom thresholds derived from pixelsPerQuarterNote (meter-independent).\n // Quarter note subdivisions: half = 2×, eighth = 0.5×, sixteenth = 0.25×.\n // \"Bar\" threshold uses 4× quarter note (a 4/4 bar) — conservative minimum.\n const tpEighth = ppqn / 2;\n const tpSixteenth = ppqn / 4;\n const pixelsPerEighth = tpEighth / ticksPerPixel;\n const pixelsPerSixteenth = tpSixteenth / ticksPerPixel;\n\n let zoomLevel: ZoomLevel;\n if (pixelsPerQuarterNote * 4 < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'coarse';\n } else if (pixelsPerQuarterNote < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'bar';\n } else if (pixelsPerEighth < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'beat';\n } else if (pixelsPerSixteenth < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'eighth';\n } else {\n zoomLevel = 'sixteenth';\n }\n\n // Coarse step in quarter notes — meter-independent so all segments\n // render at the same visual density regardless of time signature.\n let coarseQuarterNoteStep: number | undefined;\n let coarseQuarterNotes = 0;\n if (zoomLevel === 'coarse') {\n coarseQuarterNotes = 2;\n while ((coarseQuarterNotes * ppqn) / ticksPerPixel < MIN_PIXELS_PER_UNIT) {\n coarseQuarterNotes *= 2;\n }\n coarseQuarterNoteStep = coarseQuarterNotes;\n }\n\n const startTick = startPixel * ticksPerPixel;\n const endTick = endPixel * ticksPerPixel;\n\n // Build the list of meter segments: [start, end) in ticks, with per-segment bar offset\n const segments: Array<{\n segmentStartTick: number;\n segmentEndTick: number;\n meter: MeterEntry;\n barOffset: number; // cumulative bar count before this segment\n }> = [];\n\n {\n let cumulativeBars = 0;\n for (let i = 0; i < meterEntries.length; i++) {\n const meter = meterEntries[i];\n const segmentStart = meter.tick;\n const segmentEnd =\n i + 1 < meterEntries.length ? meterEntries[i + 1].tick : Number.MAX_SAFE_INTEGER;\n\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n\n segments.push({\n segmentStartTick: segmentStart,\n segmentEndTick: segmentEnd,\n meter,\n barOffset: cumulativeBars,\n });\n\n // Count how many whole bars fit in this segment (for finite segments)\n if (segmentEnd !== Number.MAX_SAFE_INTEGER) {\n const segmentLen = segmentEnd - segmentStart;\n cumulativeBars += Math.floor(segmentLen / tpBar);\n }\n }\n }\n\n const ticks: MusicalTick[] = [];\n\n // Walk each meter segment and emit ticks within the visible range\n for (const { segmentStartTick, segmentEndTick, meter, barOffset } of segments) {\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBeat = ticksPerBeat(ts, ppqn);\n const tpBar = ticksPerBar(ts, ppqn);\n\n // Determine step size for this segment\n let stepTicks: number;\n if (zoomLevel === 'coarse') {\n stepTicks = coarseQuarterNotes * ppqn;\n } else if (zoomLevel === 'bar') {\n stepTicks = tpBar;\n } else if (zoomLevel === 'beat') {\n stepTicks = tpBeat;\n } else if (zoomLevel === 'eighth') {\n stepTicks = tpEighth;\n } else {\n stepTicks = tpSixteenth;\n }\n\n // Visible tick range of this segment. The first emitted step may sit\n // before segmentTickStart (its bar/segment anchor is off-screen); the\n // pixel guard below skips it.\n const segmentTickStart = Math.max(segmentStartTick, startTick);\n const segmentTickEnd = Math.min(segmentEndTick - 1, endTick);\n\n if (segmentTickStart > segmentTickEnd) {\n continue;\n }\n\n // Grid lines restart at each bar line (the rule snapTickToGrid and\n // @dawcore/transport's quantizeTick follow), so a step that does not\n // divide the bar — eighths in 7/16 — never crosses one. The coarse level\n // is meter-independent by design (constant visual density) and keeps\n // stepping from the segment start.\n const restartAtBar = zoomLevel !== 'coarse';\n const offsetIntoSegment = segmentTickStart - segmentStartTick;\n const anchorTick = restartAtBar\n ? segmentStartTick + Math.floor(offsetIntoSegment / tpBar) * tpBar\n : segmentStartTick;\n const firstStepTick =\n anchorTick + Math.floor((segmentTickStart - anchorTick) / stepTicks) * stepTicks;\n const nextGridTick = (tick: number): number => {\n const next = tick + stepTicks;\n if (!restartAtBar) return next;\n const nextBarTick =\n segmentStartTick + (Math.floor((tick - segmentStartTick) / tpBar) + 1) * tpBar;\n return Math.min(next, nextBarTick);\n };\n\n for (\n let tick = firstStepTick;\n tick <= segmentTickEnd && tick < segmentEndTick;\n tick = nextGridTick(tick)\n ) {\n const pixel = tick / ticksPerPixel;\n\n if (pixel < startPixel || pixel > endPixel) {\n continue;\n }\n\n // Classify into three-tier hierarchy\n const tickOffsetInSegment = tick - segmentStartTick;\n let type: TickType;\n if (tickOffsetInSegment % tpBar === 0) {\n type = 'major';\n } else if (tickOffsetInSegment % tpBeat === 0) {\n type = 'minor';\n } else {\n type = 'minorMinor';\n }\n\n // Cumulative bar index for zebra striping\n const barIndexInSegment = Math.floor(tickOffsetInSegment / tpBar);\n const barIndex = barOffset + barIndexInSegment;\n\n // Labels: major always, minor only when wide enough, minorMinor never\n let label: string | undefined;\n if (type === 'major') {\n label = `${barIndex + 1}`;\n } else if (type === 'minor' && tpBeat / ticksPerPixel >= MIN_PIXELS_PER_LABEL) {\n const beatInBar = Math.floor((tickOffsetInSegment % tpBar) / tpBeat) + 1;\n label = `${barIndex + 1}.${beatInBar}`;\n }\n\n ticks.push({ pixel, type, barIndex, ...(label !== undefined ? { label } : {}) });\n }\n }\n\n // Sort by pixel (segments are ordered, but floating point steps may cause slight reordering)\n ticks.sort((a, b) => a.pixel - b.pixel);\n\n const result: MusicalTickData = {\n ticks,\n pixelsPerQuarterNote,\n zoomLevel,\n ...(coarseQuarterNoteStep !== undefined ? { coarseQuarterNoteStep } : {}),\n };\n\n return result;\n}\n\n/**\n * Convert an absolute tick to a 1-based bar.beat position, honoring meter\n * changes. Bars/beats are counted per meter segment (the same walk\n * `computeMusicalTicks` uses to build its `barOffset` accumulator). Beat is\n * the integer beat the tick falls WITHIN (floor, 1-based) — a tick exactly on\n * a bar line is beat 1.\n *\n * Guards: empty `meterEntries` → treat as 4/4 from tick 0. `ppqn <= 0` →\n * returns `{ bar: 1, beat: 1 }` (division-by-zero guard, matches\n * `computeMusicalTicks`'s ppqn guard).\n */\nexport function ticksToBarBeat(\n tick: number,\n meterEntries: MeterEntry[],\n ppqn: number\n): { bar: number; beat: number } {\n if (ppqn <= 0) return { bar: 1, beat: 1 };\n\n const entries =\n meterEntries.length > 0 ? meterEntries : [{ tick: 0, numerator: 4, denominator: 4 }];\n\n let barOffset = 0;\n for (let i = 0; i < entries.length; i++) {\n const meter = entries[i];\n const segmentStart = meter.tick;\n const segmentEnd = i + 1 < entries.length ? entries[i + 1].tick : Number.MAX_SAFE_INTEGER;\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n const tpBeat = ticksPerBeat(ts, ppqn);\n\n if (tick >= segmentStart && tick < segmentEnd) {\n const offset = tick - segmentStart;\n const barIndexInSegment = Math.floor(offset / tpBar);\n const beatInBar = Math.floor((offset % tpBar) / tpBeat);\n return { bar: barOffset + barIndexInSegment + 1, beat: beatInBar + 1 };\n }\n\n if (segmentEnd !== Number.MAX_SAFE_INTEGER) {\n const segmentLen = segmentEnd - segmentStart;\n barOffset += Math.floor(segmentLen / tpBar);\n }\n }\n\n // tick precedes the first meter entry (non-standard input) — fall back to\n // the first meter's math from its own start tick.\n const first = entries[0];\n const ts: [number, number] = [first.numerator, first.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n const tpBeat = ticksPerBeat(ts, ppqn);\n const offset = tick - first.tick;\n const barIndexInSegment = Math.floor(offset / tpBar);\n const beatInBar = Math.floor((offset % tpBar) / tpBeat);\n return { bar: barIndexInSegment + 1, beat: beatInBar + 1 };\n}\n\n/**\n * Snaps a tick position to the nearest grid boundary defined by `snapTo`.\n *\n * Finds the meter entry active at the tick position, then the BAR containing\n * the tick, and snaps relative to that bar's start: grid lines restart at\n * each bar line (the same rule as `@dawcore/transport`'s `quantizeTick` and\n * the drawn ruler grid), so odd meters stay aligned — in 7/8 at 960 PPQN a\n * quarter-note grid is 0, 960, 1920, 2880 and then the bar line at 3360,\n * never 3840. A subdivision longer than the bar leaves only the bar lines.\n * An exact tie snaps up; a tick already on a line stays put. Unlike\n * `quantizeTick`, the result is not rounded (a fractional grid size at an\n * unusual PPQN gives a fractional tick), triplet steps use the rounded\n * `snapToTicks` value, negative ticks are accepted (the lattice extends\n * backwards) and meter entries need not sit on bar boundaries of the\n * preceding meter (the next line is capped at the following entry).\n *\n * Returns the original tick unchanged when `snapTo` is 'off'.\n */\nexport function snapTickToGrid(\n tick: number,\n snapTo: SnapTo,\n meterEntries: MeterEntry[],\n ppqn = 960\n): number {\n if (snapTo === 'off') return tick;\n\n // Find the active meter entry for this tick, and where the next one starts\n let meter = meterEntries[0] ?? { tick: 0, numerator: 4, denominator: 4 };\n let nextEntryTick = Infinity;\n for (const entry of meterEntries) {\n if (entry.tick <= tick) {\n meter = entry;\n } else {\n nextEntryTick = entry.tick;\n break;\n }\n }\n\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const gridSize = snapToTicks(snapTo, ts, ppqn);\n if (gridSize <= 0) return tick;\n\n const barLength = ticksPerBar(ts, ppqn);\n if (!(barLength > 0)) {\n // Degenerate entry (numerator 0): no bars to anchor to — plain snap from\n // the entry rather than a NaN that would flow into clip positions.\n return meter.tick + Math.round((tick - meter.tick) / gridSize) * gridSize;\n }\n\n // Snap within the bar containing the tick; the line after the bar's last\n // whole subdivision is the next bar line — or the next meter entry, when\n // a hand-built map puts one off the bar grid (the drawn grid ends the\n // segment there too).\n const barStart = meter.tick + Math.floor((tick - meter.tick) / barLength) * barLength;\n const previous = barStart + Math.floor((tick - barStart) / gridSize) * gridSize;\n const next = Math.min(previous + gridSize, barStart + barLength, nextEntryTick);\n return tick - previous < next - tick ? previous : next;\n}\n","export interface MeterEntry {\n tick: number;\n numerator: number;\n denominator: number;\n}\n\n/**\n * Scans a beat number sequence and detects meter (time signature) changes.\n *\n * Each beat in the input has a `beat` number (1-indexed). When the beat resets\n * to 1, we count how many beats were in the previous bar and derive the numerator.\n *\n * @param beats - Array of beat events with `time` (seconds) and `beat` (1-indexed number).\n * @param firstBeatTick - The tick position of beats[0] on the timeline.\n * @param ppqn - Ticks per quarter note (ticks per beat).\n * @returns Array of MeterEntry sorted by tick. Always includes an entry at tick 0.\n */\nexport function detectMeterChanges(\n beats: { time: number; beat: number }[],\n firstBeatTick: number,\n ppqn: number\n): MeterEntry[] {\n const DEFAULT_NUMERATOR = 4;\n const DENOMINATOR = 4;\n\n const defaultResult: MeterEntry[] = [\n { tick: 0, numerator: DEFAULT_NUMERATOR, denominator: DENOMINATOR },\n ];\n\n if (beats.length === 0) {\n return defaultResult;\n }\n\n // Find the index of the first downbeat (beat === 1)\n const firstDownbeatIndex = beats.findIndex((b) => b.beat === 1);\n\n if (firstDownbeatIndex === -1) {\n // No downbeat found — default to 4/4\n return defaultResult;\n }\n\n // Collect completed bars: for each bar, record its start beat index and beat count\n const bars: { beatIndex: number; count: number }[] = [];\n let barStartBeatIndex = firstDownbeatIndex;\n\n for (let i = firstDownbeatIndex + 1; i < beats.length; i++) {\n if (beats[i].beat === 1) {\n bars.push({ beatIndex: barStartBeatIndex, count: i - barStartBeatIndex });\n barStartBeatIndex = i;\n }\n }\n\n if (bars.length === 0) {\n // Only one downbeat observed — can't determine meter\n return defaultResult;\n }\n\n // Build raw meter entries: emit a new entry only when numerator changes\n const rawEntries: MeterEntry[] = [];\n let prevNumerator = -1;\n\n for (const bar of bars) {\n const numerator = bar.count;\n if (numerator !== prevNumerator) {\n const tick = firstBeatTick + bar.beatIndex * ppqn;\n rawEntries.push({ tick, numerator, denominator: DENOMINATOR });\n prevNumerator = numerator;\n }\n }\n\n // Ensure tick 0 is always present\n if (rawEntries.length === 0) {\n return defaultResult;\n }\n\n if (rawEntries[0].tick === 0) {\n return rawEntries;\n }\n\n // First entry is after tick 0 — prepend tick 0 with the same numerator\n const tick0Entry: MeterEntry = {\n tick: 0,\n numerator: rawEntries[0].numerator,\n denominator: DENOMINATOR,\n };\n\n // If the first raw entry has the same numerator as tick 0, we don't need it as a\n // separate entry (they'd be adjacent duplicates). Drop the first raw entry and use\n // the tick-0 entry to represent it.\n const rest = rawEntries[0].numerator === tick0Entry.numerator ? rawEntries.slice(1) : rawEntries;\n\n return [tick0Entry, ...rest];\n}\n","/**\n * Peak generation for real-time waveform visualization during recording.\n * Matches the format used by webaudio-peaks: min/max pairs with bit depth.\n */\n\n/**\n * Generate peaks from audio samples in standard min/max pair format.\n *\n * @param samples - Audio samples to process\n * @param samplesPerPixel - Number of samples to represent in each peak\n * @param bits - Bit depth for peak values (8 or 16)\n * @returns Int8Array or Int16Array of peak values (min/max pairs)\n */\nexport function generatePeaks(\n samples: Float32Array,\n samplesPerPixel: number,\n bits: 8 | 16 = 16\n): Int8Array | Int16Array {\n const numPeaks = Math.ceil(samples.length / samplesPerPixel);\n const peakArray = bits === 8 ? new Int8Array(numPeaks * 2) : new Int16Array(numPeaks * 2);\n const maxValue = 2 ** (bits - 1);\n\n for (let i = 0; i < numPeaks; i++) {\n const start = i * samplesPerPixel;\n const end = Math.min(start + samplesPerPixel, samples.length);\n\n let min = 0;\n let max = 0;\n\n for (let j = start; j < end; j++) {\n const value = samples[j];\n if (value < min) min = value;\n if (value > max) max = value;\n }\n\n // Store as min/max pairs scaled to bit depth\n // Clamp to valid range: Int16 is [-32768, 32767], Int8 is [-128, 127]\n peakArray[i * 2] = Math.max(-maxValue, Math.floor(min * maxValue));\n peakArray[i * 2 + 1] = Math.min(maxValue - 1, Math.floor(max * maxValue));\n }\n\n return peakArray;\n}\n\n/**\n * Append new peaks to existing peaks array.\n * This is used for incremental peak updates during recording.\n */\nexport function appendPeaks(\n existingPeaks: Int8Array | Int16Array,\n newSamples: Float32Array,\n samplesPerPixel: number,\n totalSamplesProcessed: number,\n bits: 8 | 16 = 16\n): Int8Array | Int16Array {\n const maxValue = 2 ** (bits - 1);\n\n // Check if we have a partial peak from the last update\n const remainder = totalSamplesProcessed % samplesPerPixel;\n let offset = 0;\n\n // If there's a partial peak, we need to update the last peak\n if (remainder > 0 && existingPeaks.length > 0) {\n const samplesToComplete = samplesPerPixel - remainder;\n const endIndex = Math.min(samplesToComplete, newSamples.length);\n\n // Get current min/max from last peak\n let min = existingPeaks[existingPeaks.length - 2] / maxValue;\n let max = existingPeaks[existingPeaks.length - 1] / maxValue;\n\n // Update with new samples\n for (let i = 0; i < endIndex; i++) {\n const value = newSamples[i];\n if (value < min) min = value;\n if (value > max) max = value;\n }\n\n // Update last peak\n const updated = new (bits === 8 ? Int8Array : Int16Array)(existingPeaks.length);\n updated.set(existingPeaks);\n updated[existingPeaks.length - 2] = Math.max(-maxValue, Math.floor(min * maxValue));\n updated[existingPeaks.length - 1] = Math.min(maxValue - 1, Math.floor(max * maxValue));\n\n offset = endIndex;\n\n // Generate peaks for remaining samples and concatenate\n const newPeaks = generatePeaks(newSamples.slice(offset), samplesPerPixel, bits);\n const result = new (bits === 8 ? Int8Array : Int16Array)(updated.length + newPeaks.length);\n result.set(updated);\n result.set(newPeaks, updated.length);\n return result;\n }\n\n // No partial peak, just concatenate\n const newPeaks = generatePeaks(newSamples.slice(offset), samplesPerPixel, bits);\n const result = new (bits === 8 ? Int8Array : Int16Array)(existingPeaks.length + newPeaks.length);\n result.set(existingPeaks);\n result.set(newPeaks, existingPeaks.length);\n return result;\n}\n","/**\n * Utility functions for working with AudioBuffers during recording\n */\n\n/**\n * Concatenate multiple Float32Arrays into a single array\n */\nexport function concatenateAudioData(chunks: Float32Array[]): Float32Array {\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const result = new Float32Array(totalLength);\n\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\n}\n\n/**\n * Convert channel data to AudioBuffer.\n * Accepts either per-channel Float32Array[] or a single Float32Array (mono, backwards compatible).\n */\nexport function createAudioBuffer(\n audioContext: AudioContext,\n channelData: Float32Array[] | Float32Array,\n sampleRate: number,\n channelCount: number = 1\n): AudioBuffer {\n // Backwards compatibility: single Float32Array → wrap as mono\n const channels: Float32Array[] =\n channelData instanceof Float32Array ? [channelData] : channelData;\n\n const length = channels[0]?.length ?? 0;\n const buffer = audioContext.createBuffer(channelCount, length, sampleRate);\n\n for (let ch = 0; ch < Math.min(channelCount, channels.length); ch++) {\n buffer.copyToChannel(new Float32Array(channels[ch]), ch);\n }\n\n return buffer;\n}\n\n/**\n * Append new samples to an existing AudioBuffer (mono convenience)\n */\nexport function appendToAudioBuffer(\n audioContext: AudioContext,\n existingBuffer: AudioBuffer | null,\n newSamples: Float32Array,\n sampleRate: number\n): AudioBuffer {\n if (!existingBuffer) {\n return createAudioBuffer(audioContext, [newSamples], sampleRate);\n }\n\n // Get existing samples\n const existingData = existingBuffer.getChannelData(0);\n\n // Concatenate using concatenateAudioData helper\n const combined = concatenateAudioData([existingData, newSamples]);\n\n // Create new buffer\n return createAudioBuffer(audioContext, [combined], sampleRate);\n}\n","/**\n * Sample count corresponding to the audible-latency window\n * (`outputLatency` + scheduler `lookAhead`). Used to skip leading silence in\n * recordings: between record-start and audible playback the user heard nothing,\n * so that prefix should be trimmed from buffers / peaks. Returns 0 for\n * non-finite or non-positive inputs.\n *\n * Single source of truth for `useIntegratedRecording` (buffer trim) and\n * the view's recording preview (live preview peak slice). Keep the two in lockstep\n * so the live preview width matches the finalized clip.\n */\nexport function audibleLatencySamples(\n outputLatency: number,\n lookAhead: number,\n sampleRate: number\n): number {\n const total = outputLatency + lookAhead;\n if (!Number.isFinite(total) || !Number.isFinite(sampleRate)) return 0;\n if (total <= 0 || sampleRate <= 0) return 0;\n return Math.floor(total * sampleRate);\n}\n\n/**\n * Resolve the recording latency offset in samples.\n *\n * When `overrideSeconds` is provided it is an **absolute replacement** for the\n * auto-computed value — a latency in seconds, converted at `sampleRate`\n * (`0` disables compensation; negative/non-finite resolve to `0`). Otherwise the\n * offset is the auto-computed audible-latency window (`outputLatency + lookAhead`).\n *\n * Single source of truth for the override-vs-auto decision across dawcore\n * (`RecordingController`) and React (`useIntegratedRecording` finalization +\n * the view's live preview). The override branch is the same math as\n * the auto branch with `lookAhead = 0`, so both inherit the finite/positive\n * guards in `audibleLatencySamples`.\n */\nexport function resolveRecordingOffsetSamples(params: {\n /** Public override (seconds). Absolute replacement when defined. */\n overrideSeconds?: number;\n /** Browser-reported output latency (seconds). */\n outputLatency: number;\n /** Scheduler look-ahead (seconds). Pass 0 for engines without one (native transport). */\n lookAhead: number;\n /** Sample rate the recording was captured at. */\n sampleRate: number;\n}): number {\n const { overrideSeconds, outputLatency, lookAhead, sampleRate } = params;\n return overrideSeconds !== undefined\n ? audibleLatencySamples(overrideSeconds, 0, sampleRate)\n : audibleLatencySamples(outputLatency, lookAhead, sampleRate);\n}\n","import type { SpectrogramConfig, ColorMapValue } from '../types/spectrogram';\n\n/**\n * Default values for `SpectrogramConfig` fields. Used by both the orchestrator\n * and the React controller so defaults can't drift between layers.\n *\n * Intentionally omitted:\n * - `maxFrequency` — defaults to `sampleRate / 2` at compute time (clip-dependent)\n * - `alpha` — window-specific (only used by the `hamming` window function); its\n * canonical default (0.54) lives in `windowFunctions.ts` where the math is\n * - `labelsColor`, `labelsBackground` — kept as optional `undefined` so consumers\n * can opt into label styling without forcing a color value\n */\nexport const SPECTROGRAM_DEFAULTS: Required<\n Omit<SpectrogramConfig, 'maxFrequency' | 'alpha' | 'labelsColor' | 'labelsBackground'>\n> & {\n labelsColor: string | undefined;\n labelsBackground: string | undefined;\n} = {\n fftSize: 2048,\n hopSize: 512,\n windowFunction: 'hann',\n frequencyScale: 'mel',\n minFrequency: 0,\n gainDb: 20,\n rangeDb: 80,\n zeroPaddingFactor: 2,\n labels: false,\n labelsColor: undefined,\n labelsBackground: undefined,\n};\n\n/** Default color map when none is specified. */\nexport const DEFAULT_SPECTROGRAM_COLOR_MAP: ColorMapValue = 'viridis';\n","/**\n * Punch-in replace: carve a sample range out of a clip list.\n *\n * Used when a newly recorded clip lands at the playhead and must REPLACE any\n * existing clip content between its start and end (issue #579): partial\n * overlaps are trimmed, fully-covered clips are removed, and a clip that\n * spans the whole range is split into two.\n */\n\nimport type { AudioClip } from '../types/clip';\n\n/**\n * Return a new clip list with the sample range [rangeStart, rangeEnd)\n * removed from every clip that overlaps it.\n *\n * - Clips outside the range are returned by reference (untouched).\n * - Clips fully inside the range are dropped.\n * - A clip overlapping only the range's start keeps its head (right-trim).\n * - A clip overlapping only the range's end keeps its tail: its start moves\n * to rangeEnd and `offsetSamples` advances by the carved amount.\n * - A clip containing the whole range splits into head + tail; the tail is a\n * new clip (deterministic id `<original>-carve-<rangeEnd>`) sharing the\n * same audioBuffer.\n *\n * Clips whose `startSample` changes lose their `startTick` — a sample-space\n * carve cannot recompute ticks, and the engine re-enriches clips without\n * `startTick` on ingestion (see AudioClip.startTick).\n *\n * Pure and immutable: input clips are never mutated. An empty or inverted\n * range returns the input list unchanged.\n */\nexport function carveClipRange(\n clips: readonly AudioClip[],\n rangeStart: number,\n rangeEnd: number\n): AudioClip[] {\n if (!(rangeEnd > rangeStart)) {\n return [...clips];\n }\n\n const result: AudioClip[] = [];\n\n for (const clip of clips) {\n const clipStart = clip.startSample;\n const clipEnd = clip.startSample + clip.durationSamples;\n\n // [start, end) overlap test — shared boundaries don't overlap\n if (clipEnd <= rangeStart || clipStart >= rangeEnd) {\n result.push(clip);\n continue;\n }\n\n const keepHead = clipStart < rangeStart;\n const keepTail = clipEnd > rangeEnd;\n\n if (keepHead) {\n result.push({\n ...clip,\n durationSamples: rangeStart - clipStart,\n });\n }\n\n if (keepTail) {\n const carvedFromClipStart = rangeEnd - clipStart;\n const tail: AudioClip = {\n ...clip,\n // Head + tail from one clip must not share an id\n id: keepHead ? `${clip.id}-carve-${rangeEnd}` : clip.id,\n startSample: rangeEnd,\n durationSamples: clipEnd - rangeEnd,\n offsetSamples: clip.offsetSamples + carvedFromClipStart,\n };\n // startSample changed — the stale authoritative tick position must not\n // survive (the engine re-derives it from startSample on ingestion).\n delete tail.startTick;\n result.push(tail);\n }\n\n // Neither head nor tail: fully covered, dropped.\n }\n\n return result;\n}\n","import { gainToNormalized } from './dBUtils';\nimport type { MeterLevels } from '../valueSource';\n\n/** Exponential decay per reading for the smoothed peak (~800 ms to 1/e at 60 Hz). */\nexport const METER_PEAK_DECAY = 0.98;\n\nexport interface MeterReading {\n /** Raw-gain smoothed peak per metered channel; pass back in with the next message. */\n smoothedPeaks: number[];\n /** The levels to show. */\n levels: MeterLevels;\n}\n\nexport interface ReadMeterMessageParams {\n /**\n * A meter worklet message: N peak gains followed by N RMS gains.\n */\n data: ArrayLike<number>;\n /** `smoothedPeaks` from the previous reading (empty for the first). */\n previousSmoothedPeaks: readonly number[];\n /** `levels.peakLevels` from the previous reading (empty after a reset). */\n heldPeakLevels: readonly number[];\n /**\n * When the message has fewer channels than this, channel 0 is repeated to\n * fill it (a mono microphone shown on a stereo meter). Default: 0.\n */\n minChannels?: number;\n}\n\n/**\n * Turn one meter worklet message into display levels: the peak jumps up at\n * once and decays slowly, RMS is passed through, and the held peak keeps the\n * highest level seen. Pure: nothing passed in is modified.\n */\nexport function readMeterMessage({\n data,\n previousSmoothedPeaks,\n heldPeakLevels,\n minChannels = 0,\n}: ReadMeterMessageParams): MeterReading {\n const channels = Math.floor(data.length / 2);\n const smoothedPeaks: number[] = [];\n const peaks: number[] = [];\n const rms: number[] = [];\n\n for (let ch = 0; ch < channels; ch++) {\n const smoothed = Math.max(data[ch], (previousSmoothedPeaks[ch] ?? 0) * METER_PEAK_DECAY);\n smoothedPeaks.push(smoothed);\n peaks.push(gainToNormalized(smoothed));\n rms.push(gainToNormalized(data[channels + ch]));\n }\n\n const mirror = channels > 0 && channels < minChannels;\n const levels = mirror ? new Array<number>(minChannels).fill(peaks[0]) : peaks;\n const rmsLevels = mirror ? new Array<number>(minChannels).fill(rms[0]) : rms;\n const peakLevels = levels.map((level, i) => Math.max(heldPeakLevels[i] ?? 0, level));\n\n return { smoothedPeaks, levels: { levels, peakLevels, rmsLevels } };\n}\n","import type { AudioClip } from './types';\n\n/** Clip start position in seconds */\nexport function clipStartTime(clip: AudioClip): number {\n return clip.startSample / clip.sampleRate;\n}\n\n/** Clip end position in seconds (start + duration) */\nexport function clipEndTime(clip: AudioClip): number {\n return (clip.startSample + clip.durationSamples) / clip.sampleRate;\n}\n\n/** Clip offset into source audio in seconds */\nexport function clipOffsetTime(clip: AudioClip): number {\n return clip.offsetSamples / clip.sampleRate;\n}\n\n/** Clip duration in seconds */\nexport function clipDurationTime(clip: AudioClip): number {\n return clip.durationSamples / clip.sampleRate;\n}\n\n/** The part of a track `trackChannelCount` reads — `ClipTrack` satisfies it. */\nexport interface TrackChannelSource {\n clips: ReadonlyArray<{ audioBuffer?: { numberOfChannels: number } }>;\n}\n\n/**\n * Max audio channel count across a track's clips (1 for a track with no\n * decoded audio). Selects the track's pan law (`createPanStage`) and the\n * offline render's output channels.\n */\nexport function trackChannelCount(track: TrackChannelSource): number {\n return track.clips.reduce(\n (max, clip) => Math.max(max, clip.audioBuffer?.numberOfChannels ?? 1),\n 1\n );\n}\n\n/**\n * Clip width in pixels at a given samplesPerPixel.\n * Shared by Clip.tsx (container sizing) and ChannelWithProgress.tsx (progress overlay)\n * to ensure pixel-perfect alignment. Floor-based endpoint subtraction guarantees\n * adjacent clips have no pixel gaps.\n */\nexport function clipPixelWidth(\n startSample: number,\n durationSamples: number,\n samplesPerPixel: number\n): number {\n return (\n Math.floor((startSample + durationSamples) / samplesPerPixel) -\n Math.floor(startSample / samplesPerPixel)\n );\n}\n","import type { AudioClip, ClipTrack, TrackKind } from './types';\n\n/**\n * What a clip is: MIDI when it carries `midiNotes` (an empty array included),\n * audio otherwise (decoded, or peaks-only before the decode finishes).\n */\nexport function clipKind(clip: Pick<AudioClip, 'midiNotes'>): TrackKind {\n return clip.midiNotes != null ? 'midi' : 'audio';\n}\n\n/**\n * A track's kind. `kind` is required by the type; a track built in plain\n * JavaScript without it is read as audio.\n */\nexport function trackKind(track: Pick<ClipTrack, 'kind'>): TrackKind {\n return track.kind ?? 'audio';\n}\n\nfunction label(named: { id: string; name?: string }): string {\n return '\"' + (named.name || named.id) + '\"';\n}\n\n/**\n * Throws unless every clip on the track is of the track's kind. A track holds\n * audio clips or MIDI clips, never both (#756): the engine calls this wherever\n * a track enters it, so a mixed track cannot reach a playout adapter.\n */\nexport function assertTrackKind(track: ClipTrack): void {\n const kind = trackKind(track);\n if (kind !== 'audio' && kind !== 'midi') {\n throw new Error(\n '[waveform-playlist] Track ' +\n label(track) +\n ' has kind \"' +\n String(kind) +\n \"\\\"; a track's kind is 'audio' or 'midi'.\"\n );\n }\n const stray = track.clips.find((clip) => clipKind(clip) !== kind);\n if (!stray) return;\n\n const strayKind = clipKind(stray);\n const fix =\n track.kind === undefined\n ? \"The track has no kind, which is read as 'audio': set kind: 'midi' on a track of MIDI clips.\"\n : 'A track holds one kind of clip: put the clip on a track of its own kind' +\n ' (splitTrackByKind() splits a track that has both).';\n throw new Error(\n '[waveform-playlist] Track ' +\n label(track) +\n ' is an ' +\n kind +\n ' track but its clip ' +\n label(stray) +\n ' is ' +\n (strayKind === 'audio' ? 'an audio' : 'a midi') +\n ' clip. ' +\n fix\n );\n}\n\n/**\n * Splits a track by the kind of its clips, for data from before tracks had a\n * kind. A track whose clips are all of one kind comes back as one track with\n * that kind (an empty track keeps the kind it has). A track holding both comes\n * back as two: the audio track keeps the id, the MIDI track gets `midiTrackId`\n * (default: the id + '-midi') and copies of the name, volume, pan, mute and solo.\n */\nexport function splitTrackByKind(\n // `kind` optional: data saved before tracks had a kind does not have one.\n track: Omit<ClipTrack, 'kind'> & { kind?: TrackKind },\n midiTrackId: string = track.id + '-midi'\n): ClipTrack[] {\n const audioClips = track.clips.filter((clip) => clipKind(clip) === 'audio');\n const midiClips = track.clips.filter((clip) => clipKind(clip) === 'midi');\n\n if (midiClips.length === 0) {\n return [{ ...track, kind: track.clips.length === 0 ? (track.kind ?? 'audio') : 'audio' }];\n }\n if (audioClips.length === 0) {\n return [{ ...track, kind: 'midi' }];\n }\n return [\n { ...track, kind: 'audio', clips: audioClips },\n { ...track, id: midiTrackId, kind: 'midi', clips: midiClips },\n ];\n}\n","/**\n * Canonical spectrogram canvas-ID contract.\n *\n * Spectrogram canvases are identified by `${clipId}-ch${channelIndex}-chunk${chunkIndex}`.\n * This format is produced (builders) and consumed (parsers) by several packages\n * — the React `SpectrogramProvider`/`SpectrogramChannel`, the `<daw-spectrogram>`\n * Lit element, and the `@dawcore/spectrogram` worker pool. Single-sourcing the\n * build + parse here prevents the drift class where a format change lands in some\n * sites but not others (the pool's no-match fallback then routes every channel to\n * worker 0 → channel 0's data rendered for all channels — #556).\n *\n * `@waveform-playlist/core` is the home because it is zero-dependency and already\n * a dependency of every producer and consumer (unlike `@dawcore/spectrogram`,\n * which `@waveform-playlist/ui-components` does not depend on). The format is a\n * pure string contract with no FFT/compute dependency.\n */\n\n/**\n * What a spectrogram canvas registers with: the canvas handed over to the\n * worker and where it sits. Declared here, once, because the component that\n * registers (`SpectrogramChannel` in ui-components), the context that carries\n * the call (browser) and the provider that receives it (spectrogram) are three\n * packages that all depend on core.\n *\n * The receiver looks the track up from `clipId` and derives the canvas's pixel\n * offset from `chunkIndex`.\n *\n * A canvas registers with the range of the audio it is drawn for: the view\n * may draw a clip with a geometry the tracks do not have yet (a trim being\n * dragged), so the receiver draws `offsetSamples` / `durationSamples` from\n * here and falls back to the clip's own when a registration has none. A canvas\n * is registered once, so a new range means new canvases (`SpectrogramChannel`\n * keys them on it).\n */\nexport interface SpectrogramCanvasRegistration {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n channelIndex: number;\n chunkIndex: number;\n widthPx: number;\n heightPx: number;\n /** Where in the audio the drawn clip starts, in samples. Omitted: the clip's own. */\n offsetSamples?: number;\n /** How much of the audio the drawn clip covers, in samples. Omitted: the clip's own. */\n durationSamples?: number;\n}\n\nexport interface SpectrogramCanvasIdParts {\n clipId: string;\n channelIndex: number;\n chunkIndex: number;\n}\n\n/**\n * Anchored to the trailing `-ch{N}-chunk{M}` segment. The greedy first group lets\n * the clip ID contain hyphens — and even a `-ch{N}-chunk{M}`-looking substring —\n * without misrouting: it always binds to the LAST such segment.\n */\nconst CANVAS_ID_RE = /^(.+)-ch(\\d+)-chunk(\\d+)$/;\n\n/** Build a spectrogram canvas ID from its parts. */\nexport function buildSpectrogramCanvasId(parts: SpectrogramCanvasIdParts): string {\n return `${parts.clipId}-ch${parts.channelIndex}-chunk${parts.chunkIndex}`;\n}\n\n/**\n * Parse a spectrogram canvas ID into its parts, or `null` when it doesn't match\n * the `${clipId}-ch${channelIndex}-chunk${chunkIndex}` format.\n */\nexport function parseSpectrogramCanvasId(canvasId: string): SpectrogramCanvasIdParts | null {\n const match = canvasId.match(CANVAS_ID_RE);\n if (!match) return null;\n return {\n clipId: match[1],\n channelIndex: parseInt(match[2], 10),\n chunkIndex: parseInt(match[3], 10),\n };\n}\n","/**\n * Fade curve utilities for Web Audio API\n *\n * Pure functions that generate fade curves and apply them to AudioParam.\n * No Tone.js dependency — works with native Web Audio nodes.\n */\n\nimport type { FadeType } from './types';\n\n/**\n * Generate a linear fade curve\n */\nexport function linearCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const scale = length - 1;\n\n for (let i = 0; i < length; i++) {\n const x = i / scale;\n curve[i] = fadeIn ? x : 1 - x;\n }\n\n return curve;\n}\n\n/**\n * Generate an exponential fade curve\n */\nexport function exponentialCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const scale = length - 1;\n\n for (let i = 0; i < length; i++) {\n const x = i / scale;\n const index = fadeIn ? i : length - 1 - i;\n curve[index] = Math.exp(2 * x - 1) / Math.E;\n }\n\n return curve;\n}\n\n/**\n * Generate an S-curve (sine-based smooth curve)\n */\nexport function sCurveCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const phase = fadeIn ? Math.PI / 2 : -Math.PI / 2;\n\n for (let i = 0; i < length; i++) {\n curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;\n }\n\n return curve;\n}\n\n/**\n * Generate a logarithmic fade curve\n */\nexport function logarithmicCurve(length: number, fadeIn: boolean, base: number = 10): Float32Array {\n const curve = new Float32Array(length);\n\n for (let i = 0; i < length; i++) {\n const index = fadeIn ? i : length - 1 - i;\n const x = i / length;\n curve[index] = Math.log(1 + base * x) / Math.log(1 + base);\n }\n\n return curve;\n}\n\n/**\n * Generate a fade curve of the specified type\n */\nexport function generateCurve(type: FadeType, length: number, fadeIn: boolean): Float32Array {\n switch (type) {\n case 'linear':\n return linearCurve(length, fadeIn);\n case 'exponential':\n return exponentialCurve(length, fadeIn);\n case 'sCurve':\n return sCurveCurve(length, fadeIn);\n case 'logarithmic':\n return logarithmicCurve(length, fadeIn);\n default:\n return linearCurve(length, fadeIn);\n }\n}\n\n/**\n * Apply a fade in to an AudioParam\n *\n * @param param - The AudioParam to apply the fade to (usually gain)\n * @param startTime - When the fade starts (in seconds, AudioContext time)\n * @param duration - Duration of the fade in seconds\n * @param type - Type of fade curve\n * @param startValue - Starting value (default: 0)\n * @param endValue - Ending value (default: 1)\n */\nexport function applyFadeIn(\n param: AudioParam,\n startTime: number,\n duration: number,\n type: FadeType = 'linear',\n startValue: number = 0,\n endValue: number = 1\n): void {\n if (duration <= 0) return;\n\n if (type === 'linear') {\n param.setValueAtTime(startValue, startTime);\n param.linearRampToValueAtTime(endValue, startTime + duration);\n } else if (type === 'exponential') {\n param.setValueAtTime(Math.max(startValue, 0.001), startTime);\n param.exponentialRampToValueAtTime(Math.max(endValue, 0.001), startTime + duration);\n } else {\n const curve = generateCurve(type, 10000, true);\n const scaledCurve = new Float32Array(curve.length);\n const range = endValue - startValue;\n for (let i = 0; i < curve.length; i++) {\n scaledCurve[i] = startValue + curve[i] * range;\n }\n param.setValueCurveAtTime(scaledCurve, startTime, duration);\n }\n}\n\n/**\n * Apply a fade out to an AudioParam\n *\n * @param param - The AudioParam to apply the fade to (usually gain)\n * @param startTime - When the fade starts (in seconds, AudioContext time)\n * @param duration - Duration of the fade in seconds\n * @param type - Type of fade curve\n * @param startValue - Starting value (default: 1)\n * @param endValue - Ending value (default: 0)\n */\nexport function applyFadeOut(\n param: AudioParam,\n startTime: number,\n duration: number,\n type: FadeType = 'linear',\n startValue: number = 1,\n endValue: number = 0\n): void {\n if (duration <= 0) return;\n\n if (type === 'linear') {\n param.setValueAtTime(startValue, startTime);\n param.linearRampToValueAtTime(endValue, startTime + duration);\n } else if (type === 'exponential') {\n param.setValueAtTime(Math.max(startValue, 0.001), startTime);\n param.exponentialRampToValueAtTime(Math.max(endValue, 0.001), startTime + duration);\n } else {\n const curve = generateCurve(type, 10000, false);\n const scaledCurve = new Float32Array(curve.length);\n const range = startValue - endValue;\n for (let i = 0; i < curve.length; i++) {\n scaledCurve[i] = endValue + curve[i] * range;\n }\n param.setValueCurveAtTime(scaledCurve, startTime, duration);\n }\n}\n","/**\n * Framework-agnostic keyboard shortcut handling.\n * Used by both React (useKeyboardShortcuts) and Web Components (daw-editor).\n */\n\nexport interface KeyboardShortcut {\n key: string;\n ctrlKey?: boolean;\n shiftKey?: boolean;\n metaKey?: boolean;\n altKey?: boolean;\n action: () => void;\n description?: string;\n preventDefault?: boolean;\n}\n\n/** A key + modifier combination, without an action. Used for remapping maps. */\nexport type KeyBinding = Pick<\n KeyboardShortcut,\n 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'\n>;\n\n/**\n * Does a keyboard event match a key binding?\n * `undefined` modifier = match any state; `false` = must NOT be pressed.\n */\nexport function matchesKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean {\n const keyMatch =\n event.key.toLowerCase() === binding.key.toLowerCase() || event.key === binding.key;\n const ctrlMatch = binding.ctrlKey === undefined || event.ctrlKey === binding.ctrlKey;\n const shiftMatch = binding.shiftKey === undefined || event.shiftKey === binding.shiftKey;\n const metaMatch = binding.metaKey === undefined || event.metaKey === binding.metaKey;\n const altMatch = binding.altKey === undefined || event.altKey === binding.altKey;\n return keyMatch && ctrlMatch && shiftMatch && metaMatch && altMatch;\n}\n\nconst ELEMENT_NODE = 1;\n\n/**\n * The elements the event passed through, innermost first. `event.target` is\n * retargeted to the shadow host for a listener outside a shadow root, so the\n * composed path is the only way to see a control inside a web component.\n */\nfunction elementPath(event: KeyboardEvent): Element[] {\n const composed = typeof event.composedPath === 'function' ? event.composedPath() : [];\n if (composed.length > 0) {\n return composed.filter(\n (node): node is Element => (node as Node | null)?.nodeType === ELEMENT_NODE\n );\n }\n // Not dispatched (or no composedPath): walk up from the target.\n const path: Element[] = [];\n let current = event.target as Element | null;\n while (current && current.nodeType === ELEMENT_NODE) {\n path.push(current);\n current = current.parentElement;\n }\n return path;\n}\n\n/** `element.matches(selector)`, or `fallback` where the selector is not supported. */\nfunction matchesOr(element: Element, selector: string, fallback: boolean): boolean {\n try {\n return element.matches(selector);\n } catch {\n return fallback;\n }\n}\n\n/**\n * Controls that take text or use many keys themselves (every `<input>` type,\n * including sliders and checkboxes): no shortcut fires on them.\n */\nfunction ownsAllKeys(element: Element): boolean {\n const tag = element.tagName;\n return (\n tag === 'INPUT' ||\n tag === 'TEXTAREA' ||\n tag === 'SELECT' ||\n (element as HTMLElement).isContentEditable === true\n );\n}\n\n/**\n * Does `key` activate this native control? Buttons and `<summary>` take Space\n * and Enter; a link takes Enter only (Space on a link scrolls the page, so\n * yielding it would lose the shortcut for nothing). A disabled button takes\n * neither.\n *\n * ARIA-role widgets (`role=\"button\"` on a div) are left out on purpose: whether\n * they respond to a key is up to their own script, and yielding to one that\n * does not (a drag handle that is only draggable with a pointer) would just\n * make the key dead.\n */\nfunction activates(element: Element, key: string): boolean {\n if (key !== ' ' && key !== 'Enter') return false;\n const tag = element.tagName;\n if (tag === 'BUTTON') return (element as HTMLButtonElement).disabled !== true;\n if (tag === 'SUMMARY') return true;\n return key === 'Enter' && (tag === 'A' || tag === 'AREA') && element.hasAttribute('href');\n}\n\n/**\n * Is this container actually showing? A closed custom dialog is often left in\n * the page: `hidden`, `aria-hidden`, `display: none`, or (animated ones)\n * `visibility: hidden` / `opacity: 0`. Unknown (no `checkVisibility`, as in\n * test DOMs) counts as showing.\n */\nfunction isRendered(element: Element): boolean {\n if (element.hasAttribute('hidden')) return false;\n if (element.getAttribute('aria-hidden') === 'true') return false;\n const check = (\n element as Element & {\n checkVisibility?: (options?: {\n visibilityProperty?: boolean;\n opacityProperty?: boolean;\n }) => boolean;\n }\n ).checkVisibility;\n if (typeof check !== 'function') return true;\n try {\n return check.call(element, { visibilityProperty: true, opacityProperty: true });\n } catch {\n return true;\n }\n}\n\n/** An open modal `<dialog>` or a visible `aria-modal` container: Escape closes it. */\nfunction isOpenModal(element: Element): boolean {\n if (element.getAttribute('aria-modal') === 'true') {\n // A closed custom dialog is often left in the page, hidden, with the\n // attribute still on it. That must not swallow Escape for good.\n return isRendered(element);\n }\n return (\n element.tagName === 'DIALOG' &&\n element.hasAttribute('open') &&\n matchesOr(element, ':modal', true)\n );\n}\n\n/**\n * A modal dialog is open in `doc`. Focus is not always inside it: clicking the\n * dialog's own padding can leave focus on `<body>`, and Escape still closes\n * the dialog from there. A modal inside a shadow root is only seen while focus\n * is inside it (the composed path), since this query does not pierce shadow DOM.\n */\nfunction documentHasOpenModal(doc: Document | null | undefined): boolean {\n if (!doc) return false;\n try {\n return Array.from(doc.querySelectorAll('dialog[open], [aria-modal=\"true\"]')).some(isOpenModal);\n } catch {\n return false;\n }\n}\n\n/**\n * True when the key already means something to the control that has focus, so\n * a global shortcut must leave it alone:\n *\n * - `<input>` (every type), `<textarea>`, `<select>` and contenteditable keep\n * every key;\n * - Escape belongs to an open modal dialog, wherever focus is;\n * - Space and Enter belong to a focused `<button>` or `<summary>`, and Enter to\n * a focused link.\n *\n * It makes no difference how the control got focus. A button the user clicked\n * still has focus, so Space activates it again, exactly as it does on any\n * other page; a shortcut only gets the key once focus is somewhere else.\n *\n * `handleKeyboardEvent` applies this itself. It is exported for listeners that\n * match keys on their own.\n */\nexport function keyBelongsToFocusedControl(event: KeyboardEvent): boolean {\n const path = elementPath(event);\n const focused = path[0];\n\n if (event.key === 'Escape') {\n // Also when the event has no element target (dispatched on the document).\n const doc = focused?.ownerDocument ?? (typeof document !== 'undefined' ? document : null);\n if (path.some(isOpenModal) || documentHasOpenModal(doc)) return true;\n }\n if (!focused) return false;\n if (ownsAllKeys(focused)) return true;\n return activates(focused, event.key);\n}\n\n/**\n * Events whose default a shortcut prevented (here, in `handleKeyboardEvent`).\n * An Escape prevented by anything else (dnd-kit's pointer sensor and\n * `<daw-editor>` prevent it when they cancel a drag) is not a shortcut; one a\n * shortcut list prevented still reaches the next list (#848, review of #915).\n */\nconst preventedByShortcut = new WeakSet<Event>();\n\n/**\n * Handle a keyboard event against a list of shortcuts.\n * Pure function, no framework dependency.\n *\n * Shortcuts do not fire for a key the focused control uses itself; see\n * `keyBelongsToFocusedControl`. Nor for an Escape whose default something\n * other than a shortcut already prevented (a drag cancelled it): an Escape that\n * cancelled a drag does nothing else.\n */\nexport function handleKeyboardEvent(\n event: KeyboardEvent,\n shortcuts: KeyboardShortcut[],\n enabled: boolean\n): void {\n if (!enabled) return;\n\n // Ignore key repeat events — holding a key fires keydown repeatedly.\n // Without this guard, holding Space rapidly toggles play/pause.\n if (event.repeat) return;\n\n // A drag that took the key (dnd-kit's pointer sensor, <daw-editor>'s drag\n // cancel) has already prevented its default: an Escape that cancelled a\n // drag does nothing else (#848). Another shortcut list's own prevention\n // does not count: two lists that both bind Escape both run.\n if (event.key === 'Escape' && event.defaultPrevented && !preventedByShortcut.has(event)) return;\n\n if (keyBelongsToFocusedControl(event)) return;\n\n const matchingShortcut = shortcuts.find((shortcut) => matchesKeyBinding(event, shortcut));\n\n if (matchingShortcut) {\n if (matchingShortcut.preventDefault !== false) {\n event.preventDefault();\n preventedByShortcut.add(event);\n }\n matchingShortcut.action();\n }\n}\n","export type RangeSupport = 'supported' | 'unsupported' | 'unknown';\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Probe whether an audio host honors HTTP range requests, so an on-demand\n * player can decide its seeking policy. Range *detection* lives here; range\n * *policy* (disable the scrubber, surface an error, play from start) stays with\n * the consuming component — the detection is generic, the UX is per-component.\n *\n * Sends `GET` with `Range: bytes=0-1` and reads only the status line, aborting\n * the body immediately: on a non-range host the `200` carries the entire\n * (possibly hours-long) file, which must never be downloaded just to detect the\n * failure.\n *\n * - `206` → `'supported'`\n * - `200` (host ignored Range, returned full body) → `'unsupported'`\n * - any throw (network error / CORS-opaque cross-origin) or other status → `'unknown'`\n *\n * **Positive-failure only:** only an observed `200` asserts a failure. A\n * CORS-opaque probe is `'unknown'`, NOT a failure — native `<audio>` seeking\n * works cross-origin *without* CORS, so seeking should stay enabled. A naive\n * \"no 206 ⇒ failure\" would false-positive on every CORS-opaque host.\n *\n * @param url The audio URL to probe.\n * @param fetchImpl Injectable fetch (defaults to the global `fetch`) — pass a\n * stub in tests so no real network is hit, and pass an explicit\n * implementation on runtimes without a global `fetch`.\n */\nexport async function probeRangeSupport(\n url: string,\n fetchImpl: FetchLike = fetch\n): Promise<RangeSupport> {\n const controller = new AbortController();\n try {\n const res = await fetchImpl(url, {\n method: 'GET',\n headers: { Range: 'bytes=0-1' },\n // Bypass the HTTP cache: RFC 7234 lets a UA satisfy a range request from a\n // cached full 200, which would falsely read as the server ignoring Range.\n cache: 'no-store',\n signal: controller.signal,\n });\n if (res.status === 206) return 'supported';\n if (res.status === 200) return 'unsupported';\n return 'unknown';\n } catch {\n return 'unknown';\n } finally {\n // Never consume the body — abort the moment we have the status line.\n controller.abort();\n }\n}\n","/**\n * Framework-agnostic microphone enumeration.\n *\n * Works without requesting a stream, but browsers redact device information\n * until microphone permission is granted: labels are empty everywhere, and\n * Chrome/Safari typically also redact deviceIds (often exposing a single\n * placeholder entry). The `hasLabels` flag tells consumers whether the list\n * is a usable picker or just a \"microphones exist\" signal — re-enumerate\n * after a successful getUserMedia to get the real list.\n *\n * Follows the probeRangeSupport pattern: the browser API is injectable for\n * tests and non-browser environments degrade gracefully.\n */\n\nexport interface MicrophoneDeviceInfo {\n deviceId: string;\n /** Real device label, or a generated fallback name when redacted. */\n label: string;\n groupId: string;\n}\n\nexport interface MicrophoneEnumeration {\n /** False when enumeration is unavailable — SSR/Node, insecure context\n * (mediaDevices requires HTTPS or localhost), or a very old browser. */\n supported: boolean;\n /** True when the browser exposed real device labels. False before\n * microphone permission is granted (labels — and often deviceIds — are\n * redacted); the `devices` labels are then generated fallbacks. */\n hasLabels: boolean;\n devices: MicrophoneDeviceInfo[];\n}\n\nconst UNSUPPORTED: MicrophoneEnumeration = Object.freeze({\n supported: false,\n hasLabels: false,\n devices: [],\n});\n\nfunction resolveMediaDevices(mediaDevices?: MediaDevices): MediaDevices | undefined {\n if (mediaDevices) return mediaDevices;\n return typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;\n}\n\n/**\n * List audio input devices without requesting a stream.\n *\n * @param mediaDevices - Injectable for tests; defaults to `navigator.mediaDevices`.\n */\nexport async function enumerateMicrophones(\n mediaDevices?: MediaDevices\n): Promise<MicrophoneEnumeration> {\n const md = resolveMediaDevices(mediaDevices);\n if (!md || typeof md.enumerateDevices !== 'function') {\n return UNSUPPORTED;\n }\n\n const all = await md.enumerateDevices();\n const inputs = all.filter((device) => device.kind === 'audioinput');\n const hasLabels = inputs.some((device) => device.label.length > 0);\n\n return {\n supported: true,\n hasLabels,\n devices: inputs.map((device, index) => ({\n deviceId: device.deviceId,\n label:\n device.label ||\n // Pre-permission fallbacks: Chrome redacts deviceId to '' as well,\n // so fall through to a positional name when there's nothing to slice.\n (device.deviceId ? `Microphone ${device.deviceId.slice(0, 8)}` : `Microphone ${index + 1}`),\n groupId: device.groupId,\n })),\n };\n}\n\n/**\n * Subscribe to the microphone device list: the listener fires once with the\n * initial enumeration and again on every `devicechange` (hot-plug, permission\n * grant in some browsers). Returns an unsubscribe function.\n *\n * Enumeration failures are logged and skipped — the subscription survives a\n * transient failure and delivers the next successful enumeration.\n *\n * @param mediaDevices - Injectable for tests; defaults to `navigator.mediaDevices`.\n */\nexport function watchMicrophoneDevices(\n listener: (enumeration: MicrophoneEnumeration) => void,\n mediaDevices?: MediaDevices\n): () => void {\n const md = resolveMediaDevices(mediaDevices);\n if (!md || typeof md.enumerateDevices !== 'function') {\n // Deliver asynchronously so subscribe-then-unsubscribe never re-enters\n // the caller synchronously.\n queueMicrotask(() => listener(UNSUPPORTED));\n return () => {};\n }\n\n let active = true;\n\n const deliver = () => {\n enumerateMicrophones(md)\n .then((result) => {\n if (active) listener(result);\n })\n .catch((err) => {\n console.warn('[waveform-playlist] Microphone enumeration failed:', String(err));\n });\n };\n\n md.addEventListener('devicechange', deliver);\n deliver();\n\n return () => {\n active = false;\n md.removeEventListener('devicechange', deliver);\n };\n}\n","import type { AnnotationData } from '../types/annotations';\n\n/** Edges within this distance (seconds) are considered \"linked\". */\nexport const LINK_THRESHOLD = 0.01;\n\n/** Minimum annotation duration (seconds) enforced by boundary edits. */\nexport const MIN_ANNOTATION_DURATION = 0.1;\n\n/** Link threshold for INTEGER TICK positions — closer than half a tick means equal. */\nexport const ANNOTATION_LINK_THRESHOLD_TICKS = 0.5;\n\n/** Minimum tick-annotation duration: a 128th note, floored at 1 tick. */\nexport function annotationMinDurationTicks(ppqn: number): number {\n return Math.max(1, Math.round(ppqn / 32));\n}\n\n/** Unit constants for a boundary-math run. Defaults are the seconds-domain values. */\nexport interface AnnotationBoundaryOptions {\n linkThreshold?: number;\n minDuration?: number;\n}\n\nexport interface AnnotationBoundaryUpdate {\n annotationIndex: number;\n newTime: number;\n isDraggingStart: boolean;\n annotations: readonly AnnotationData[];\n duration: number;\n linkEndpoints: boolean;\n}\n\n/**\n * Pure boundary-update logic shared by the React annotations package and the\n * dawcore annotation web components. Handles linked endpoints (moving one edge\n * drags the linked neighbor edge, with cascade) and collision push-back.\n * Returns a NEW array; never mutates inputs.\n */\nexport function updateAnnotationBoundaries(\n params: AnnotationBoundaryUpdate,\n options: AnnotationBoundaryOptions = {}\n): AnnotationData[] {\n const { annotationIndex, newTime, isDraggingStart, annotations, duration, linkEndpoints } =\n params;\n const linkThreshold = options.linkThreshold ?? LINK_THRESHOLD;\n const minDuration = options.minDuration ?? MIN_ANNOTATION_DURATION;\n\n const updatedAnnotations = [...annotations];\n const annotation = annotations[annotationIndex];\n\n if (isDraggingStart) {\n const constrainedStart = Math.min(annotation.end - minDuration, Math.max(0, newTime));\n\n updatedAnnotations[annotationIndex] = { ...annotation, start: constrainedStart };\n\n if (linkEndpoints && annotationIndex > 0) {\n const prevAnnotation = updatedAnnotations[annotationIndex - 1];\n if (Math.abs(prevAnnotation.end - annotation.start) < linkThreshold) {\n // Linked edges share one position. Setting the neighbour's edge to the\n // dragged edge (not moving it by the same amount) closes a gap smaller\n // than the threshold instead of carrying it along for the whole drag.\n updatedAnnotations[annotationIndex - 1] = {\n ...prevAnnotation,\n end: Math.max(prevAnnotation.start + minDuration, constrainedStart),\n };\n } else if (constrainedStart <= prevAnnotation.end) {\n updatedAnnotations[annotationIndex] = {\n ...updatedAnnotations[annotationIndex],\n start: prevAnnotation.end,\n };\n }\n } else if (\n !linkEndpoints &&\n annotationIndex > 0 &&\n constrainedStart < updatedAnnotations[annotationIndex - 1].end\n ) {\n updatedAnnotations[annotationIndex - 1] = {\n ...updatedAnnotations[annotationIndex - 1],\n end: constrainedStart,\n };\n }\n } else {\n const constrainedEnd = Math.max(annotation.start + minDuration, Math.min(newTime, duration));\n\n updatedAnnotations[annotationIndex] = { ...annotation, end: constrainedEnd };\n\n if (linkEndpoints && annotationIndex < updatedAnnotations.length - 1) {\n const nextAnnotation = updatedAnnotations[annotationIndex + 1];\n if (Math.abs(nextAnnotation.start - annotation.end) < linkThreshold) {\n // As above: the linked edge takes the dragged edge's position.\n updatedAnnotations[annotationIndex + 1] = {\n ...nextAnnotation,\n start: Math.min(nextAnnotation.end - minDuration, constrainedEnd),\n };\n\n let currentIndex = annotationIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n if (Math.abs(next.start - current.end) < linkThreshold) {\n const nextDelta = current.end - annotations[currentIndex].end;\n updatedAnnotations[currentIndex + 1] = {\n ...next,\n start: Math.min(next.end - minDuration, next.start + nextDelta),\n };\n currentIndex++;\n } else {\n break;\n }\n }\n } else if (constrainedEnd >= nextAnnotation.start) {\n updatedAnnotations[annotationIndex] = {\n ...updatedAnnotations[annotationIndex],\n end: nextAnnotation.start,\n };\n }\n } else if (\n !linkEndpoints &&\n annotationIndex < updatedAnnotations.length - 1 &&\n constrainedEnd > updatedAnnotations[annotationIndex + 1].start\n ) {\n const nextAnnotation = updatedAnnotations[annotationIndex + 1];\n updatedAnnotations[annotationIndex + 1] = { ...nextAnnotation, start: constrainedEnd };\n\n let currentIndex = annotationIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n if (current.end > next.start) {\n updatedAnnotations[currentIndex + 1] = { ...next, start: current.end };\n currentIndex++;\n } else {\n break;\n }\n }\n }\n }\n\n return updatedAnnotations;\n}\n","import type { KeyBinding } from '../keyboard';\n\nexport type AnnotationShortcutAction =\n | 'selectPrevious'\n | 'selectNext'\n | 'selectFirst'\n | 'selectLast'\n | 'clearSelection'\n | 'moveStartEarlier'\n | 'moveStartLater'\n | 'moveEndEarlier'\n | 'moveEndLater'\n | 'playActive';\n\n/** Key remapping map — null on the consumer means \"use defaults\". */\nexport interface AnnotationShortcutMap {\n selectPrevious?: KeyBinding;\n selectNext?: KeyBinding;\n selectFirst?: KeyBinding;\n selectLast?: KeyBinding;\n clearSelection?: KeyBinding;\n moveStartEarlier?: KeyBinding;\n moveStartLater?: KeyBinding;\n moveEndEarlier?: KeyBinding;\n moveEndLater?: KeyBinding;\n playActive?: KeyBinding;\n}\n\n// Explicit ctrlKey/metaKey: false so browser combos (Cmd+ArrowLeft = history\n// back, Cmd+[ = back, etc.) never trigger annotation actions — same convention\n// as <daw-keyboard-shortcuts> presets.\nconst noMods = { ctrlKey: false as const, metaKey: false as const };\n\nexport const DEFAULT_ANNOTATION_SHORTCUTS: Record<AnnotationShortcutAction, KeyBinding[]> = {\n selectPrevious: [\n { key: 'ArrowUp', ...noMods },\n { key: 'ArrowLeft', ...noMods },\n ],\n selectNext: [\n { key: 'ArrowDown', ...noMods },\n { key: 'ArrowRight', ...noMods },\n ],\n selectFirst: [{ key: 'Home', ...noMods }],\n selectLast: [{ key: 'End', ...noMods }],\n clearSelection: [{ key: 'Escape', ...noMods }],\n moveStartEarlier: [{ key: '[', ...noMods }],\n moveStartLater: [{ key: ']', ...noMods }],\n // '{' / '}' are what event.key reports for Shift+[ / Shift+] — no explicit\n // shiftKey needed; the key value itself encodes it.\n moveEndEarlier: [{ key: '{', ...noMods }],\n moveEndLater: [{ key: '}', ...noMods }],\n playActive: [{ key: 'Enter', ...noMods }],\n};\n\nconst ALL_ACTIONS = Object.keys(DEFAULT_ANNOTATION_SHORTCUTS) as AnnotationShortcutAction[];\n\n/**\n * Flatten defaults + remap into a matchable list. A remapped action replaces\n * ALL of its default bindings with the single provided binding.\n */\nexport function resolveAnnotationShortcuts(\n remap: AnnotationShortcutMap | null\n): Array<{ action: AnnotationShortcutAction; binding: KeyBinding }> {\n return ALL_ACTIONS.flatMap((action) => {\n const override = remap?.[action];\n const bindings = override ? [override] : DEFAULT_ANNOTATION_SHORTCUTS[action];\n return bindings.map((binding) => ({ action, binding }));\n });\n}\n","/**\n * Outside production builds, freeze what the annotation store hands out. The\n * same objects are shared by the store, every reader and every later list\n * built from them, so a write by a consumer would change all of them; frozen,\n * the write throws where it is made (in a module, which is strict code).\n *\n * Frozen: the array, each annotation and its `lines` array.\n *\n * Not exported from the package: core's index re-exports `store.ts` and\n * `bounds.ts` only.\n */\n\nimport type { AnnotationData } from '../types';\n\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/**\n * True unless this is a production build. Bundlers replace\n * `process.env.NODE_ENV` with a literal; where there is no `process` at all\n * (a page that loads the module without a bundler) this is false.\n */\nexport function isDevelopmentBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Freeze `list`, each annotation and its `lines` in development; return `list`. */\nexport function freezeAnnotations(list: readonly AnnotationData[]): readonly AnnotationData[] {\n if (!isDevelopmentBuild()) return list;\n for (const annotation of list) {\n if (Array.isArray(annotation.lines)) Object.freeze(annotation.lines);\n Object.freeze(annotation);\n }\n return Object.freeze(list);\n}\n","import type { AnnotationData } from '../types';\nimport { freezeAnnotations } from './devFreeze';\n\n/**\n * The owner of a list of annotations. The app makes one and gives it to a\n * provider; everything that reads the annotations reads them here, and every\n * change is a call to `set` or `update`.\n */\nexport interface AnnotationStore {\n /**\n * The current annotations. The same array until a change. Never write to\n * it: outside production builds it is frozen.\n */\n getAnnotations(): readonly AnnotationData[];\n /** Be told after every change. Returns the function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /** Replace the annotations. */\n set(annotations: readonly AnnotationData[]): void;\n /**\n * Change the annotations: `fn` gets the current array and returns the next.\n * The change is applied before `update` returns, so the next call's\n * `current` already holds it. Returning `current` changes nothing.\n */\n update(fn: (current: readonly AnnotationData[]) => readonly AnnotationData[]): void;\n}\n\nexport interface AnnotationStoreOptions {\n /**\n * The app's rule for every change. Gets the proposed list and the current\n * one, returns the list to store: `next` to accept, `current` to refuse,\n * or another list to adjust (e.g. clamp an edge so it does not overlap).\n * Not called for the initial list. A throw from it reaches the caller of\n * `set` or `update`, and the store keeps its value.\n */\n beforeChange?: (\n next: readonly AnnotationData[],\n current: readonly AnnotationData[]\n ) => readonly AnnotationData[];\n}\n\nfunction invalid(message: string): TypeError {\n return new TypeError('[waveform-playlist] Invalid annotations: ' + message);\n}\n\n/** Every annotation has numeric `start` and `end`, and the ids are unique. */\nfunction validateAnnotations(list: readonly AnnotationData[]): void {\n if (!Array.isArray(list)) throw invalid('expected an array.');\n const seen = new Set<string>();\n for (const annotation of list) {\n const { id, start, end } = annotation ?? ({} as AnnotationData);\n if (!Number.isFinite(start) || !Number.isFinite(end)) {\n throw invalid(\n `annotation \"${String(id)}\" needs numeric start and end (got ${typeof start} and ${typeof end}). ` +\n 'Parse text formats first, e.g. parseAeneas() from @waveform-playlist/annotations.'\n );\n }\n if (seen.has(id)) throw invalid(`two annotations have the id \"${id}\".`);\n seen.add(id);\n }\n}\n\n/**\n * Make an annotation store holding `initial` (empty when absent). Throws a\n * `TypeError` for an invalid list: an annotation without numeric `start` and\n * `end`, or two with one id.\n */\nexport function createAnnotationStore(\n initial: readonly AnnotationData[] = [],\n options: AnnotationStoreOptions = {}\n): AnnotationStore {\n validateAnnotations(initial);\n let annotations = freezeAnnotations(initial);\n const listeners = new Set<{ listener: () => void }>();\n const { beforeChange } = options;\n\n const commit = (proposed: readonly AnnotationData[]) => {\n if (proposed === annotations) return;\n validateAnnotations(proposed);\n let next = proposed;\n if (beforeChange) {\n next = beforeChange(proposed, annotations);\n if (next === annotations) return;\n if (next !== proposed) validateAnnotations(next);\n }\n annotations = freezeAnnotations(next);\n for (const entry of [...listeners]) {\n if (!listeners.has(entry)) continue;\n try {\n entry.listener();\n } catch (error) {\n console.warn('[waveform-playlist] Error in an annotation store subscriber:', error);\n }\n }\n };\n\n return {\n getAnnotations: () => annotations,\n subscribe(listener) {\n // Each call gets its own entry, so one function subscribed twice is told twice.\n const entry = { listener };\n listeners.add(entry);\n return () => {\n listeners.delete(entry);\n };\n },\n set(next) {\n commit(next);\n },\n update(fn) {\n commit(fn(annotations));\n },\n };\n}\n","import type { AnnotationData } from '../types';\n\n/** New bounds for the annotation with `id`. */\nexport interface AnnotationBoundsChange {\n id: string;\n start: number;\n end: number;\n}\n\n/**\n * Write `start` and `end` of each change onto the annotation with that id in\n * `current`. Every other field, and every annotation no change names, is kept\n * as it is (the same object). An id that is not in `current` is skipped.\n *\n * Returns `current` itself when nothing changes, so an `update` with it\n * notifies nobody.\n */\nexport function applyAnnotationBounds(\n current: readonly AnnotationData[],\n changes: readonly AnnotationBoundsChange[]\n): readonly AnnotationData[] {\n if (changes.length === 0) return current;\n const byId = new Map(changes.map((change) => [change.id, change]));\n let changed = false;\n const next = current.map((annotation) => {\n const change = byId.get(annotation.id);\n if (!change || (change.start === annotation.start && change.end === annotation.end)) {\n return annotation;\n }\n changed = true;\n return { ...annotation, start: change.start, end: change.end };\n });\n return changed ? next : current;\n}\n","const PREFIX = '[waveform-playlist] ';\n\n/** Gains of the pan matrix: `out = [[ll, rl], [lr, rr]] · in`, where e.g.\n * `rl` is how much of the input's RIGHT channel reaches the LEFT output. */\nexport interface PanMatrix {\n ll: number;\n lr: number;\n rl: number;\n rr: number;\n}\n\n/**\n * The pan law for a track, chosen by the channel count of its SOURCE\n * material — exactly the two algorithms of the Web Audio `StereoPannerNode`.\n *\n * - Mono source — equal-power pan, θ = (pan + 1)·π/4: L × cos θ, R × sin θ.\n * For a mono signal (taken as L = R) that is the mono law, L = m·cos θ and\n * R = m·sin θ: −3 dB per side at centre. A stereo signal from the track's\n * effects is balanced by the same gains, so it stays stereo at the same\n * centre level as the dry signal.\n * - Stereo source — the stereo law: centre passes both channels at unity;\n * panning left folds the right channel into the left\n * (L + R·cos x, R·sin x with x = (pan + 1)·π/2), and symmetrically right.\n *\n * `pan` is clamped to −1 … 1; a non-finite value is treated as centre.\n */\nexport function panMatrix(pan: number, sourceChannelCount: number): PanMatrix {\n const p = Number.isFinite(pan) ? Math.max(-1, Math.min(1, pan)) : 0;\n if (sourceChannelCount < 2) {\n const theta = ((p + 1) * Math.PI) / 4;\n return { ll: Math.cos(theta), lr: 0, rl: 0, rr: Math.sin(theta) };\n }\n if (p <= 0) {\n const x = ((p + 1) * Math.PI) / 2;\n return { ll: 1, lr: 0, rl: Math.cos(x), rr: Math.sin(x) };\n }\n const x = (p * Math.PI) / 2;\n return { ll: Math.cos(x), lr: Math.sin(x), rl: 0, rr: 1 };\n}\n\n/**\n * The part of an audio context the pan stage needs. Any `AudioContext` or\n * `OfflineAudioContext` satisfies it, and so does the `rawContext` behind\n * Tone.js (native or standardized-audio-context).\n */\nexport type PanStageContext = Pick<\n BaseAudioContext,\n 'createGain' | 'createChannelSplitter' | 'createChannelMerger'\n>;\n\n/** A track's pan stage: `input → … → output`, with `setPan(-1 … 1)`. */\nexport interface PanStage {\n readonly input: AudioNode;\n readonly output: AudioNode;\n setPan(pan: number): void;\n /** Switch the pan law (1 = mono law, 2+ = stereo law), keeping the pan. */\n setSourceChannelCount(sourceChannelCount: number): void;\n /** Disconnect every node of the stage. */\n dispose(): void;\n}\n\n/**\n * Build the pan stage for a track whose source material has\n * `sourceChannelCount` channels (1 for mono clips and synth voices).\n *\n * Why this is not a `StereoPannerNode`: a track's pan stage is fed by its\n * effects chain (pre-fader inserts), whose channel layout is not the\n * source's. A `StereoPannerNode` picks its law from the layout it RECEIVES,\n * so a stereo effect on a mono track would jump ~3 dB at centre. And under\n * standardized-audio-context (Tone.js's default context) a panner's channel\n * mode cannot be changed at all (its bug #105), which pins a mono track's\n * panner to one channel.\n *\n * This stage is a 2×2 gain matrix built from plain gain, splitter and merger\n * nodes — none of which is restricted — so it behaves identically on every\n * context, always passes stereo through, and takes its law from the caller.\n */\nexport function createPanStage(\n context: PanStageContext,\n pan: number,\n sourceChannelCount: number\n): PanStage {\n // Take the incoming signal as stereo regardless of its layout: with an\n // explicit count of 2 (speakers interpretation) mono is upmixed to L = R\n // and stereo passes through unchanged.\n const upmix = context.createGain();\n upmix.channelCount = 2;\n upmix.channelCountMode = 'explicit';\n upmix.channelInterpretation = 'speakers';\n const split = context.createChannelSplitter(2);\n const merge = context.createChannelMerger(2);\n const ll = context.createGain();\n const lr = context.createGain();\n const rl = context.createGain();\n const rr = context.createGain();\n\n let currentPan = pan;\n let currentChannelCount = sourceChannelCount;\n const apply = (): void => {\n const matrix = panMatrix(currentPan, currentChannelCount);\n ll.gain.value = matrix.ll;\n lr.gain.value = matrix.lr;\n rl.gain.value = matrix.rl;\n rr.gain.value = matrix.rr;\n };\n apply();\n\n upmix.connect(split);\n split.connect(ll, 0, 0);\n split.connect(lr, 0, 0);\n split.connect(rl, 1, 0);\n split.connect(rr, 1, 0);\n ll.connect(merge, 0, 0);\n rl.connect(merge, 0, 0);\n lr.connect(merge, 0, 1);\n rr.connect(merge, 0, 1);\n\n return {\n input: upmix,\n output: merge,\n setPan: (value) => {\n currentPan = value;\n apply();\n },\n setSourceChannelCount: (value) => {\n currentChannelCount = value;\n apply();\n },\n dispose: () => {\n for (const node of [upmix, split, ll, lr, rl, rr, merge]) {\n try {\n node.disconnect();\n } catch (err) {\n console.warn(PREFIX + 'pan stage: error disconnecting node: ' + String(err));\n }\n }\n },\n };\n}\n","/**\n * A value that changes too often to live in UI state (meter levels, recording\n * progress): read it with `getSnapshot()`, or be told about each new value\n * with `subscribe()`.\n *\n * The pair matches React's `useSyncExternalStore(source.subscribe,\n * source.getSnapshot)`, but nothing here depends on React.\n */\nexport interface ValueSource<T> {\n /**\n * Call `listener` with each new value. Returns the function that removes\n * the subscription.\n */\n subscribe(listener: (value: T) => void): () => void;\n /** The latest value. The same object is returned until the next change. */\n getSnapshot(): T;\n}\n\n/** Per-channel meter readings, each normalized to 0-1. */\nexport interface MeterLevels {\n /** Smoothed peak level per channel. */\n levels: number[];\n /** Highest level seen per channel since the last reset. */\n peakLevels: number[];\n /** RMS level per channel. */\n rmsLevels: number[];\n}\n\nexport type MeterSource = ValueSource<MeterLevels>;\n\n/** What a recording in progress has captured so far. */\nexport interface RecordingProgress {\n /** Elapsed recording time in seconds. */\n duration: number;\n /** Min/max peak pairs per channel, for the live waveform preview. */\n peaks: (Int8Array | Int16Array)[];\n}\n\nexport type RecordingProgressSource = ValueSource<RecordingProgress>;\n\nexport interface ValueSourceHandle<T> {\n /** The read side, safe to hand to consumers. */\n source: ValueSource<T>;\n /** Replace the value and notify listeners. A no-op for the current value. */\n publish(value: T): void;\n}\n\n/** Build a `MeterLevels` of zeros for `channelCount` channels. */\nexport function silentMeterLevels(channelCount: number): MeterLevels {\n const count = Math.max(0, Math.floor(channelCount));\n return {\n levels: new Array<number>(count).fill(0),\n peakLevels: new Array<number>(count).fill(0),\n rmsLevels: new Array<number>(count).fill(0),\n };\n}\n\n/**\n * Create a `ValueSource` together with the function that publishes to it.\n * Published values must be new objects: listeners and `getSnapshot` callers\n * compare by identity.\n */\nexport function createValueSource<T>(initial: T): ValueSourceHandle<T> {\n let current = initial;\n // Keyed by a per-subscription token, so the same function subscribed twice\n // is two subscriptions.\n const listeners = new Map<symbol, (value: T) => void>();\n\n const source: ValueSource<T> = {\n subscribe(listener) {\n const token = Symbol('subscription');\n listeners.set(token, listener);\n return () => {\n listeners.delete(token);\n };\n },\n getSnapshot() {\n return current;\n },\n };\n\n const publish = (value: T) => {\n if (Object.is(value, current)) return;\n current = value;\n // Copy first: a listener may unsubscribe (itself or another) while this runs.\n for (const listener of [...listeners.values()]) {\n try {\n listener(value);\n } catch (err) {\n console.warn('[waveform-playlist] A value source listener threw: ' + String(err));\n }\n }\n };\n\n return { source, publish };\n}\n","import { createValueSource } from './valueSource';\n\nexport type SourceState<V> =\n | { status: 'pending' }\n | { status: 'loaded'; value: V }\n | { status: 'failed'; error: Error };\n\nexport interface SourceLoader<K, V> {\n /** Declare the whole set of keys that are wanted now. */\n setWanted(keys: Iterable<K>): void;\n /** Abort every load in flight. Wanted keys and loaded values are kept. */\n suspend(): void;\n /** Record a value the caller already holds as loaded. */\n provide(key: K, value: V): void;\n /** Start a failed key again. A no-op for any other state. */\n retry(key: K): void;\n /** `ValueSource` shape: a new Map object on every change. */\n subscribe(listener: (states: ReadonlyMap<K, SourceState<V>>) => void): () => void;\n getSnapshot(): ReadonlyMap<K, SourceState<V>>;\n}\n\ninterface Entry<V> {\n state: SourceState<V>;\n /** Present only while a load is in flight. */\n controller?: AbortController;\n /** Identifies the load whose result may still be applied. */\n token: symbol;\n}\n\nfunction toError(reason: unknown): Error {\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\n/**\n * Loads sources by key. One owner declares the whole set of wanted keys with\n * `setWanted`; a key is loaded once, kept while it stays wanted, and dropped\n * (its load aborted) when it leaves the set. Framework-free: read it with\n * `useSyncExternalStore(loader.subscribe, loader.getSnapshot)`.\n *\n * A rejection is ignored only when the loader aborted that load; a load that\n * rejects with an AbortError of its own is recorded as `failed` (`retry` restarts it).\n */\nexport function createSourceLoader<K, V>(options: {\n load: (key: K, signal: AbortSignal) => Promise<V>;\n}): SourceLoader<K, V> {\n const { load } = options;\n const entries = new Map<K, Entry<V>>();\n // Set by suspend(), cleared by setWanted(): while set, nothing may start a load.\n let suspended = false;\n const { source, publish } = createValueSource<ReadonlyMap<K, SourceState<V>>>(new Map());\n\n const publishEntries = () => {\n const next = new Map<K, SourceState<V>>();\n for (const [key, entry] of entries) next.set(key, entry.state);\n publish(next);\n };\n\n const abort = (entry: Entry<V>) => {\n entry.controller?.abort();\n };\n\n // Start a load for `key`; the caller publishes afterwards.\n const start = (key: K) => {\n const token = Symbol('load');\n const controller = new AbortController();\n const entry: Entry<V> = { state: { status: 'pending' }, controller, token };\n entries.set(key, entry);\n\n const settle = (state: SourceState<V>) => {\n const current = entries.get(key);\n if (!current || current.token !== token) return;\n entries.set(key, { state, token });\n publishEntries();\n };\n\n let promise: Promise<V>;\n try {\n // A plain function that returns the value instead of a promise is accepted.\n promise = Promise.resolve(load(key, controller.signal));\n } catch (err) {\n entries.set(key, { state: { status: 'failed', error: toError(err) }, token });\n return;\n }\n promise.then(\n (value) => settle({ status: 'loaded', value }),\n (err: unknown) => {\n // A load the loader aborted is ignored by the token check in settle()\n // as well; returning here only skips building an Error for it. A load\n // that rejects with its own AbortError is not aborted here: a failure.\n if (controller.signal.aborted) return;\n settle({ status: 'failed', error: toError(err) });\n }\n );\n };\n\n return {\n setWanted(keys) {\n const wanted = new Set(keys);\n suspended = false;\n let changed = false;\n for (const [key, entry] of [...entries]) {\n if (wanted.has(key)) continue;\n abort(entry);\n entries.delete(key);\n changed = true;\n }\n for (const key of wanted) {\n const entry = entries.get(key);\n if (entry && (entry.state.status !== 'pending' || entry.controller)) continue;\n start(key);\n // Restarting a suspended key leaves it pending: nothing to publish unless it failed at once.\n if (!entry || entries.get(key)?.state.status !== 'pending') changed = true;\n }\n if (changed) publishEntries();\n },\n\n suspend() {\n suspended = true;\n for (const [key, entry] of [...entries]) {\n if (entry.state.status !== 'pending' || !entry.controller) continue;\n abort(entry);\n entries.set(key, { state: entry.state, token: Symbol('suspended') });\n }\n },\n\n provide(key, value) {\n const entry = entries.get(key);\n if (entry?.state.status === 'loaded') return;\n if (entry) abort(entry);\n entries.set(key, { state: { status: 'loaded', value }, token: Symbol('provided') });\n publishEntries();\n },\n\n retry(key) {\n if (entries.get(key)?.state.status !== 'failed') return;\n if (suspended) {\n // Nothing would abort a load started now: wait for the next setWanted.\n entries.set(key, { state: { status: 'pending' }, token: Symbol('suspended') });\n } else {\n start(key);\n }\n publishEntries();\n },\n\n subscribe: source.subscribe,\n getSnapshot: source.getSnapshot,\n };\n}\n","import type { Fade } from './types';\nimport type { RenderMode, SpectrogramConfig, ColorMapValue } from './types/spectrogram';\nimport { createClipFromSeconds, createTrack } from './types/clip';\nimport type {\n AudioClip,\n ClipSource,\n LoadingClip,\n ArrangementTrack,\n WaveformDataObject,\n} from './types/clip';\n\nexport interface AudioTrackOptions {\n /** Track id. Default: generated. An empty string counts as none. */\n id?: string;\n /** Id of the clip. Default: generated. An empty string counts as none. */\n clipId?: string;\n /** Track name. Default: the file name of `src` without its extension, else 'Untitled'. */\n name?: string;\n /** The audio to load. A string is a URL; a Blob or File is keyed by identity. */\n src?: ClipSource;\n /** Audio already in memory. With `src` too, the clip is an `AudioClip` that records `src`. */\n audioBuffer?: AudioBuffer;\n /** Pre-computed peaks. Without `src` or `audioBuffer`, the clip is built from these alone. */\n waveformData?: WaveformDataObject;\n /** Position on the timeline, in seconds. Default 0. */\n start?: number;\n /** Duration in seconds. Default: the whole source from `offset`. */\n duration?: number;\n /** Start within the source, in seconds. Default 0. */\n offset?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Clip gain. Default 1. */\n gain?: number;\n color?: string;\n muted?: boolean;\n soloed?: boolean;\n volume?: number;\n pan?: number;\n renderMode?: RenderMode;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n}\n\n// A copy of the private generateId in types/clip.ts (same id format).\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\nfunction checkNonNegative(name: string, value: number | undefined): void {\n if (value !== undefined && !(Number.isFinite(value) && value >= 0)) {\n throw new Error(`audioTrack: ${name} must be a finite number of seconds, 0 or more`);\n }\n}\n\nfunction checkOptions(options: AudioTrackOptions): void {\n checkNonNegative('start', options.start);\n checkNonNegative('offset', options.offset);\n const { duration } = options;\n if (duration !== undefined && !(Number.isFinite(duration) && duration > 0)) {\n throw new Error('audioTrack: duration must be a positive finite number of seconds');\n }\n}\n\nfunction decodeName(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name; // a malformed sequence keeps the raw name\n }\n}\n\nfunction defaultName(src: ClipSource | undefined): string {\n const raw =\n typeof src === 'string'\n ? src\n : typeof File !== 'undefined' && src instanceof File\n ? src.name\n : '';\n if (/^(data|blob):/i.test(raw)) return 'Untitled';\n const path = raw.split(/[?#]/)[0];\n const file = path.slice(path.lastIndexOf('/') + 1);\n const dot = file.lastIndexOf('.');\n const base = dot > 0 ? file.slice(0, dot) : file;\n return decodeName(base) || 'Untitled';\n}\n\n/**\n * Duration in seconds to build the clip with. An offset at or past the end of\n * the audio throws; a duration that runs past the end is cut to it, with a\n * warning. Compared in samples, with a tolerance of one sample.\n */\nfunction fitToAudio(\n name: string,\n offset: number,\n duration: number | undefined,\n sampleRate: number,\n sourceSamples: number\n): number {\n const offsetSamples = Math.round(offset * sampleRate);\n if (offsetSamples >= sourceSamples) {\n throw new Error('audioTrack: offset is past the end of the audio');\n }\n const remaining = sourceSamples - offsetSamples;\n if (duration === undefined) return remaining / sampleRate;\n const wanted = Math.round(duration * sampleRate);\n if (offsetSamples + wanted > sourceSamples + 1) {\n console.warn(\n `[waveform-playlist] audioTrack: offset + duration of \"${name}\" runs past the end of the audio; the clip is cut to the end.`\n );\n }\n return Math.min(wanted, remaining) / sampleRate;\n}\n\nfunction buildLoadingClip(\n id: string,\n src: ClipSource,\n name: string,\n options: AudioTrackOptions\n): LoadingClip {\n const given = {\n start: options.start,\n duration: options.duration,\n offset: options.offset,\n gain: options.gain,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n color: options.color,\n waveformData: options.waveformData,\n };\n const present = Object.entries(given).filter(([, value]) => value !== undefined);\n return { id, src, name, ...Object.fromEntries(present) };\n}\n\nfunction buildClip(options: AudioTrackOptions, name: string): AudioClip | LoadingClip {\n const { audioBuffer, waveformData, start = 0, offset = 0, duration } = options;\n const src = options.src || undefined; // '' counts as none\n const id = options.clipId || generateId();\n if (src !== undefined && !audioBuffer) return buildLoadingClip(id, src, name, options);\n if (!audioBuffer && !waveformData) {\n throw new Error('audioTrack: give src, audioBuffer or waveformData');\n }\n // The length of the audio in samples: the buffer's own length, or the\n // waveform data's duration rounded up, as createClipFromSeconds rounds it.\n const sampleRate = audioBuffer?.sampleRate ?? waveformData?.sample_rate ?? 0;\n const sourceSamples =\n audioBuffer?.length ?? Math.ceil((waveformData?.duration ?? 0) * sampleRate);\n const clipSeconds = fitToAudio(name, offset, duration, sampleRate, sourceSamples);\n const clip = createClipFromSeconds({\n audioBuffer,\n waveformData,\n startTime: start,\n offset,\n duration: clipSeconds,\n name,\n gain: options.gain,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n color: options.color,\n src,\n });\n return { ...clip, id };\n}\n\n/**\n * Builds a track whose one clip names its audio. With `src` and no\n * `audioBuffer` the clip is a `LoadingClip` (audio not loaded yet); with\n * `audioBuffer`, or `waveformData` and no `src`, it is an `AudioClip` built now.\n * A duration that runs past the end of the audio is cut to it, with a warning.\n */\nexport function audioTrack(options: AudioTrackOptions): ArrangementTrack {\n checkOptions(options);\n const name = options.name ?? defaultName(options.src);\n const clip = buildClip(options, name);\n const base = createTrack({\n name,\n muted: options.muted,\n soloed: options.soloed,\n volume: options.volume,\n pan: options.pan,\n spectrogramConfig: options.spectrogramConfig,\n spectrogramColorMap: options.spectrogramColorMap,\n color: options.color,\n });\n const track: ArrangementTrack = {\n ...base,\n id: options.id || base.id,\n clips: [clip],\n renderMode: options.renderMode,\n };\n return track;\n}\n","/**\n * One gesture on a mixer control (a fader drag, a held arrow key) as one\n * undo step (#843). The mixer setters join changes that carry the same\n * `gesture` id into one step; this helper makes the id, and ends the gesture\n * so that the next change starts a new one.\n *\n * Framework-free: React's sliders and dawcore's elements both use it. One\n * helper per control, so two sliders never share an id. It lives in core,\n * not beside the setters in the engine, because `<daw-editor>` loads the\n * engine with a dynamic `import()`: a value import of the engine would put\n * it back in dawcore's first bundle.\n */\n\nexport interface MixerGesture {\n /** The id to pass while a gesture is going on. */\n readonly id: string;\n /** The gesture is over: the next change starts a new one. */\n end(): void;\n /** Ends the gesture on the input's own events; returns the detach function. */\n attach(input: HTMLInputElement): () => void;\n}\n\n/**\n * The keys that move a range input. While one is down the browser repeats\n * it, and the input fires `change` on each step: the gesture lasts until the\n * key comes up.\n */\nconst RANGE_KEYS: ReadonlySet<string> = new Set([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'PageUp',\n 'PageDown',\n 'Home',\n 'End',\n]);\n\n/**\n * Made once per copy of this module, so two copies of the package installed\n * side by side (each with its own counter) never make the same id.\n */\nconst ID_PREFIX = Math.random().toString(36).slice(2, 10);\nlet idCount = 0;\n\nfunction nextId(): string {\n idCount += 1;\n return `mg-${ID_PREFIX}-${idCount}`;\n}\n\n/**\n * Make the gesture helper of one mixer control.\n *\n * ```ts\n * const gesture = createMixerGesture();\n * const detach = gesture.attach(slider);\n * slider.addEventListener('input', () =>\n * engine.setTrackVolume(trackId, slider.valueAsNumber, { gesture: gesture.id })\n * );\n * ```\n *\n * `attach` ends the gesture on the input's `change` (the end of a pointer\n * drag), except while a key that moves the input is held down; then on that\n * key's `keyup`. A `blur` ends it too. Mute and solo buttons need no helper:\n * each click is a step of its own.\n */\nexport function createMixerGesture(): MixerGesture {\n let id = nextId();\n const end = (): void => {\n id = nextId();\n };\n\n const attach = (input: HTMLInputElement): (() => void) => {\n let heldKey: string | null = null;\n\n const onKeyDown = (event: Event): void => {\n const { key } = event as KeyboardEvent;\n if (RANGE_KEYS.has(key)) heldKey = key;\n };\n const onKeyUp = (event: Event): void => {\n if ((event as KeyboardEvent).key !== heldKey) return;\n heldKey = null;\n end();\n };\n const onChange = (): void => {\n if (heldKey === null) end();\n };\n const onBlur = (): void => {\n heldKey = null;\n end();\n };\n\n input.addEventListener('keydown', onKeyDown);\n input.addEventListener('keyup', onKeyUp);\n input.addEventListener('change', onChange);\n input.addEventListener('blur', onBlur);\n return () => {\n input.removeEventListener('keydown', onKeyDown);\n input.removeEventListener('keyup', onKeyUp);\n input.removeEventListener('change', onChange);\n input.removeEventListener('blur', onBlur);\n };\n };\n\n return {\n get id() {\n return id;\n },\n end,\n attach,\n };\n}\n","/**\n * The effect registry shared by `<daw-editor>` and the React effects hooks:\n * one `registerEffect()` call makes a custom effect (an AudioWorklet, or any\n * chain of native nodes) available to both. Nothing here creates an audio\n * node; definitions are handed the context they must build on.\n */\n\n/** Range/display metadata for one effect parameter. */\nexport interface EffectParamDef {\n min: number;\n max: number;\n step?: number;\n /** 's', 'ms', 'Hz', 'dB', '%' … */\n unit?: string;\n /** Display name for a parameter panel. Defaults to the parameter's key. */\n label?: string;\n}\n\n/**\n * A live, wired effect. `input`/`output` are the chain attachment points\n * (the same node for single-node effects). `applyParams` updates AudioParams\n * in place — the chain never rebuilds for parameter changes.\n *\n * The host owns every connection OUT of `output`: when it rewires the chain\n * it disconnects all of them. Do not connect `output` to anything inside the\n * effect (a feedback path, say); take such a tap from a node before it.\n */\nexport interface NativeEffectInstance {\n input: AudioNode;\n output: AudioNode;\n applyParams: (params: Record<string, number>) => void;\n dispose?: () => void;\n /** Serializable snapshot of plugin-internal state (WAM getState). */\n getState?: () => Promise<unknown>;\n /** Builds the plugin's own GUI element (WAM createGui). GUI lifecycle is\n * independent of audio — hiding/destroying a GUI never stops processing. */\n createGui?: () => Promise<HTMLElement>;\n /** Releases a GUI element previously built by `createGui` (WAM destroyGui). */\n destroyGui?: (gui: HTMLElement) => void;\n /** Parameter metadata for the generic fallback panel (WAM getParameterInfo). */\n getParameterInfo?: () => Promise<unknown>;\n}\n\n/** A registered effect type. `create` must work on any BaseAudioContext so\n * the same definitions serve offline rendering. */\nexport interface NativeEffectDefinition {\n label: string;\n category: string;\n defaults: Record<string, number>;\n params: Record<string, EffectParamDef>;\n /** Name of the wet/dry param, when the effect has one. Bypass zeroes it\n * (storing the original); effects without one are bypassed by\n * disconnection. */\n wetParam?: string;\n /**\n * Optional async setup that must finish before `create` can run on a given\n * context — typically `audioContext.audioWorklet.addModule(url)` for an\n * AudioWorklet-backed effect. Worklet modules are context-bound, so this\n * runs once per context, including the OfflineAudioContext of every export\n * (which the consumer never sees). Hosts await it wherever they can: the\n * React hooks' `addEffect`, both surfaces' exports, `<daw-editor>`'s\n * `setEffectsState()`. `<daw-editor>`'s `addEffect()` is synchronous and\n * cannot — call `editor.prepareEffect(type)` first.\n *\n * Must be safe to run more than once on the same context: it runs again\n * after a failed attempt and when the type is re-registered.\n */\n prepare?: (audioContext: BaseAudioContext) => Promise<void>;\n create: (audioContext: BaseAudioContext, params: Record<string, number>) => NativeEffectInstance;\n /**\n * Set by a host library on the effects of its own catalogue (dawcore's\n * `native-*`), never by an app. The registry is shared between hosts, and a\n * host lists its own catalogue plus what the app registered, not another\n * host's catalogue: the React effect picker leaves these out. The effect\n * can still be added by id anywhere.\n */\n builtIn?: boolean;\n}\n\n/** Result of creating an effect via the registry. */\nexport interface CreatedNativeEffect {\n instance: NativeEffectInstance;\n params: Record<string, number>;\n wetParam?: string;\n}\n\ninterface PreparedRecord {\n /** The definition this preparation ran for — a re-registered type must\n * prepare again with its new definition. */\n definition: NativeEffectDefinition;\n promise: Promise<void>;\n settled: boolean;\n}\n\ninterface RegistryState {\n definitions: Map<string, NativeEffectDefinition>;\n /** Per-context preparation state. Weak: an OfflineAudioContext (one per\n * export) must not be kept alive by the registry. */\n prepared: WeakMap<BaseAudioContext, Map<string, PreparedRecord>>;\n}\n\n/**\n * The registry lives on `globalThis`, not in this module. An app can end up\n * with two copies of this package (its own version, and the exact version a\n * dependent pins); with a module-level map an effect registered through one\n * copy would be unknown to hosts using the other.\n */\n// Versioned: every copy that shares the state must agree on its shape. A\n// change to `RegistryState` needs a new key.\nconst REGISTRY_KEY = Symbol.for('@waveform-playlist/core/effect-registry/v1');\n\nfunction registryState(): RegistryState {\n const holder = globalThis as unknown as Record<symbol, RegistryState | undefined>;\n const existing = holder[REGISTRY_KEY];\n if (existing) return existing;\n const created: RegistryState = { definitions: new Map(), prepared: new WeakMap() };\n holder[REGISTRY_KEY] = created;\n return created;\n}\n\nconst registry = registryState().definitions;\nconst prepared = registryState().prepared;\n\nexport function registerEffect(type: string, definition: NativeEffectDefinition): void {\n if (registry.has(type)) {\n console.warn(\n '[waveform-playlist] registerEffect: overwriting existing effect type \"' + type + '\"'\n );\n }\n registry.set(type, definition);\n}\n\n/** Remove a registered type. Returns whether it was registered. Effects\n * already created from it keep working. */\nexport function unregisterEffect(type: string): boolean {\n return registry.delete(type);\n}\n\n/** A copy — mutating the returned map does not affect the registry. */\nexport function getEffectDefinitions(): Map<string, NativeEffectDefinition> {\n return new Map(registry);\n}\n\n/**\n * Run a registered effect's `prepare` hook for one context, once. Concurrent\n * and later calls share the same run; a failed run is forgotten so the next\n * call retries. Resolves immediately for definitions without a hook, and for\n * unknown types (creating the effect reports those).\n */\nexport function prepareEffect(type: string, audioContext: BaseAudioContext): Promise<void> {\n const definition = registry.get(type);\n if (!definition?.prepare) {\n return Promise.resolve();\n }\n const forContext = prepared.get(audioContext) ?? new Map<string, PreparedRecord>();\n prepared.set(audioContext, forContext);\n const existing = forContext.get(type);\n if (existing && existing.definition === definition) {\n return existing.promise;\n }\n\n const prepare = definition.prepare;\n const record: PreparedRecord = {\n definition,\n settled: false,\n // The async wrapper turns a synchronous throw into a rejection.\n promise: (async () => prepare(audioContext))().then(\n () => {\n record.settled = true;\n },\n (err: unknown) => {\n if (forContext.get(type) === record) {\n forContext.delete(type);\n }\n throw err;\n }\n ),\n };\n forContext.set(type, record);\n return record.promise;\n}\n\nfunction isPrepared(\n type: string,\n definition: NativeEffectDefinition,\n audioContext: BaseAudioContext\n): boolean {\n const record = prepared.get(audioContext)?.get(type);\n return record !== undefined && record.definition === definition && record.settled;\n}\n\n/**\n * Whether `type` has a prepare hook that has not completed on this context\n * for its CURRENT definition. Synchronous, so async callers can skip the\n * await (and stay synchronous) for the common case of effects without one.\n */\nexport function needsPrepare(type: string, audioContext: BaseAudioContext): boolean {\n const definition = registry.get(type);\n return definition?.prepare !== undefined && !isPrepared(type, definition, audioContext);\n}\n\n/**\n * Await a type's preparation until it holds for the definition registered\n * NOW. A type re-registered while its old definition was preparing would\n * otherwise reach `create` unprepared. Rejects with the hook's own error.\n */\nexport async function ensureEffectPrepared(\n type: string,\n audioContext: BaseAudioContext\n): Promise<void> {\n while (needsPrepare(type, audioContext)) {\n await prepareEffect(type, audioContext);\n }\n}\n\nexport function createEffectInstance(\n type: string,\n audioContext: BaseAudioContext,\n params: Record<string, number> = {}\n): CreatedNativeEffect {\n const definition = registry.get(type);\n if (!definition) {\n throw new Error(\n '[waveform-playlist] createEffectInstance: unknown effect type \"' +\n type +\n '\". Available types: ' +\n [...registry.keys()].join(', ')\n );\n }\n const merged = { ...definition.defaults, ...params };\n let instance: NativeEffectInstance;\n try {\n instance = definition.create(audioContext, merged);\n } catch (err) {\n if (!definition.prepare || isPrepared(type, definition, audioContext)) {\n throw err;\n }\n // The likeliest cause by far: an AudioWorklet module that was never\n // added to THIS context. Name the fix; keep the original message.\n const hinted = new Error(\n '[waveform-playlist] effect \"' +\n type +\n '\" has a prepare() step that has not completed on this audio context — ' +\n \"await prepareEffect('\" +\n type +\n \"', audioContext) before creating it (on <daw-editor>: await editor.prepareEffect('\" +\n type +\n \"') before addEffect). Original error: \" +\n (err instanceof Error ? err.message : String(err))\n ) as Error & { cause?: unknown };\n // Keep the original (its name, type and stack) reachable: the hint is a\n // guess at the cause, and `create` may have thrown for a real bug.\n hinted.cause = err;\n throw hinted;\n }\n try {\n instance.applyParams(merged);\n } catch (err) {\n // The caller never sees this instance, so nobody else can release it.\n try {\n instance.dispose?.();\n } catch {\n // The applyParams error is the one to report.\n }\n throw err;\n }\n return { instance, params: merged, wetParam: definition.wetParam };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,mBAAmB;;;AC2KzB,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcO,SAAS,cAAc,MAAoD;AAChF,SAAO,EAAE,gBAAgB,SAAS,KAAK,cAAc;AACvD;AAmLO,SAAS,oBAAoB,SAA4C;AAC9E,QAAM,EAAE,WAAW,gBAAgB,KAAK,KAAK,IAAI;AAEjD,MAAI,YAAY,GAAG;AACjB,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AAEA,MAAI;AACJ,MAAI,gBAAgB;AAClB,gBAAY;AAAA,EACd,WAAW,QAAQ,UAAa,SAAS,QAAW;AAClD,gBAAY,CAAC,SAAkB,OAAO,MAAO,OAAO;AAAA,EACtD,OAAO;AACL,UAAM,IAAI;AAAA,MACR;AAAA,IACF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AAC,WAAW,WAAW,WAAW,MAAM,YAAY,YAAY,GAAG;AACrE,YAAM;AAAA,IACR;AAGA,UAAM,SAAS,IAAI;AAAA,MACjB,iCACE,OACA,qGAEA,OACA,uFACA,OACA,4CACC,eAAe,QAAQ,IAAI,UAAU,OAAO,GAAG;AAAA,IACpD;AAGA,WAAO,QAAQ;AACf,UAAM;AAAA,EACR;AACA,MAAI;AACF,aAAS,YAAY,MAAM;AAAA,EAC7B,SAAS,KAAK;AAEZ,QAAI;AACF,eAAS,UAAU;AAAA,IACrB,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACA,SAAO,EAAE,UAAU,QAAQ,QAAQ,UAAU,WAAW,SAAS;AACnE;","names":["InteractionState","label","ts","tpBar","tpBeat","offset","barIndexInSegment","beatInBar","newPeaks","result","x","generateId"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/constants.ts","../src/types/clip.ts","../src/types/index.ts","../src/utils/conversions.ts","../src/utils/beatsAndBars.ts","../src/utils/dBUtils.ts","../src/utils/musicalTicks.ts","../src/utils/meterDetection.ts","../src/utils/peaksGenerator.ts","../src/utils/audioBufferUtils.ts","../src/utils/latency.ts","../src/utils/spectrogram-defaults.ts","../src/utils/carveClipRange.ts","../src/utils/meterLevels.ts","../src/clipTimeHelpers.ts","../src/trackKind.ts","../src/spectrogramCanvasId.ts","../src/fades.ts","../src/keyboard.ts","../src/probeRangeSupport.ts","../src/enumerateMicrophones.ts","../src/annotations/boundaries.ts","../src/annotations/shortcuts.ts","../src/annotations/devFreeze.ts","../src/annotations/store.ts","../src/annotations/bounds.ts","../src/panStage.ts","../src/panLaw.ts","../src/valueSource.ts","../src/sourceLoader.ts","../src/audioTrack.ts","../src/mixerGesture.ts","../src/effects/registry.ts"],"sourcesContent":["export * from './constants';\nexport * from './types';\nexport * from './utils';\nexport * from './clipTimeHelpers';\nexport * from './trackKind';\nexport * from './spectrogramCanvasId';\nexport * from './fades';\nexport * from './keyboard';\nexport * from './probeRangeSupport';\nexport * from './enumerateMicrophones';\nexport * from './annotations/boundaries';\nexport * from './annotations/shortcuts';\nexport * from './annotations/store';\nexport * from './annotations/bounds';\nexport * from './panStage';\nexport * from './panLaw';\nexport * from './valueSource';\nexport * from './sourceLoader';\nexport * from './audioTrack';\nexport { createMixerGesture } from './mixerGesture';\nexport type { MixerGesture } from './mixerGesture';\nexport * from './effects/registry';\n","/**\n * Maximum width in CSS pixels for a single canvas chunk.\n * Canvas elements are split into chunks of this width to enable\n * horizontal virtual scrolling — only visible chunks are mounted.\n */\nexport const MAX_CANVAS_WIDTH = 1000;\n","/**\n * Clip-Based Model Types\n *\n * These types support a professional multi-track editing model where:\n * - Each track can contain multiple audio clips\n * - Clips can be positioned anywhere on the timeline\n * - Clips have independent trim points (offset/duration)\n * - Gaps between clips are silent\n * - Clips can overlap (for crossfades)\n */\n\nimport { Fade } from './index';\nimport type { RenderMode, SpectrogramConfig, ColorMapValue } from './spectrogram';\nimport type { PanLaw } from '../panLaw';\n\n/**\n * WaveformData object from waveform-data.js library.\n * Supports resample() and slice() for dynamic zoom levels.\n * See: https://github.com/bbc/waveform-data.js\n */\nexport interface WaveformDataObject {\n /** Sample rate of the original audio */\n readonly sample_rate: number;\n /** Number of audio samples per pixel */\n readonly scale: number;\n /** Length of waveform data in pixels */\n readonly length: number;\n /** Bit depth (8 or 16) */\n readonly bits: number;\n /** Duration in seconds */\n readonly duration: number;\n /** Number of channels */\n readonly channels: number;\n /** Get channel data */\n channel: (index: number) => {\n min_array: () => number[];\n max_array: () => number[];\n };\n /** Resample to different scale */\n resample: (options: { scale: number } | { width: number }) => WaveformDataObject;\n /** Slice a portion of the waveform */\n slice: (\n options: { startTime: number; endTime: number } | { startIndex: number; endIndex: number }\n ) => WaveformDataObject;\n}\n\n/**\n * Represents a single audio clip on the timeline\n *\n * IMPORTANT: All positions/durations are stored as SAMPLE COUNTS (integers)\n * to avoid floating-point precision errors. Convert to seconds only when\n * needed for playback using: seconds = samples / sampleRate\n *\n * Clips can be created with just waveformData (for instant visual rendering)\n * and have audioBuffer added later when audio finishes loading.\n */\nexport interface AudioClip {\n /** Unique identifier for this clip */\n id: string;\n\n /**\n * The audio buffer containing the audio data.\n * Optional for peaks-first rendering - can be added later.\n * Required for playback and editing operations.\n */\n audioBuffer?: AudioBuffer;\n\n /** Position on timeline where this clip starts (in samples at timeline sampleRate) */\n startSample: number;\n\n /**\n * Position on timeline in ticks (authoritative when present).\n * When set, startSample is a derived cache recomputed from startTick via TempoMap.\n * Optional for backwards compatibility — engine enriches clips without startTick on ingestion.\n */\n startTick?: number;\n\n /** Duration of this clip (in samples) - how much of the audio buffer to play */\n durationSamples: number;\n\n /** Offset into the audio buffer where playback starts (in samples) - the \"trim start\" point */\n offsetSamples: number;\n\n /**\n * Sample rate for this clip's audio.\n * Required when audioBuffer is not provided (for peaks-first rendering).\n * When audioBuffer is present, this should match audioBuffer.sampleRate.\n */\n sampleRate: number;\n\n /**\n * Total duration of the source audio in samples.\n * Required when audioBuffer is not provided (for trim bounds calculation).\n * When audioBuffer is present, this should equal audioBuffer.length.\n */\n sourceDurationSamples: number;\n\n /** Optional fade in effect */\n fadeIn?: Fade;\n\n /** Optional fade out effect */\n fadeOut?: Fade;\n\n /** Clip-specific gain/volume multiplier (0.0 to 1.0+) */\n gain: number;\n\n /** Optional label/name for this clip */\n name?: string;\n\n /** Optional color for visual distinction */\n color?: string;\n\n /**\n * Pre-computed waveform data from waveform-data.js library.\n * When provided, the library will use this instead of computing peaks from the audioBuffer.\n * Supports resampling to different zoom levels and slicing for clip trimming.\n * Load with: `const waveformData = await loadWaveformData('/path/to/peaks.dat')`\n */\n waveformData?: WaveformDataObject;\n\n /**\n * MIDI note data — when present, this clip plays MIDI instead of audio.\n * The playout adapter uses this field to detect MIDI clips and route them\n * to MidiToneTrack (PolySynth) instead of ToneTrack (AudioBufferSourceNode).\n */\n midiNotes?: MidiNoteData[];\n\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n\n /** MIDI program number (0-127). GM instrument number for SoundFont playback. */\n midiProgram?: number;\n\n /** The source this clip's audio came from (a URL, Blob or File), when it is known. */\n src?: ClipSource;\n}\n\n/** What a loading clip names. A string is a URL; a Blob or File is keyed by identity. */\nexport type ClipSource = string | Blob;\n\n/**\n * A clip whose audio is not loaded yet. Times are in seconds; whatever loads\n * `src` turns it into an `AudioClip` (integer samples).\n */\nexport interface LoadingClip {\n /** Unique identifier for this clip */\n id: string;\n\n /** The audio to load */\n src: ClipSource;\n\n /** Position on the timeline, in seconds. Default 0. */\n start?: number;\n\n /** Duration in seconds. Default: the whole source from `offset`. */\n duration?: number;\n\n /** Start within the source, in seconds. Default 0. */\n offset?: number;\n\n name?: string;\n gain?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n color?: string;\n\n /** Pre-computed peaks, drawn while the audio loads */\n waveformData?: WaveformDataObject;\n}\n\n/**\n * The fields of a track that say how it is drawn, not how it plays. An\n * adapter is never given them (`PlayoutTrack`), and the engine makes no\n * adapter call for a change of these fields alone: on the native transport an\n * `updateTrack` stops the track's playing sources (silent until its next\n * clip), so a render-mode choice during playback silenced it (review of #930). The one list; the engine reads it.\n */\nexport const TRACK_VIEW_FIELDS = [\n 'name',\n 'color',\n 'height',\n 'renderMode',\n 'spectrogramConfig',\n 'spectrogramColorMap',\n] as const satisfies readonly (keyof ClipTrack)[];\n\n/** A field of `TRACK_VIEW_FIELDS`. */\nexport type TrackViewField = (typeof TRACK_VIEW_FIELDS)[number];\n\n/** A track as a playout adapter is given it: a `ClipTrack` without the view fields. */\nexport type PlayoutTrack = Omit<ClipTrack, TrackViewField>;\n\n/** A track whose clips are loaded (`AudioClip`) or not loaded yet (`LoadingClip`). */\nexport type ArrangementTrack = Omit<ClipTrack, 'clips'> & {\n clips: (AudioClip | LoadingClip)[];\n};\n\n/** True for a clip whose audio is not loaded yet (it has no `sampleRate`). */\nexport function isLoadingClip(clip: AudioClip | LoadingClip): clip is LoadingClip {\n return !('sampleRate' in clip) || clip.sampleRate == null;\n}\n\n/** What a track holds: audio clips or MIDI clips. A track never holds both. */\nexport type TrackKind = 'audio' | 'midi';\n\n/**\n * Represents a track containing multiple clips of one kind\n */\nexport interface ClipTrack {\n /** Unique identifier for this track */\n id: string;\n\n /**\n * What the track holds. Every clip on an audio track is an audio clip and\n * every clip on a MIDI track has `midiNotes`; the engine throws on a track\n * that breaks this. An empty track has a kind too, which decides what may be\n * recorded or added to it. A MIDI track is drawn as a piano roll.\n */\n kind: TrackKind;\n\n /** Display name for this track */\n name: string;\n\n /** Array of audio clips on this track */\n clips: AudioClip[];\n\n /** Whether this track is muted */\n muted: boolean;\n\n /** Whether this track is soloed */\n soloed: boolean;\n\n /** Track volume (0.0 to 1.0+) */\n volume: number;\n\n /** Stereo pan (-1.0 = left, 0 = center, 1.0 = right) */\n pan: number;\n\n /**\n * The pan law this track enters with (default `'auto'`: decided by its\n * first decoded audio). While the track is in an arrangement, the\n * arrangement's mixer holds the value (#684).\n */\n panLaw?: PanLaw;\n\n /** Optional track color for visual distinction */\n color?: string;\n\n /** Track height in pixels (for UI) */\n height?: number;\n\n /** Visualization render mode. Default: 'waveform' */\n renderMode?: RenderMode;\n\n /** Per-track spectrogram configuration (FFT size, window, frequency scale, etc.) */\n spectrogramConfig?: SpectrogramConfig;\n\n /** Per-track spectrogram color map name or custom color array */\n spectrogramColorMap?: ColorMapValue;\n}\n\n/**\n * Represents the entire timeline/project\n */\nexport interface Timeline {\n /** All tracks in the timeline */\n tracks: ClipTrack[];\n\n /** Total timeline duration in seconds */\n duration: number;\n\n /** Sample rate for all audio (typically 44100 or 48000) */\n sampleRate: number;\n\n /** Optional project name */\n name?: string;\n\n /** Optional tempo (BPM) for grid snapping */\n tempo?: number;\n\n /** Optional time signature for grid snapping */\n timeSignature?: {\n numerator: number;\n denominator: number;\n };\n}\n\n/**\n * Options for creating a new audio clip (using sample counts)\n *\n * Either audioBuffer OR (sampleRate + sourceDurationSamples + waveformData) must be provided.\n * Providing waveformData without audioBuffer enables peaks-first rendering.\n */\nexport interface CreateClipOptions {\n /** Audio buffer - optional for peaks-first rendering */\n audioBuffer?: AudioBuffer;\n startSample: number; // Position on timeline (in samples)\n startTick?: number; // Timeline position in ticks (optional)\n durationSamples?: number; // Defaults to full buffer/source duration (in samples)\n offsetSamples?: number; // Defaults to 0\n gain?: number; // Defaults to 1.0\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Pre-computed waveform data from waveform-data.js (e.g., from BBC audiowaveform) */\n waveformData?: WaveformDataObject;\n /** Sample rate - required if audioBuffer not provided */\n sampleRate?: number;\n /** Total source audio duration in samples - required if audioBuffer not provided */\n sourceDurationSamples?: number;\n /** MIDI note data — passed through to the created AudioClip */\n midiNotes?: MidiNoteData[];\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n /** MIDI program number (0-127). GM instrument for SoundFont playback. */\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\n/**\n * Options for creating a new audio clip (using seconds for convenience)\n *\n * Either audioBuffer OR (sampleRate + sourceDuration + waveformData) must be provided.\n * Providing waveformData without audioBuffer enables peaks-first rendering.\n */\nexport interface CreateClipOptionsSeconds {\n /** Audio buffer - optional for peaks-first rendering */\n audioBuffer?: AudioBuffer;\n startTime: number; // Position on timeline (in seconds)\n startTick?: number; // Timeline position in ticks (optional)\n duration?: number; // Defaults to full buffer/source duration (in seconds)\n offset?: number; // Defaults to 0 (in seconds)\n gain?: number; // Defaults to 1.0\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Pre-computed waveform data from waveform-data.js (e.g., from BBC audiowaveform) */\n waveformData?: WaveformDataObject;\n /** Sample rate - required if audioBuffer not provided */\n sampleRate?: number;\n /** Total source audio duration in seconds - required if audioBuffer not provided */\n sourceDuration?: number;\n /** MIDI note data — passed through to the created AudioClip */\n midiNotes?: MidiNoteData[];\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. */\n midiChannel?: number;\n /** MIDI program number (0-127). GM instrument for SoundFont playback. */\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\n/**\n * Options for creating a new audio clip from tick position.\n * startTick is authoritative; startSample is derived.\n *\n * Provide either:\n * - ticksToSeconds callback (for variable-tempo / multi-tempo), or\n * - bpm + ppqn (for single-tempo convenience)\n */\nexport interface CreateClipOptionsTicks {\n startTick: number;\n ticksToSeconds?: (tick: number) => number;\n bpm?: number;\n ppqn?: number;\n audioBuffer?: AudioBuffer;\n durationSamples?: number;\n offsetSamples?: number;\n gain?: number;\n name?: string;\n color?: string;\n fadeIn?: Fade;\n fadeOut?: Fade;\n waveformData?: WaveformDataObject;\n sampleRate?: number;\n sourceDurationSamples?: number;\n midiNotes?: MidiNoteData[];\n midiChannel?: number;\n midiProgram?: number;\n /** The source this clip was loaded from — passed through to the created AudioClip */\n src?: ClipSource;\n}\n\nexport function createClipFromTicks(options: CreateClipOptionsTicks): AudioClip {\n const { startTick, ticksToSeconds, bpm, ppqn } = options;\n\n if (startTick < 0) {\n throw new Error('createClipFromTicks: startTick must be non-negative');\n }\n\n let toSeconds: (tick: number) => number;\n if (ticksToSeconds) {\n toSeconds = ticksToSeconds;\n } else if (bpm !== undefined && ppqn !== undefined) {\n toSeconds = (tick: number) => (tick * 60) / (ppqn * bpm);\n } else {\n throw new Error(\n 'createClipFromTicks: either ticksToSeconds callback or both bpm and ppqn are required'\n );\n }\n\n const sampleRate =\n options.audioBuffer?.sampleRate ?? options.sampleRate ?? options.waveformData?.sample_rate;\n if (sampleRate === undefined) {\n throw new Error('createClipFromTicks: sampleRate is required when audioBuffer is not provided');\n }\n\n const startSample = Math.round(toSeconds(startTick) * sampleRate);\n\n return createClip({\n audioBuffer: options.audioBuffer,\n startSample,\n startTick,\n durationSamples: options.durationSamples,\n offsetSamples: options.offsetSamples,\n gain: options.gain,\n name: options.name,\n color: options.color,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n waveformData: options.waveformData,\n sampleRate: options.sampleRate,\n sourceDurationSamples: options.sourceDurationSamples,\n midiNotes: options.midiNotes,\n midiChannel: options.midiChannel,\n midiProgram: options.midiProgram,\n src: options.src,\n });\n}\n\n/**\n * Options for creating a new track\n */\nexport interface CreateTrackOptions {\n name: string;\n /** What the track holds. Default: 'audio'. */\n kind?: TrackKind;\n clips?: AudioClip[];\n muted?: boolean;\n soloed?: boolean;\n volume?: number;\n pan?: number;\n color?: string;\n height?: number;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n}\n\n/**\n * Creates a new AudioClip with sensible defaults (using sample counts)\n *\n * For peaks-first rendering (no audioBuffer), sampleRate and sourceDurationSamples can be:\n * - Provided explicitly via options\n * - Derived from waveformData (sample_rate and duration properties)\n */\nexport function createClip(options: CreateClipOptions): AudioClip {\n const {\n audioBuffer,\n startSample,\n startTick,\n offsetSamples = 0,\n gain = 1.0,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n } = options;\n\n // Determine sample rate: audioBuffer > explicit option > waveformData\n const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;\n\n // Determine source duration: audioBuffer > explicit option > waveformData (converted to samples)\n const sourceDurationSamples =\n audioBuffer?.length ??\n options.sourceDurationSamples ??\n (waveformData && sampleRate ? Math.ceil(waveformData.duration * sampleRate) : undefined);\n\n if (sampleRate === undefined) {\n throw new Error(\n 'createClip: sampleRate is required when audioBuffer is not provided (can use waveformData.sample_rate)'\n );\n }\n if (sourceDurationSamples === undefined) {\n throw new Error(\n 'createClip: sourceDurationSamples is required when audioBuffer is not provided (can use waveformData.duration)'\n );\n }\n\n if (audioBuffer && waveformData && audioBuffer.sampleRate !== waveformData.sample_rate) {\n console.warn(\n '[waveform-playlist] \"' +\n (name ?? 'unnamed') +\n '\": pre-computed peaks at ' +\n waveformData.sample_rate +\n ' Hz do not match decoded audio at ' +\n audioBuffer.sampleRate +\n ' Hz — peaks may be recomputed from decoded audio'\n );\n }\n\n // Default duration to full source duration\n const durationSamples = options.durationSamples ?? sourceDurationSamples;\n\n return {\n id: generateId(),\n audioBuffer,\n startSample,\n startTick,\n durationSamples,\n offsetSamples,\n sampleRate,\n sourceDurationSamples,\n gain,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n ...(src !== undefined ? { src } : {}),\n };\n}\n\n/**\n * Creates a new AudioClip from time-based values (convenience function)\n * Converts seconds to samples using the audioBuffer's sampleRate or explicit sampleRate\n *\n * For peaks-first rendering (no audioBuffer), sampleRate and sourceDuration can be:\n * - Provided explicitly via options\n * - Derived from waveformData (sample_rate and duration properties)\n */\nexport function createClipFromSeconds(options: CreateClipOptionsSeconds): AudioClip {\n const {\n audioBuffer,\n startTime,\n offset = 0,\n gain = 1.0,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n } = options;\n\n // Determine sample rate: audioBuffer > explicit option > waveformData\n const sampleRate = audioBuffer?.sampleRate ?? options.sampleRate ?? waveformData?.sample_rate;\n if (sampleRate === undefined) {\n throw new Error(\n 'createClipFromSeconds: sampleRate is required when audioBuffer is not provided (can use waveformData.sample_rate)'\n );\n }\n\n // Determine source duration: audioBuffer > explicit option > waveformData\n const sourceDuration = audioBuffer?.duration ?? options.sourceDuration ?? waveformData?.duration;\n if (sourceDuration === undefined) {\n throw new Error(\n 'createClipFromSeconds: sourceDuration is required when audioBuffer is not provided (can use waveformData.duration)'\n );\n }\n\n // Note: audioBuffer and waveformData may have different sample rates (e.g., Opus at 48000\n // decoded on 44100 hardware). This is expected — callers fall back to worker to recompute peaks.\n\n // Default clip duration to full source duration\n const duration = options.duration ?? sourceDuration;\n\n return createClip({\n audioBuffer,\n startSample: Math.round(startTime * sampleRate),\n startTick: options.startTick,\n durationSamples: Math.round(duration * sampleRate),\n offsetSamples: Math.round(offset * sampleRate),\n sampleRate,\n sourceDurationSamples: Math.ceil(sourceDuration * sampleRate),\n gain,\n name,\n color,\n fadeIn,\n fadeOut,\n waveformData,\n midiNotes,\n midiChannel,\n midiProgram,\n src,\n });\n}\n\n/**\n * Creates a new ClipTrack with sensible defaults\n */\nexport function createTrack(options: CreateTrackOptions): ClipTrack {\n const {\n name,\n kind = 'audio',\n clips = [],\n muted = false,\n soloed = false,\n volume = 1.0,\n pan = 0,\n color,\n height,\n spectrogramConfig,\n spectrogramColorMap,\n } = options;\n\n return {\n id: generateId(),\n kind,\n name,\n clips,\n muted,\n soloed,\n volume,\n pan,\n color,\n height,\n spectrogramConfig,\n spectrogramColorMap,\n };\n}\n\n/**\n * Creates a new Timeline with sensible defaults\n */\nexport function createTimeline(\n tracks: ClipTrack[],\n sampleRate: number = 44100,\n options?: {\n name?: string;\n tempo?: number;\n timeSignature?: { numerator: number; denominator: number };\n }\n): Timeline {\n // Calculate total duration from all clips across all tracks (in seconds)\n const durationSamples = tracks.reduce((maxSamples, track) => {\n const trackSamples = track.clips.reduce((max, clip) => {\n return Math.max(max, clip.startSample + clip.durationSamples);\n }, 0);\n return Math.max(maxSamples, trackSamples);\n }, 0);\n\n const duration = durationSamples / sampleRate;\n\n return {\n tracks,\n duration,\n sampleRate,\n name: options?.name,\n tempo: options?.tempo,\n timeSignature: options?.timeSignature,\n };\n}\n\n/**\n * Generates a unique ID for clips and tracks\n */\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n}\n\n/**\n * MIDI note data for clips that play MIDI instead of audio.\n * When present on an AudioClip, the clip is treated as a MIDI clip\n * by the playout adapter.\n */\nexport interface MidiNoteData {\n /** MIDI note number (0-127) */\n midi: number;\n /** Note name in scientific pitch notation (\"C4\", \"G#3\") */\n name: string;\n /** Start time in seconds, relative to clip start */\n time: number;\n /** Duration in seconds */\n duration: number;\n /** Velocity (0-1 normalized) */\n velocity: number;\n /** MIDI channel (0-indexed). Channel 9 = GM percussion. Enables per-note routing in flattened tracks. */\n channel?: number;\n}\n\n/**\n * Utility: Get all clips within a sample range\n */\nexport function getClipsInRange(\n track: ClipTrack,\n startSample: number,\n endSample: number\n): AudioClip[] {\n return track.clips.filter((clip) => {\n const clipEnd = clip.startSample + clip.durationSamples;\n // Clip overlaps with range if:\n // - Clip starts before range ends AND\n // - Clip ends after range starts\n return clip.startSample < endSample && clipEnd > startSample;\n });\n}\n\n/**\n * Utility: Get all clips at a specific sample position\n */\nexport function getClipsAtSample(track: ClipTrack, sample: number): AudioClip[] {\n return track.clips.filter((clip) => {\n const clipEnd = clip.startSample + clip.durationSamples;\n return sample >= clip.startSample && sample < clipEnd;\n });\n}\n\n/**\n * Utility: Check if two clips overlap\n */\nexport function clipsOverlap(clip1: AudioClip, clip2: AudioClip): boolean {\n const clip1End = clip1.startSample + clip1.durationSamples;\n const clip2End = clip2.startSample + clip2.durationSamples;\n\n return clip1.startSample < clip2End && clip1End > clip2.startSample;\n}\n\n/**\n * Utility: Sort clips by startSample\n */\nexport function sortClipsByTime(clips: AudioClip[]): AudioClip[] {\n return [...clips].sort((a, b) => a.startSample - b.startSample);\n}\n\n/**\n * Utility: Find gaps between clips (silent regions)\n */\nexport interface Gap {\n startSample: number;\n endSample: number;\n durationSamples: number;\n}\n\nexport function findGaps(track: ClipTrack): Gap[] {\n if (track.clips.length === 0) return [];\n\n const sorted = sortClipsByTime(track.clips);\n const gaps: Gap[] = [];\n\n for (let i = 0; i < sorted.length - 1; i++) {\n const currentClipEnd = sorted[i].startSample + sorted[i].durationSamples;\n const nextClipStart = sorted[i + 1].startSample;\n\n if (nextClipStart > currentClipEnd) {\n gaps.push({\n startSample: currentClipEnd,\n endSample: nextClipStart,\n durationSamples: nextClipStart - currentClipEnd,\n });\n }\n }\n\n return gaps;\n}\n","/**\n * Peaks type - represents a typed array of interleaved min/max peak data\n */\nexport type Peaks = Int8Array | Int16Array;\n\n/**\n * Bits type - number of bits for peak data\n */\nexport type Bits = 8 | 16;\n\n/**\n * PeakData - result of peak extraction\n */\nexport interface PeakData {\n /** Number of peak pairs extracted */\n length: number;\n /** Array of peak data for each channel (interleaved min/max) */\n data: Peaks[];\n /** Bit depth of peak data */\n bits: Bits;\n}\n\nexport interface WaveformConfig {\n sampleRate: number;\n samplesPerPixel: number;\n waveHeight?: number;\n waveOutlineColor?: string;\n waveFillColor?: string;\n waveProgressColor?: string;\n}\n\nexport interface AudioBuffer {\n length: number;\n duration: number;\n numberOfChannels: number;\n sampleRate: number;\n getChannelData(channel: number): Float32Array;\n}\n\nexport interface Track {\n id: string;\n name: string;\n src?: string | AudioBuffer; // Support both URL strings and AudioBuffer objects\n gain: number;\n muted: boolean;\n soloed: boolean;\n stereoPan: number;\n startTime: number;\n endTime?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n cueIn?: number;\n cueOut?: number;\n}\n\n/**\n * Simple fade configuration\n */\nexport interface Fade {\n /** Duration of the fade in seconds */\n duration: number;\n /** Type of fade curve (default: 'linear') */\n type?: FadeType;\n}\n\nexport type FadeType = 'logarithmic' | 'linear' | 'sCurve' | 'exponential';\n\n/**\n * Alias for Fade — used by media-element-playout and playout packages\n */\nexport type FadeConfig = Fade;\n\nexport interface PlaylistConfig {\n samplesPerPixel?: number;\n waveHeight?: number;\n container?: HTMLElement;\n isAutomaticScroll?: boolean;\n timescale?: boolean;\n colors?: {\n waveOutlineColor?: string;\n waveFillColor?: string;\n waveProgressColor?: string;\n };\n controls?: {\n show?: boolean;\n width?: number;\n };\n zoomLevels?: number[];\n}\n\nexport interface PlayoutState {\n isPlaying: boolean;\n isPaused: boolean;\n cursor: number;\n duration: number;\n}\n\nexport interface TimeSelection {\n start: number;\n end: number;\n}\n\nexport enum InteractionState {\n Cursor = 'cursor',\n Select = 'select',\n Shift = 'shift',\n FadeIn = 'fadein',\n FadeOut = 'fadeout',\n}\n\n// Export clip-based model types\nexport * from './clip';\n\n// Export spectrogram types\nexport * from './spectrogram';\n\n// Export annotation types\nexport * from './annotations';\n","export function samplesToSeconds(samples: number, sampleRate: number): number {\n return samples / sampleRate;\n}\n\nexport function secondsToSamples(seconds: number, sampleRate: number): number {\n return Math.ceil(seconds * sampleRate);\n}\n\nexport function samplesToPixels(samples: number, samplesPerPixel: number): number {\n return Math.floor(samples / samplesPerPixel);\n}\n\nexport function pixelsToSamples(pixels: number, samplesPerPixel: number): number {\n return Math.floor(pixels * samplesPerPixel);\n}\n\nexport function pixelsToSeconds(\n pixels: number,\n samplesPerPixel: number,\n sampleRate: number\n): number {\n return (pixels * samplesPerPixel) / sampleRate;\n}\n\nexport function secondsToPixels(\n seconds: number,\n samplesPerPixel: number,\n sampleRate: number\n): number {\n return Math.ceil((seconds * sampleRate) / samplesPerPixel);\n}\n","/** Default PPQN matching Tone.js Transport (192 ticks per quarter note) */\nexport const PPQN = 192;\n\n/** Number of PPQN ticks per beat for the given time signature. */\nexport function ticksPerBeat(timeSignature: [number, number], ppqn = PPQN): number {\n const [, denominator] = timeSignature;\n return ppqn * (4 / denominator);\n}\n\n/** Number of PPQN ticks per bar for the given time signature. */\nexport function ticksPerBar(timeSignature: [number, number], ppqn = PPQN): number {\n const [numerator] = timeSignature;\n return numerator * ticksPerBeat(timeSignature, ppqn);\n}\n\n/** Convert PPQN ticks to sample count. Uses Math.round for integer sample alignment. */\nexport function ticksToSamples(\n ticks: number,\n bpm: number,\n sampleRate: number,\n ppqn = PPQN\n): number {\n return Math.round((ticks * 60 * sampleRate) / (bpm * ppqn));\n}\n\n/** Convert sample count to PPQN ticks. Inverse of ticksToSamples. */\nexport function samplesToTicks(\n samples: number,\n bpm: number,\n sampleRate: number,\n ppqn = PPQN\n): number {\n return Math.round((samples * ppqn * bpm) / (60 * sampleRate));\n}\n\n/** Snap a tick position to the nearest grid line (rounds to nearest). */\nexport function snapToGrid(ticks: number, gridSizeTicks: number): number {\n return Math.round(ticks / gridSizeTicks) * gridSizeTicks;\n}\n","const DEFAULT_FLOOR = -100;\n\n/**\n * Convert a dB value to a normalized range.\n *\n * Maps dB values linearly: floor → 0, 0 dB → 1.\n * Values above 0 dB map to > 1 (e.g., +5 dB → 1.05 with default floor).\n *\n * @param dB - Decibel value (typically -Infinity to +5)\n * @param floor - Minimum dB value mapped to 0. Default: -100 (Firefox compat)\n * @returns Normalized value (0 at floor, 1 at 0 dB, >1 above 0 dB)\n */\nexport function dBToNormalized(dB: number, floor: number = DEFAULT_FLOOR): number {\n if (Number.isNaN(dB)) {\n console.warn('[waveform-playlist] dBToNormalized received NaN');\n return 0;\n }\n if (floor >= 0) {\n console.warn('[waveform-playlist] dBToNormalized floor must be negative, got:', floor);\n return 0;\n }\n if (!isFinite(dB) || dB <= floor) return 0;\n return (dB - floor) / -floor;\n}\n\n/**\n * Convert a normalized value back to dB.\n *\n * Maps linearly: 0 → floor, 1 → 0 dB.\n * Values above 1 map to positive dB (e.g., 1.05 → +5 dB with default floor).\n *\n * @param normalized - Normalized value (0 = floor, 1 = 0 dB)\n * @param floor - Minimum dB value (maps from 0). Must be negative. Default: -100\n * @returns dB value (floor at 0, 0 dB at 1, positive dB above 1)\n */\nexport function normalizedToDb(normalized: number, floor: number = DEFAULT_FLOOR): number {\n if (!isFinite(normalized)) return floor;\n if (floor >= 0) {\n console.warn('[waveform-playlist] normalizedToDb floor must be negative, got:', floor);\n return DEFAULT_FLOOR;\n }\n const clamped = Math.max(0, normalized);\n return clamped * -floor + floor;\n}\n\n/**\n * Convert a linear gain value to decibels.\n *\n * @param gain - Linear gain (0 = silence, 1 = unity)\n * @returns Decibel value (e.g., 0.5 → ≈ -6.02 dB)\n */\nexport function gainToDb(gain: number): number {\n return 20 * Math.log10(Math.max(gain, 0.0001));\n}\n\n/**\n * Convert a linear gain value (0-1+) to normalized 0-1 via dB.\n *\n * Combines gain-to-dB (20 * log10) with dBToNormalized for a consistent\n * mapping from raw AudioWorklet peak/RMS values to the 0-1 range used\n * by UI meter components.\n *\n * @param gain - Linear gain value (typically 0 to 1, can exceed 1)\n * @param floor - Minimum dB value mapped to 0. Default: -100\n * @returns Normalized value (0 at silence/floor, 1 at 0 dB, >1 above 0 dB)\n */\nexport function gainToNormalized(gain: number, floor: number = DEFAULT_FLOOR): number {\n if (gain <= 0) return 0;\n // Use raw log10 (no clamp) — gain > 0 is guaranteed above,\n // and dBToNormalized handles -Infinity via its floor check.\n const db = 20 * Math.log10(gain);\n return dBToNormalized(db, floor);\n}\n","import { ticksPerBeat, ticksPerBar } from './beatsAndBars';\nimport type { MeterEntry } from './meterDetection';\n\nexport type { MeterEntry } from './meterDetection';\n\n/** All supported snap-to-grid values. */\nexport type SnapTo =\n | 'bar'\n | 'beat'\n | '1/2'\n | '1/4'\n | '1/8'\n | '1/16'\n | '1/32'\n | '1/2T'\n | '1/4T'\n | '1/8T'\n | '1/16T'\n | 'off';\n\n/**\n * Returns the tick interval for the given SnapTo value.\n *\n * Straight subdivisions (1/2, 1/4, 1/8, 1/16, 1/32) are always expressed as\n * fractions of a quarter note (ppqn), independent of the time signature\n * denominator. Triplet subdivisions use × 2/3 of the corresponding straight\n * value. 'bar' and 'beat' depend on the `timeSignature` argument (the\n * caller passes the meter entry active at the position).\n * 'off' returns 0.\n */\nexport function snapToTicks(snapTo: SnapTo, timeSignature: [number, number], ppqn = 960): number {\n const ts = timeSignature;\n switch (snapTo) {\n case 'bar':\n return ticksPerBar(ts, ppqn);\n case 'beat':\n return ticksPerBeat(ts, ppqn);\n case '1/2':\n return ppqn * 2;\n case '1/4':\n return ppqn;\n case '1/8':\n return ppqn / 2;\n case '1/16':\n return ppqn / 4;\n case '1/32':\n return ppqn / 8;\n case '1/2T':\n return Math.round((ppqn * 2 * 2) / 3);\n case '1/4T':\n return Math.round((ppqn * 2) / 3);\n case '1/8T':\n return Math.round((ppqn * 2) / 6);\n case '1/16T':\n return Math.round((ppqn * 2) / 12);\n case 'off':\n return 0;\n }\n}\n\n/**\n * Three-tier tick hierarchy (following Audacity's model):\n * major — Bar boundaries. Always labeled, strongest grid lines.\n * minor — Beat boundaries. Labeled when wide enough, medium grid lines.\n * minorMinor — Subdivisions (eighths, sixteenths). Never labeled, ruler ticks only (no grid).\n */\nexport type TickType = 'major' | 'minor' | 'minorMinor';\n\n/** Zoom level category used to select which subdivision to iterate at. */\nexport type ZoomLevel = 'coarse' | 'bar' | 'beat' | 'eighth' | 'sixteenth';\n\n/** A single musical tick with rendering metadata. */\nexport interface MusicalTick {\n /** Pixel position of the tick in the timeline. */\n pixel: number;\n /** Three-tier type: major (bar), minor (beat), minorMinor (subdivision). */\n type: TickType;\n /** Human-readable label. Present for major ticks always; minor ticks when zoomed in. */\n label?: string;\n /** 0-based global bar index (for alternating bar-level striping). */\n barIndex: number;\n}\n\n/** Result of computeMusicalTicks(). */\nexport interface MusicalTickData {\n ticks: MusicalTick[];\n pixelsPerQuarterNote: number;\n zoomLevel: ZoomLevel;\n /** At 'coarse' zoom: how many quarter notes between rendered tick lines. */\n coarseQuarterNoteStep?: number;\n}\n\n/** Parameters for computeMusicalTicks(). */\nexport interface MusicalTickParams {\n meterEntries: MeterEntry[];\n /** Ticks per pixel (zoom level — lower value = more zoomed in). */\n ticksPerPixel: number;\n startPixel: number;\n endPixel: number;\n /** Pulses per quarter note. Defaults to 960. */\n ppqn?: number;\n}\n\n/** Minimum pixels per musical unit before switching to a coarser zoom level. */\nexport const MIN_PIXELS_PER_UNIT = 8;\n\n/** Minimum pixels between beat labels for readable text. */\nconst MIN_PIXELS_PER_LABEL = 60;\n\n/**\n * Determines the zoom level and computes which tick lines to render for a\n * given viewport. Pure tick arithmetic — no BPM or sample rate required.\n *\n * Walks meter entries in segments, so bar/beat boundaries and labels are\n * correct across meter changes.\n */\nexport function computeMusicalTicks(params: MusicalTickParams): MusicalTickData {\n const { meterEntries, ticksPerPixel, startPixel, endPixel, ppqn = 960 } = params;\n\n const firstMeter = meterEntries[0] ?? { tick: 0, numerator: 4, denominator: 4 };\n\n // Guard against invalid inputs that would cause division by zero or infinite loops\n if (ticksPerPixel <= 0 || ppqn <= 0 || firstMeter.denominator <= 0) {\n return { ticks: [], pixelsPerQuarterNote: 0, zoomLevel: 'coarse' };\n }\n\n // pixelsPerQuarterNote is constant across meters — only depends on ppqn and zoom\n const pixelsPerQuarterNote = ppqn / ticksPerPixel;\n\n // All zoom thresholds derived from pixelsPerQuarterNote (meter-independent).\n // Quarter note subdivisions: half = 2×, eighth = 0.5×, sixteenth = 0.25×.\n // \"Bar\" threshold uses 4× quarter note (a 4/4 bar) — conservative minimum.\n const tpEighth = ppqn / 2;\n const tpSixteenth = ppqn / 4;\n const pixelsPerEighth = tpEighth / ticksPerPixel;\n const pixelsPerSixteenth = tpSixteenth / ticksPerPixel;\n\n let zoomLevel: ZoomLevel;\n if (pixelsPerQuarterNote * 4 < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'coarse';\n } else if (pixelsPerQuarterNote < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'bar';\n } else if (pixelsPerEighth < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'beat';\n } else if (pixelsPerSixteenth < MIN_PIXELS_PER_UNIT) {\n zoomLevel = 'eighth';\n } else {\n zoomLevel = 'sixteenth';\n }\n\n // Coarse step in quarter notes — meter-independent so all segments\n // render at the same visual density regardless of time signature.\n let coarseQuarterNoteStep: number | undefined;\n let coarseQuarterNotes = 0;\n if (zoomLevel === 'coarse') {\n coarseQuarterNotes = 2;\n while ((coarseQuarterNotes * ppqn) / ticksPerPixel < MIN_PIXELS_PER_UNIT) {\n coarseQuarterNotes *= 2;\n }\n coarseQuarterNoteStep = coarseQuarterNotes;\n }\n\n const startTick = startPixel * ticksPerPixel;\n const endTick = endPixel * ticksPerPixel;\n\n // Build the list of meter segments: [start, end) in ticks, with per-segment bar offset\n const segments: Array<{\n segmentStartTick: number;\n segmentEndTick: number;\n meter: MeterEntry;\n barOffset: number; // cumulative bar count before this segment\n }> = [];\n\n {\n let cumulativeBars = 0;\n for (let i = 0; i < meterEntries.length; i++) {\n const meter = meterEntries[i];\n const segmentStart = meter.tick;\n const segmentEnd =\n i + 1 < meterEntries.length ? meterEntries[i + 1].tick : Number.MAX_SAFE_INTEGER;\n\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n\n segments.push({\n segmentStartTick: segmentStart,\n segmentEndTick: segmentEnd,\n meter,\n barOffset: cumulativeBars,\n });\n\n // Count how many whole bars fit in this segment (for finite segments)\n if (segmentEnd !== Number.MAX_SAFE_INTEGER) {\n const segmentLen = segmentEnd - segmentStart;\n cumulativeBars += Math.floor(segmentLen / tpBar);\n }\n }\n }\n\n const ticks: MusicalTick[] = [];\n\n // Walk each meter segment and emit ticks within the visible range\n for (const { segmentStartTick, segmentEndTick, meter, barOffset } of segments) {\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBeat = ticksPerBeat(ts, ppqn);\n const tpBar = ticksPerBar(ts, ppqn);\n\n // Determine step size for this segment\n let stepTicks: number;\n if (zoomLevel === 'coarse') {\n stepTicks = coarseQuarterNotes * ppqn;\n } else if (zoomLevel === 'bar') {\n stepTicks = tpBar;\n } else if (zoomLevel === 'beat') {\n stepTicks = tpBeat;\n } else if (zoomLevel === 'eighth') {\n stepTicks = tpEighth;\n } else {\n stepTicks = tpSixteenth;\n }\n\n // Visible tick range of this segment. The first emitted step may sit\n // before segmentTickStart (its bar/segment anchor is off-screen); the\n // pixel guard below skips it.\n const segmentTickStart = Math.max(segmentStartTick, startTick);\n const segmentTickEnd = Math.min(segmentEndTick - 1, endTick);\n\n if (segmentTickStart > segmentTickEnd) {\n continue;\n }\n\n // Grid lines restart at each bar line (the rule snapTickToGrid and\n // @dawcore/transport's quantizeTick follow), so a step that does not\n // divide the bar — eighths in 7/16 — never crosses one. The coarse level\n // is meter-independent by design (constant visual density) and keeps\n // stepping from the segment start.\n const restartAtBar = zoomLevel !== 'coarse';\n const offsetIntoSegment = segmentTickStart - segmentStartTick;\n const anchorTick = restartAtBar\n ? segmentStartTick + Math.floor(offsetIntoSegment / tpBar) * tpBar\n : segmentStartTick;\n const firstStepTick =\n anchorTick + Math.floor((segmentTickStart - anchorTick) / stepTicks) * stepTicks;\n const nextGridTick = (tick: number): number => {\n const next = tick + stepTicks;\n if (!restartAtBar) return next;\n const nextBarTick =\n segmentStartTick + (Math.floor((tick - segmentStartTick) / tpBar) + 1) * tpBar;\n return Math.min(next, nextBarTick);\n };\n\n for (\n let tick = firstStepTick;\n tick <= segmentTickEnd && tick < segmentEndTick;\n tick = nextGridTick(tick)\n ) {\n const pixel = tick / ticksPerPixel;\n\n if (pixel < startPixel || pixel > endPixel) {\n continue;\n }\n\n // Classify into three-tier hierarchy\n const tickOffsetInSegment = tick - segmentStartTick;\n let type: TickType;\n if (tickOffsetInSegment % tpBar === 0) {\n type = 'major';\n } else if (tickOffsetInSegment % tpBeat === 0) {\n type = 'minor';\n } else {\n type = 'minorMinor';\n }\n\n // Cumulative bar index for zebra striping\n const barIndexInSegment = Math.floor(tickOffsetInSegment / tpBar);\n const barIndex = barOffset + barIndexInSegment;\n\n // Labels: major always, minor only when wide enough, minorMinor never\n let label: string | undefined;\n if (type === 'major') {\n label = `${barIndex + 1}`;\n } else if (type === 'minor' && tpBeat / ticksPerPixel >= MIN_PIXELS_PER_LABEL) {\n const beatInBar = Math.floor((tickOffsetInSegment % tpBar) / tpBeat) + 1;\n label = `${barIndex + 1}.${beatInBar}`;\n }\n\n ticks.push({ pixel, type, barIndex, ...(label !== undefined ? { label } : {}) });\n }\n }\n\n // Sort by pixel (segments are ordered, but floating point steps may cause slight reordering)\n ticks.sort((a, b) => a.pixel - b.pixel);\n\n const result: MusicalTickData = {\n ticks,\n pixelsPerQuarterNote,\n zoomLevel,\n ...(coarseQuarterNoteStep !== undefined ? { coarseQuarterNoteStep } : {}),\n };\n\n return result;\n}\n\n/**\n * Convert an absolute tick to a 1-based bar.beat position, honoring meter\n * changes. Bars/beats are counted per meter segment (the same walk\n * `computeMusicalTicks` uses to build its `barOffset` accumulator). Beat is\n * the integer beat the tick falls WITHIN (floor, 1-based) — a tick exactly on\n * a bar line is beat 1.\n *\n * Guards: empty `meterEntries` → treat as 4/4 from tick 0. `ppqn <= 0` →\n * returns `{ bar: 1, beat: 1 }` (division-by-zero guard, matches\n * `computeMusicalTicks`'s ppqn guard).\n */\nexport function ticksToBarBeat(\n tick: number,\n meterEntries: MeterEntry[],\n ppqn: number\n): { bar: number; beat: number } {\n if (ppqn <= 0) return { bar: 1, beat: 1 };\n\n const entries =\n meterEntries.length > 0 ? meterEntries : [{ tick: 0, numerator: 4, denominator: 4 }];\n\n let barOffset = 0;\n for (let i = 0; i < entries.length; i++) {\n const meter = entries[i];\n const segmentStart = meter.tick;\n const segmentEnd = i + 1 < entries.length ? entries[i + 1].tick : Number.MAX_SAFE_INTEGER;\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n const tpBeat = ticksPerBeat(ts, ppqn);\n\n if (tick >= segmentStart && tick < segmentEnd) {\n const offset = tick - segmentStart;\n const barIndexInSegment = Math.floor(offset / tpBar);\n const beatInBar = Math.floor((offset % tpBar) / tpBeat);\n return { bar: barOffset + barIndexInSegment + 1, beat: beatInBar + 1 };\n }\n\n if (segmentEnd !== Number.MAX_SAFE_INTEGER) {\n const segmentLen = segmentEnd - segmentStart;\n barOffset += Math.floor(segmentLen / tpBar);\n }\n }\n\n // tick precedes the first meter entry (non-standard input) — fall back to\n // the first meter's math from its own start tick.\n const first = entries[0];\n const ts: [number, number] = [first.numerator, first.denominator];\n const tpBar = ticksPerBar(ts, ppqn);\n const tpBeat = ticksPerBeat(ts, ppqn);\n const offset = tick - first.tick;\n const barIndexInSegment = Math.floor(offset / tpBar);\n const beatInBar = Math.floor((offset % tpBar) / tpBeat);\n return { bar: barIndexInSegment + 1, beat: beatInBar + 1 };\n}\n\n/**\n * Snaps a tick position to the nearest grid boundary defined by `snapTo`.\n *\n * Finds the meter entry active at the tick position, then the BAR containing\n * the tick, and snaps relative to that bar's start: grid lines restart at\n * each bar line (the same rule as `@dawcore/transport`'s `quantizeTick` and\n * the drawn ruler grid), so odd meters stay aligned — in 7/8 at 960 PPQN a\n * quarter-note grid is 0, 960, 1920, 2880 and then the bar line at 3360,\n * never 3840. A subdivision longer than the bar leaves only the bar lines.\n * An exact tie snaps up; a tick already on a line stays put. Unlike\n * `quantizeTick`, the result is not rounded (a fractional grid size at an\n * unusual PPQN gives a fractional tick), triplet steps use the rounded\n * `snapToTicks` value, negative ticks are accepted (the lattice extends\n * backwards) and meter entries need not sit on bar boundaries of the\n * preceding meter (the next line is capped at the following entry).\n *\n * Returns the original tick unchanged when `snapTo` is 'off'.\n */\nexport function snapTickToGrid(\n tick: number,\n snapTo: SnapTo,\n meterEntries: MeterEntry[],\n ppqn = 960\n): number {\n if (snapTo === 'off') return tick;\n\n // Find the active meter entry for this tick, and where the next one starts\n let meter = meterEntries[0] ?? { tick: 0, numerator: 4, denominator: 4 };\n let nextEntryTick = Infinity;\n for (const entry of meterEntries) {\n if (entry.tick <= tick) {\n meter = entry;\n } else {\n nextEntryTick = entry.tick;\n break;\n }\n }\n\n const ts: [number, number] = [meter.numerator, meter.denominator];\n const gridSize = snapToTicks(snapTo, ts, ppqn);\n if (gridSize <= 0) return tick;\n\n const barLength = ticksPerBar(ts, ppqn);\n if (!(barLength > 0)) {\n // Degenerate entry (numerator 0): no bars to anchor to — plain snap from\n // the entry rather than a NaN that would flow into clip positions.\n return meter.tick + Math.round((tick - meter.tick) / gridSize) * gridSize;\n }\n\n // Snap within the bar containing the tick; the line after the bar's last\n // whole subdivision is the next bar line — or the next meter entry, when\n // a hand-built map puts one off the bar grid (the drawn grid ends the\n // segment there too).\n const barStart = meter.tick + Math.floor((tick - meter.tick) / barLength) * barLength;\n const previous = barStart + Math.floor((tick - barStart) / gridSize) * gridSize;\n const next = Math.min(previous + gridSize, barStart + barLength, nextEntryTick);\n return tick - previous < next - tick ? previous : next;\n}\n","export interface MeterEntry {\n tick: number;\n numerator: number;\n denominator: number;\n}\n\n/**\n * Scans a beat number sequence and detects meter (time signature) changes.\n *\n * Each beat in the input has a `beat` number (1-indexed). When the beat resets\n * to 1, we count how many beats were in the previous bar and derive the numerator.\n *\n * @param beats - Array of beat events with `time` (seconds) and `beat` (1-indexed number).\n * @param firstBeatTick - The tick position of beats[0] on the timeline.\n * @param ppqn - Ticks per quarter note (ticks per beat).\n * @returns Array of MeterEntry sorted by tick. Always includes an entry at tick 0.\n */\nexport function detectMeterChanges(\n beats: { time: number; beat: number }[],\n firstBeatTick: number,\n ppqn: number\n): MeterEntry[] {\n const DEFAULT_NUMERATOR = 4;\n const DENOMINATOR = 4;\n\n const defaultResult: MeterEntry[] = [\n { tick: 0, numerator: DEFAULT_NUMERATOR, denominator: DENOMINATOR },\n ];\n\n if (beats.length === 0) {\n return defaultResult;\n }\n\n // Find the index of the first downbeat (beat === 1)\n const firstDownbeatIndex = beats.findIndex((b) => b.beat === 1);\n\n if (firstDownbeatIndex === -1) {\n // No downbeat found — default to 4/4\n return defaultResult;\n }\n\n // Collect completed bars: for each bar, record its start beat index and beat count\n const bars: { beatIndex: number; count: number }[] = [];\n let barStartBeatIndex = firstDownbeatIndex;\n\n for (let i = firstDownbeatIndex + 1; i < beats.length; i++) {\n if (beats[i].beat === 1) {\n bars.push({ beatIndex: barStartBeatIndex, count: i - barStartBeatIndex });\n barStartBeatIndex = i;\n }\n }\n\n if (bars.length === 0) {\n // Only one downbeat observed — can't determine meter\n return defaultResult;\n }\n\n // Build raw meter entries: emit a new entry only when numerator changes\n const rawEntries: MeterEntry[] = [];\n let prevNumerator = -1;\n\n for (const bar of bars) {\n const numerator = bar.count;\n if (numerator !== prevNumerator) {\n const tick = firstBeatTick + bar.beatIndex * ppqn;\n rawEntries.push({ tick, numerator, denominator: DENOMINATOR });\n prevNumerator = numerator;\n }\n }\n\n // Ensure tick 0 is always present\n if (rawEntries.length === 0) {\n return defaultResult;\n }\n\n if (rawEntries[0].tick === 0) {\n return rawEntries;\n }\n\n // First entry is after tick 0 — prepend tick 0 with the same numerator\n const tick0Entry: MeterEntry = {\n tick: 0,\n numerator: rawEntries[0].numerator,\n denominator: DENOMINATOR,\n };\n\n // If the first raw entry has the same numerator as tick 0, we don't need it as a\n // separate entry (they'd be adjacent duplicates). Drop the first raw entry and use\n // the tick-0 entry to represent it.\n const rest = rawEntries[0].numerator === tick0Entry.numerator ? rawEntries.slice(1) : rawEntries;\n\n return [tick0Entry, ...rest];\n}\n","/**\n * Peak generation for real-time waveform visualization during recording.\n * Matches the format used by webaudio-peaks: min/max pairs with bit depth.\n */\n\n/**\n * Generate peaks from audio samples in standard min/max pair format.\n *\n * @param samples - Audio samples to process\n * @param samplesPerPixel - Number of samples to represent in each peak\n * @param bits - Bit depth for peak values (8 or 16)\n * @returns Int8Array or Int16Array of peak values (min/max pairs)\n */\nexport function generatePeaks(\n samples: Float32Array,\n samplesPerPixel: number,\n bits: 8 | 16 = 16\n): Int8Array | Int16Array {\n const numPeaks = Math.ceil(samples.length / samplesPerPixel);\n const peakArray = bits === 8 ? new Int8Array(numPeaks * 2) : new Int16Array(numPeaks * 2);\n const maxValue = 2 ** (bits - 1);\n\n for (let i = 0; i < numPeaks; i++) {\n const start = i * samplesPerPixel;\n const end = Math.min(start + samplesPerPixel, samples.length);\n\n let min = 0;\n let max = 0;\n\n for (let j = start; j < end; j++) {\n const value = samples[j];\n if (value < min) min = value;\n if (value > max) max = value;\n }\n\n // Store as min/max pairs scaled to bit depth\n // Clamp to valid range: Int16 is [-32768, 32767], Int8 is [-128, 127]\n peakArray[i * 2] = Math.max(-maxValue, Math.floor(min * maxValue));\n peakArray[i * 2 + 1] = Math.min(maxValue - 1, Math.floor(max * maxValue));\n }\n\n return peakArray;\n}\n\n/**\n * Append new peaks to existing peaks array.\n * This is used for incremental peak updates during recording.\n */\nexport function appendPeaks(\n existingPeaks: Int8Array | Int16Array,\n newSamples: Float32Array,\n samplesPerPixel: number,\n totalSamplesProcessed: number,\n bits: 8 | 16 = 16\n): Int8Array | Int16Array {\n const maxValue = 2 ** (bits - 1);\n\n // Check if we have a partial peak from the last update\n const remainder = totalSamplesProcessed % samplesPerPixel;\n let offset = 0;\n\n // If there's a partial peak, we need to update the last peak\n if (remainder > 0 && existingPeaks.length > 0) {\n const samplesToComplete = samplesPerPixel - remainder;\n const endIndex = Math.min(samplesToComplete, newSamples.length);\n\n // Get current min/max from last peak\n let min = existingPeaks[existingPeaks.length - 2] / maxValue;\n let max = existingPeaks[existingPeaks.length - 1] / maxValue;\n\n // Update with new samples\n for (let i = 0; i < endIndex; i++) {\n const value = newSamples[i];\n if (value < min) min = value;\n if (value > max) max = value;\n }\n\n // Update last peak\n const updated = new (bits === 8 ? Int8Array : Int16Array)(existingPeaks.length);\n updated.set(existingPeaks);\n updated[existingPeaks.length - 2] = Math.max(-maxValue, Math.floor(min * maxValue));\n updated[existingPeaks.length - 1] = Math.min(maxValue - 1, Math.floor(max * maxValue));\n\n offset = endIndex;\n\n // Generate peaks for remaining samples and concatenate\n const newPeaks = generatePeaks(newSamples.slice(offset), samplesPerPixel, bits);\n const result = new (bits === 8 ? Int8Array : Int16Array)(updated.length + newPeaks.length);\n result.set(updated);\n result.set(newPeaks, updated.length);\n return result;\n }\n\n // No partial peak, just concatenate\n const newPeaks = generatePeaks(newSamples.slice(offset), samplesPerPixel, bits);\n const result = new (bits === 8 ? Int8Array : Int16Array)(existingPeaks.length + newPeaks.length);\n result.set(existingPeaks);\n result.set(newPeaks, existingPeaks.length);\n return result;\n}\n","/**\n * Utility functions for working with AudioBuffers during recording\n */\n\n/**\n * Concatenate multiple Float32Arrays into a single array\n */\nexport function concatenateAudioData(chunks: Float32Array[]): Float32Array {\n const totalLength = chunks.reduce((sum, chunk) => sum + chunk.length, 0);\n const result = new Float32Array(totalLength);\n\n let offset = 0;\n for (const chunk of chunks) {\n result.set(chunk, offset);\n offset += chunk.length;\n }\n\n return result;\n}\n\n/**\n * Convert channel data to AudioBuffer.\n * Accepts either per-channel Float32Array[] or a single Float32Array (mono, backwards compatible).\n */\nexport function createAudioBuffer(\n audioContext: AudioContext,\n channelData: Float32Array[] | Float32Array,\n sampleRate: number,\n channelCount: number = 1\n): AudioBuffer {\n // Backwards compatibility: single Float32Array → wrap as mono\n const channels: Float32Array[] =\n channelData instanceof Float32Array ? [channelData] : channelData;\n\n const length = channels[0]?.length ?? 0;\n const buffer = audioContext.createBuffer(channelCount, length, sampleRate);\n\n for (let ch = 0; ch < Math.min(channelCount, channels.length); ch++) {\n buffer.copyToChannel(new Float32Array(channels[ch]), ch);\n }\n\n return buffer;\n}\n\n/**\n * Append new samples to an existing AudioBuffer (mono convenience)\n */\nexport function appendToAudioBuffer(\n audioContext: AudioContext,\n existingBuffer: AudioBuffer | null,\n newSamples: Float32Array,\n sampleRate: number\n): AudioBuffer {\n if (!existingBuffer) {\n return createAudioBuffer(audioContext, [newSamples], sampleRate);\n }\n\n // Get existing samples\n const existingData = existingBuffer.getChannelData(0);\n\n // Concatenate using concatenateAudioData helper\n const combined = concatenateAudioData([existingData, newSamples]);\n\n // Create new buffer\n return createAudioBuffer(audioContext, [combined], sampleRate);\n}\n","/**\n * Sample count corresponding to the audible-latency window\n * (`outputLatency` + scheduler `lookAhead`). Used to skip leading silence in\n * recordings: between record-start and audible playback the user heard nothing,\n * so that prefix should be trimmed from buffers / peaks. Returns 0 for\n * non-finite or non-positive inputs.\n *\n * Single source of truth for `useIntegratedRecording` (buffer trim) and\n * the view's recording preview (live preview peak slice). Keep the two in lockstep\n * so the live preview width matches the finalized clip.\n */\nexport function audibleLatencySamples(\n outputLatency: number,\n lookAhead: number,\n sampleRate: number\n): number {\n const total = outputLatency + lookAhead;\n if (!Number.isFinite(total) || !Number.isFinite(sampleRate)) return 0;\n if (total <= 0 || sampleRate <= 0) return 0;\n return Math.floor(total * sampleRate);\n}\n\n/**\n * Resolve the recording latency offset in samples.\n *\n * When `overrideSeconds` is provided it is an **absolute replacement** for the\n * auto-computed value — a latency in seconds, converted at `sampleRate`\n * (`0` disables compensation; negative/non-finite resolve to `0`). Otherwise the\n * offset is the auto-computed audible-latency window (`outputLatency + lookAhead`).\n *\n * Single source of truth for the override-vs-auto decision across dawcore\n * (`RecordingController`) and React (`useIntegratedRecording` finalization +\n * the view's live preview). The override branch is the same math as\n * the auto branch with `lookAhead = 0`, so both inherit the finite/positive\n * guards in `audibleLatencySamples`.\n */\nexport function resolveRecordingOffsetSamples(params: {\n /** Public override (seconds). Absolute replacement when defined. */\n overrideSeconds?: number;\n /** Browser-reported output latency (seconds). */\n outputLatency: number;\n /** Scheduler look-ahead (seconds). Pass 0 for engines without one (native transport). */\n lookAhead: number;\n /** Sample rate the recording was captured at. */\n sampleRate: number;\n}): number {\n const { overrideSeconds, outputLatency, lookAhead, sampleRate } = params;\n return overrideSeconds !== undefined\n ? audibleLatencySamples(overrideSeconds, 0, sampleRate)\n : audibleLatencySamples(outputLatency, lookAhead, sampleRate);\n}\n","import type { SpectrogramConfig, ColorMapValue } from '../types/spectrogram';\n\n/**\n * Default values for `SpectrogramConfig` fields. Used by both the orchestrator\n * and the React controller so defaults can't drift between layers.\n *\n * Intentionally omitted:\n * - `maxFrequency` — defaults to `sampleRate / 2` at compute time (clip-dependent)\n * - `alpha` — window-specific (only used by the `hamming` window function); its\n * canonical default (0.54) lives in `windowFunctions.ts` where the math is\n * - `labelsColor`, `labelsBackground` — kept as optional `undefined` so consumers\n * can opt into label styling without forcing a color value\n */\nexport const SPECTROGRAM_DEFAULTS: Required<\n Omit<SpectrogramConfig, 'maxFrequency' | 'alpha' | 'labelsColor' | 'labelsBackground'>\n> & {\n labelsColor: string | undefined;\n labelsBackground: string | undefined;\n} = {\n fftSize: 2048,\n hopSize: 512,\n windowFunction: 'hann',\n frequencyScale: 'mel',\n minFrequency: 0,\n gainDb: 20,\n rangeDb: 80,\n zeroPaddingFactor: 2,\n labels: false,\n labelsColor: undefined,\n labelsBackground: undefined,\n};\n\n/** Default color map when none is specified. */\nexport const DEFAULT_SPECTROGRAM_COLOR_MAP: ColorMapValue = 'viridis';\n","/**\n * Punch-in replace: carve a sample range out of a clip list.\n *\n * Used when a newly recorded clip lands at the playhead and must REPLACE any\n * existing clip content between its start and end (issue #579): partial\n * overlaps are trimmed, fully-covered clips are removed, and a clip that\n * spans the whole range is split into two.\n */\n\nimport type { AudioClip } from '../types/clip';\n\n/**\n * Return a new clip list with the sample range [rangeStart, rangeEnd)\n * removed from every clip that overlaps it.\n *\n * - Clips outside the range are returned by reference (untouched).\n * - Clips fully inside the range are dropped.\n * - A clip overlapping only the range's start keeps its head (right-trim).\n * - A clip overlapping only the range's end keeps its tail: its start moves\n * to rangeEnd and `offsetSamples` advances by the carved amount.\n * - A clip containing the whole range splits into head + tail; the tail is a\n * new clip (deterministic id `<original>-carve-<rangeEnd>`) sharing the\n * same audioBuffer.\n *\n * Clips whose `startSample` changes lose their `startTick` — a sample-space\n * carve cannot recompute ticks, and the engine re-enriches clips without\n * `startTick` on ingestion (see AudioClip.startTick).\n *\n * Pure and immutable: input clips are never mutated. An empty or inverted\n * range returns the input list unchanged.\n */\nexport function carveClipRange(\n clips: readonly AudioClip[],\n rangeStart: number,\n rangeEnd: number\n): AudioClip[] {\n if (!(rangeEnd > rangeStart)) {\n return [...clips];\n }\n\n const result: AudioClip[] = [];\n\n for (const clip of clips) {\n const clipStart = clip.startSample;\n const clipEnd = clip.startSample + clip.durationSamples;\n\n // [start, end) overlap test — shared boundaries don't overlap\n if (clipEnd <= rangeStart || clipStart >= rangeEnd) {\n result.push(clip);\n continue;\n }\n\n const keepHead = clipStart < rangeStart;\n const keepTail = clipEnd > rangeEnd;\n\n if (keepHead) {\n result.push({\n ...clip,\n durationSamples: rangeStart - clipStart,\n });\n }\n\n if (keepTail) {\n const carvedFromClipStart = rangeEnd - clipStart;\n const tail: AudioClip = {\n ...clip,\n // Head + tail from one clip must not share an id\n id: keepHead ? `${clip.id}-carve-${rangeEnd}` : clip.id,\n startSample: rangeEnd,\n durationSamples: clipEnd - rangeEnd,\n offsetSamples: clip.offsetSamples + carvedFromClipStart,\n };\n // startSample changed — the stale authoritative tick position must not\n // survive (the engine re-derives it from startSample on ingestion).\n delete tail.startTick;\n result.push(tail);\n }\n\n // Neither head nor tail: fully covered, dropped.\n }\n\n return result;\n}\n","import { gainToNormalized } from './dBUtils';\nimport type { MeterLevels } from '../valueSource';\n\n/** Exponential decay per reading for the smoothed peak (~800 ms to 1/e at 60 Hz). */\nexport const METER_PEAK_DECAY = 0.98;\n\nexport interface MeterReading {\n /** Raw-gain smoothed peak per metered channel; pass back in with the next message. */\n smoothedPeaks: number[];\n /** The levels to show. */\n levels: MeterLevels;\n}\n\nexport interface ReadMeterMessageParams {\n /**\n * A meter worklet message: N peak gains followed by N RMS gains.\n */\n data: ArrayLike<number>;\n /** `smoothedPeaks` from the previous reading (empty for the first). */\n previousSmoothedPeaks: readonly number[];\n /** `levels.peakLevels` from the previous reading (empty after a reset). */\n heldPeakLevels: readonly number[];\n /**\n * When the message has fewer channels than this, channel 0 is repeated to\n * fill it (a mono microphone shown on a stereo meter). Default: 0.\n */\n minChannels?: number;\n}\n\n/**\n * Turn one meter worklet message into display levels: the peak jumps up at\n * once and decays slowly, RMS is passed through, and the held peak keeps the\n * highest level seen. Pure: nothing passed in is modified.\n */\nexport function readMeterMessage({\n data,\n previousSmoothedPeaks,\n heldPeakLevels,\n minChannels = 0,\n}: ReadMeterMessageParams): MeterReading {\n const channels = Math.floor(data.length / 2);\n const smoothedPeaks: number[] = [];\n const peaks: number[] = [];\n const rms: number[] = [];\n\n for (let ch = 0; ch < channels; ch++) {\n const smoothed = Math.max(data[ch], (previousSmoothedPeaks[ch] ?? 0) * METER_PEAK_DECAY);\n smoothedPeaks.push(smoothed);\n peaks.push(gainToNormalized(smoothed));\n rms.push(gainToNormalized(data[channels + ch]));\n }\n\n const mirror = channels > 0 && channels < minChannels;\n const levels = mirror ? new Array<number>(minChannels).fill(peaks[0]) : peaks;\n const rmsLevels = mirror ? new Array<number>(minChannels).fill(rms[0]) : rms;\n const peakLevels = levels.map((level, i) => Math.max(heldPeakLevels[i] ?? 0, level));\n\n return { smoothedPeaks, levels: { levels, peakLevels, rmsLevels } };\n}\n","import type { AudioClip } from './types';\n\n/** Clip start position in seconds */\nexport function clipStartTime(clip: AudioClip): number {\n return clip.startSample / clip.sampleRate;\n}\n\n/** Clip end position in seconds (start + duration) */\nexport function clipEndTime(clip: AudioClip): number {\n return (clip.startSample + clip.durationSamples) / clip.sampleRate;\n}\n\n/** Clip offset into source audio in seconds */\nexport function clipOffsetTime(clip: AudioClip): number {\n return clip.offsetSamples / clip.sampleRate;\n}\n\n/** Clip duration in seconds */\nexport function clipDurationTime(clip: AudioClip): number {\n return clip.durationSamples / clip.sampleRate;\n}\n\n/** The part of a track `trackChannelCount` reads — `ClipTrack` satisfies it. */\nexport interface TrackChannelSource {\n clips: ReadonlyArray<{ audioBuffer?: { numberOfChannels: number } }>;\n}\n\n/**\n * Max audio channel count across a track's clips (1 for a track with no\n * decoded audio). Read for the React export's output channels. The track's\n * pan law is not chosen from it: that is `trackPanLaw(track)` (#684).\n */\nexport function trackChannelCount(track: TrackChannelSource): number {\n return track.clips.reduce(\n (max, clip) => Math.max(max, clip.audioBuffer?.numberOfChannels ?? 1),\n 1\n );\n}\n\n/**\n * Clip width in pixels at a given samplesPerPixel.\n * Shared by Clip.tsx (container sizing) and ChannelWithProgress.tsx (progress overlay)\n * to ensure pixel-perfect alignment. Floor-based endpoint subtraction guarantees\n * adjacent clips have no pixel gaps.\n */\nexport function clipPixelWidth(\n startSample: number,\n durationSamples: number,\n samplesPerPixel: number\n): number {\n return (\n Math.floor((startSample + durationSamples) / samplesPerPixel) -\n Math.floor(startSample / samplesPerPixel)\n );\n}\n","import type { AudioClip, ClipTrack, TrackKind } from './types';\n\n/**\n * What a clip is: MIDI when it carries `midiNotes` (an empty array included),\n * audio otherwise (decoded, or peaks-only before the decode finishes).\n */\nexport function clipKind(clip: Pick<AudioClip, 'midiNotes'>): TrackKind {\n return clip.midiNotes != null ? 'midi' : 'audio';\n}\n\n/**\n * A track's kind. `kind` is required by the type; a track built in plain\n * JavaScript without it is read as audio.\n */\nexport function trackKind(track: Pick<ClipTrack, 'kind'>): TrackKind {\n return track.kind ?? 'audio';\n}\n\nfunction label(named: { id: string; name?: string }): string {\n return '\"' + (named.name || named.id) + '\"';\n}\n\n/**\n * Throws unless every clip on the track is of the track's kind. A track holds\n * audio clips or MIDI clips, never both (#756): the engine calls this wherever\n * a track enters it, so a mixed track cannot reach a playout adapter.\n */\nexport function assertTrackKind(track: ClipTrack): void {\n const kind = trackKind(track);\n if (kind !== 'audio' && kind !== 'midi') {\n throw new Error(\n '[waveform-playlist] Track ' +\n label(track) +\n ' has kind \"' +\n String(kind) +\n \"\\\"; a track's kind is 'audio' or 'midi'.\"\n );\n }\n const stray = track.clips.find((clip) => clipKind(clip) !== kind);\n if (!stray) return;\n\n const strayKind = clipKind(stray);\n const fix =\n track.kind === undefined\n ? \"The track has no kind, which is read as 'audio': set kind: 'midi' on a track of MIDI clips.\"\n : 'A track holds one kind of clip: put the clip on a track of its own kind' +\n ' (splitTrackByKind() splits a track that has both).';\n throw new Error(\n '[waveform-playlist] Track ' +\n label(track) +\n ' is an ' +\n kind +\n ' track but its clip ' +\n label(stray) +\n ' is ' +\n (strayKind === 'audio' ? 'an audio' : 'a midi') +\n ' clip. ' +\n fix\n );\n}\n\n/**\n * Splits a track by the kind of its clips, for data from before tracks had a\n * kind. A track whose clips are all of one kind comes back as one track with\n * that kind (an empty track keeps the kind it has). A track holding both comes\n * back as two: the audio track keeps the id, the MIDI track gets `midiTrackId`\n * (default: the id + '-midi') and copies of the name, volume, pan, mute and solo.\n */\nexport function splitTrackByKind(\n // `kind` optional: data saved before tracks had a kind does not have one.\n track: Omit<ClipTrack, 'kind'> & { kind?: TrackKind },\n midiTrackId: string = track.id + '-midi'\n): ClipTrack[] {\n const audioClips = track.clips.filter((clip) => clipKind(clip) === 'audio');\n const midiClips = track.clips.filter((clip) => clipKind(clip) === 'midi');\n\n if (midiClips.length === 0) {\n return [{ ...track, kind: track.clips.length === 0 ? (track.kind ?? 'audio') : 'audio' }];\n }\n if (audioClips.length === 0) {\n return [{ ...track, kind: 'midi' }];\n }\n return [\n { ...track, kind: 'audio', clips: audioClips },\n { ...track, id: midiTrackId, kind: 'midi', clips: midiClips },\n ];\n}\n","/**\n * Canonical spectrogram canvas-ID contract.\n *\n * Spectrogram canvases are identified by `${clipId}-ch${channelIndex}-chunk${chunkIndex}`.\n * This format is produced (builders) and consumed (parsers) by several packages\n * — the React `SpectrogramProvider`/`SpectrogramChannel`, the `<daw-spectrogram>`\n * Lit element, and the `@dawcore/spectrogram` worker pool. Single-sourcing the\n * build + parse here prevents the drift class where a format change lands in some\n * sites but not others (the pool's no-match fallback then routes every channel to\n * worker 0 → channel 0's data rendered for all channels — #556).\n *\n * `@waveform-playlist/core` is the home because it is zero-dependency and already\n * a dependency of every producer and consumer (unlike `@dawcore/spectrogram`,\n * which `@waveform-playlist/ui-components` does not depend on). The format is a\n * pure string contract with no FFT/compute dependency.\n */\n\n/**\n * What a spectrogram canvas registers with: the canvas handed over to the\n * worker and where it sits. Declared here, once, because the component that\n * registers (`SpectrogramChannel` in ui-components), the context that carries\n * the call (browser) and the provider that receives it (spectrogram) are three\n * packages that all depend on core.\n *\n * The receiver looks the track up from `clipId` and derives the canvas's pixel\n * offset from `chunkIndex`.\n *\n * A canvas registers with the range of the audio it is drawn for: the view\n * may draw a clip with a geometry the tracks do not have yet (a trim being\n * dragged), so the receiver draws `offsetSamples` / `durationSamples` from\n * here and falls back to the clip's own when a registration has none. A canvas\n * is registered once, so a new range means new canvases (`SpectrogramChannel`\n * keys them on it).\n */\nexport interface SpectrogramCanvasRegistration {\n canvasId: string;\n canvas: OffscreenCanvas;\n clipId: string;\n channelIndex: number;\n chunkIndex: number;\n widthPx: number;\n heightPx: number;\n /** Where in the audio the drawn clip starts, in samples. Omitted: the clip's own. */\n offsetSamples?: number;\n /** How much of the audio the drawn clip covers, in samples. Omitted: the clip's own. */\n durationSamples?: number;\n}\n\nexport interface SpectrogramCanvasIdParts {\n clipId: string;\n channelIndex: number;\n chunkIndex: number;\n}\n\n/**\n * Anchored to the trailing `-ch{N}-chunk{M}` segment. The greedy first group lets\n * the clip ID contain hyphens — and even a `-ch{N}-chunk{M}`-looking substring —\n * without misrouting: it always binds to the LAST such segment.\n */\nconst CANVAS_ID_RE = /^(.+)-ch(\\d+)-chunk(\\d+)$/;\n\n/** Build a spectrogram canvas ID from its parts. */\nexport function buildSpectrogramCanvasId(parts: SpectrogramCanvasIdParts): string {\n return `${parts.clipId}-ch${parts.channelIndex}-chunk${parts.chunkIndex}`;\n}\n\n/**\n * Parse a spectrogram canvas ID into its parts, or `null` when it doesn't match\n * the `${clipId}-ch${channelIndex}-chunk${chunkIndex}` format.\n */\nexport function parseSpectrogramCanvasId(canvasId: string): SpectrogramCanvasIdParts | null {\n const match = canvasId.match(CANVAS_ID_RE);\n if (!match) return null;\n return {\n clipId: match[1],\n channelIndex: parseInt(match[2], 10),\n chunkIndex: parseInt(match[3], 10),\n };\n}\n","/**\n * Fade curve utilities for Web Audio API\n *\n * Pure functions that generate fade curves and apply them to AudioParam.\n * No Tone.js dependency — works with native Web Audio nodes.\n */\n\nimport type { FadeType } from './types';\n\n/**\n * Generate a linear fade curve\n */\nexport function linearCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const scale = length - 1;\n\n for (let i = 0; i < length; i++) {\n const x = i / scale;\n curve[i] = fadeIn ? x : 1 - x;\n }\n\n return curve;\n}\n\n/**\n * Generate an exponential fade curve\n */\nexport function exponentialCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const scale = length - 1;\n\n for (let i = 0; i < length; i++) {\n const x = i / scale;\n const index = fadeIn ? i : length - 1 - i;\n curve[index] = Math.exp(2 * x - 1) / Math.E;\n }\n\n return curve;\n}\n\n/**\n * Generate an S-curve (sine-based smooth curve)\n */\nexport function sCurveCurve(length: number, fadeIn: boolean): Float32Array {\n const curve = new Float32Array(length);\n const phase = fadeIn ? Math.PI / 2 : -Math.PI / 2;\n\n for (let i = 0; i < length; i++) {\n curve[i] = Math.sin((Math.PI * i) / length - phase) / 2 + 0.5;\n }\n\n return curve;\n}\n\n/**\n * Generate a logarithmic fade curve\n */\nexport function logarithmicCurve(length: number, fadeIn: boolean, base: number = 10): Float32Array {\n const curve = new Float32Array(length);\n\n for (let i = 0; i < length; i++) {\n const index = fadeIn ? i : length - 1 - i;\n const x = i / length;\n curve[index] = Math.log(1 + base * x) / Math.log(1 + base);\n }\n\n return curve;\n}\n\n/**\n * Generate a fade curve of the specified type\n */\nexport function generateCurve(type: FadeType, length: number, fadeIn: boolean): Float32Array {\n switch (type) {\n case 'linear':\n return linearCurve(length, fadeIn);\n case 'exponential':\n return exponentialCurve(length, fadeIn);\n case 'sCurve':\n return sCurveCurve(length, fadeIn);\n case 'logarithmic':\n return logarithmicCurve(length, fadeIn);\n default:\n return linearCurve(length, fadeIn);\n }\n}\n\n/**\n * Apply a fade in to an AudioParam\n *\n * @param param - The AudioParam to apply the fade to (usually gain)\n * @param startTime - When the fade starts (in seconds, AudioContext time)\n * @param duration - Duration of the fade in seconds\n * @param type - Type of fade curve\n * @param startValue - Starting value (default: 0)\n * @param endValue - Ending value (default: 1)\n */\nexport function applyFadeIn(\n param: AudioParam,\n startTime: number,\n duration: number,\n type: FadeType = 'linear',\n startValue: number = 0,\n endValue: number = 1\n): void {\n if (duration <= 0) return;\n\n if (type === 'linear') {\n param.setValueAtTime(startValue, startTime);\n param.linearRampToValueAtTime(endValue, startTime + duration);\n } else if (type === 'exponential') {\n param.setValueAtTime(Math.max(startValue, 0.001), startTime);\n param.exponentialRampToValueAtTime(Math.max(endValue, 0.001), startTime + duration);\n } else {\n const curve = generateCurve(type, 10000, true);\n const scaledCurve = new Float32Array(curve.length);\n const range = endValue - startValue;\n for (let i = 0; i < curve.length; i++) {\n scaledCurve[i] = startValue + curve[i] * range;\n }\n param.setValueCurveAtTime(scaledCurve, startTime, duration);\n }\n}\n\n/**\n * Apply a fade out to an AudioParam\n *\n * @param param - The AudioParam to apply the fade to (usually gain)\n * @param startTime - When the fade starts (in seconds, AudioContext time)\n * @param duration - Duration of the fade in seconds\n * @param type - Type of fade curve\n * @param startValue - Starting value (default: 1)\n * @param endValue - Ending value (default: 0)\n */\nexport function applyFadeOut(\n param: AudioParam,\n startTime: number,\n duration: number,\n type: FadeType = 'linear',\n startValue: number = 1,\n endValue: number = 0\n): void {\n if (duration <= 0) return;\n\n if (type === 'linear') {\n param.setValueAtTime(startValue, startTime);\n param.linearRampToValueAtTime(endValue, startTime + duration);\n } else if (type === 'exponential') {\n param.setValueAtTime(Math.max(startValue, 0.001), startTime);\n param.exponentialRampToValueAtTime(Math.max(endValue, 0.001), startTime + duration);\n } else {\n const curve = generateCurve(type, 10000, false);\n const scaledCurve = new Float32Array(curve.length);\n const range = startValue - endValue;\n for (let i = 0; i < curve.length; i++) {\n scaledCurve[i] = endValue + curve[i] * range;\n }\n param.setValueCurveAtTime(scaledCurve, startTime, duration);\n }\n}\n","/**\n * Framework-agnostic keyboard shortcut handling.\n * Used by both React (useKeyboardShortcuts) and Web Components (daw-editor).\n */\n\nexport interface KeyboardShortcut {\n key: string;\n ctrlKey?: boolean;\n shiftKey?: boolean;\n metaKey?: boolean;\n altKey?: boolean;\n action: () => void;\n description?: string;\n preventDefault?: boolean;\n}\n\n/** A key + modifier combination, without an action. Used for remapping maps. */\nexport type KeyBinding = Pick<\n KeyboardShortcut,\n 'key' | 'ctrlKey' | 'shiftKey' | 'metaKey' | 'altKey'\n>;\n\n/**\n * Does a keyboard event match a key binding?\n * `undefined` modifier = match any state; `false` = must NOT be pressed.\n */\nexport function matchesKeyBinding(event: KeyboardEvent, binding: KeyBinding): boolean {\n const keyMatch =\n event.key.toLowerCase() === binding.key.toLowerCase() || event.key === binding.key;\n const ctrlMatch = binding.ctrlKey === undefined || event.ctrlKey === binding.ctrlKey;\n const shiftMatch = binding.shiftKey === undefined || event.shiftKey === binding.shiftKey;\n const metaMatch = binding.metaKey === undefined || event.metaKey === binding.metaKey;\n const altMatch = binding.altKey === undefined || event.altKey === binding.altKey;\n return keyMatch && ctrlMatch && shiftMatch && metaMatch && altMatch;\n}\n\nconst ELEMENT_NODE = 1;\n\n/**\n * The elements the event passed through, innermost first. `event.target` is\n * retargeted to the shadow host for a listener outside a shadow root, so the\n * composed path is the only way to see a control inside a web component.\n */\nfunction elementPath(event: KeyboardEvent): Element[] {\n const composed = typeof event.composedPath === 'function' ? event.composedPath() : [];\n if (composed.length > 0) {\n return composed.filter(\n (node): node is Element => (node as Node | null)?.nodeType === ELEMENT_NODE\n );\n }\n // Not dispatched (or no composedPath): walk up from the target.\n const path: Element[] = [];\n let current = event.target as Element | null;\n while (current && current.nodeType === ELEMENT_NODE) {\n path.push(current);\n current = current.parentElement;\n }\n return path;\n}\n\n/** `element.matches(selector)`, or `fallback` where the selector is not supported. */\nfunction matchesOr(element: Element, selector: string, fallback: boolean): boolean {\n try {\n return element.matches(selector);\n } catch {\n return fallback;\n }\n}\n\n/**\n * Controls that take text or use many keys themselves (every `<input>` type,\n * including sliders and checkboxes): no shortcut fires on them.\n */\nfunction ownsAllKeys(element: Element): boolean {\n const tag = element.tagName;\n return (\n tag === 'INPUT' ||\n tag === 'TEXTAREA' ||\n tag === 'SELECT' ||\n (element as HTMLElement).isContentEditable === true\n );\n}\n\n/**\n * Does `key` activate this native control? Buttons and `<summary>` take Space\n * and Enter; a link takes Enter only (Space on a link scrolls the page, so\n * yielding it would lose the shortcut for nothing). A disabled button takes\n * neither.\n *\n * ARIA-role widgets (`role=\"button\"` on a div) are left out on purpose: whether\n * they respond to a key is up to their own script, and yielding to one that\n * does not (a drag handle that is only draggable with a pointer) would just\n * make the key dead.\n */\nfunction activates(element: Element, key: string): boolean {\n if (key !== ' ' && key !== 'Enter') return false;\n const tag = element.tagName;\n if (tag === 'BUTTON') return (element as HTMLButtonElement).disabled !== true;\n if (tag === 'SUMMARY') return true;\n return key === 'Enter' && (tag === 'A' || tag === 'AREA') && element.hasAttribute('href');\n}\n\n/**\n * Is this container actually showing? A closed custom dialog is often left in\n * the page: `hidden`, `aria-hidden`, `display: none`, or (animated ones)\n * `visibility: hidden` / `opacity: 0`. Unknown (no `checkVisibility`, as in\n * test DOMs) counts as showing.\n */\nfunction isRendered(element: Element): boolean {\n if (element.hasAttribute('hidden')) return false;\n if (element.getAttribute('aria-hidden') === 'true') return false;\n const check = (\n element as Element & {\n checkVisibility?: (options?: {\n visibilityProperty?: boolean;\n opacityProperty?: boolean;\n }) => boolean;\n }\n ).checkVisibility;\n if (typeof check !== 'function') return true;\n try {\n return check.call(element, { visibilityProperty: true, opacityProperty: true });\n } catch {\n return true;\n }\n}\n\n/** An open modal `<dialog>` or a visible `aria-modal` container: Escape closes it. */\nfunction isOpenModal(element: Element): boolean {\n if (element.getAttribute('aria-modal') === 'true') {\n // A closed custom dialog is often left in the page, hidden, with the\n // attribute still on it. That must not swallow Escape for good.\n return isRendered(element);\n }\n return (\n element.tagName === 'DIALOG' &&\n element.hasAttribute('open') &&\n matchesOr(element, ':modal', true)\n );\n}\n\n/**\n * A modal dialog is open in `doc`. Focus is not always inside it: clicking the\n * dialog's own padding can leave focus on `<body>`, and Escape still closes\n * the dialog from there. A modal inside a shadow root is only seen while focus\n * is inside it (the composed path), since this query does not pierce shadow DOM.\n */\nfunction documentHasOpenModal(doc: Document | null | undefined): boolean {\n if (!doc) return false;\n try {\n return Array.from(doc.querySelectorAll('dialog[open], [aria-modal=\"true\"]')).some(isOpenModal);\n } catch {\n return false;\n }\n}\n\n/**\n * True when the key already means something to the control that has focus, so\n * a global shortcut must leave it alone:\n *\n * - `<input>` (every type), `<textarea>`, `<select>` and contenteditable keep\n * every key;\n * - Escape belongs to an open modal dialog, wherever focus is;\n * - Space and Enter belong to a focused `<button>` or `<summary>`, and Enter to\n * a focused link.\n *\n * It makes no difference how the control got focus. A button the user clicked\n * still has focus, so Space activates it again, exactly as it does on any\n * other page; a shortcut only gets the key once focus is somewhere else.\n *\n * `handleKeyboardEvent` applies this itself. It is exported for listeners that\n * match keys on their own.\n */\nexport function keyBelongsToFocusedControl(event: KeyboardEvent): boolean {\n const path = elementPath(event);\n const focused = path[0];\n\n if (event.key === 'Escape') {\n // Also when the event has no element target (dispatched on the document).\n const doc = focused?.ownerDocument ?? (typeof document !== 'undefined' ? document : null);\n if (path.some(isOpenModal) || documentHasOpenModal(doc)) return true;\n }\n if (!focused) return false;\n if (ownsAllKeys(focused)) return true;\n return activates(focused, event.key);\n}\n\n/**\n * Events whose default a shortcut prevented (here, in `handleKeyboardEvent`).\n * An Escape prevented by anything else (dnd-kit's pointer sensor and\n * `<daw-editor>` prevent it when they cancel a drag) is not a shortcut; one a\n * shortcut list prevented still reaches the next list (#848, review of #915).\n */\nconst preventedByShortcut = new WeakSet<Event>();\n\n/**\n * Handle a keyboard event against a list of shortcuts.\n * Pure function, no framework dependency.\n *\n * Shortcuts do not fire for a key the focused control uses itself; see\n * `keyBelongsToFocusedControl`. Nor for an Escape whose default something\n * other than a shortcut already prevented (a drag cancelled it): an Escape that\n * cancelled a drag does nothing else.\n */\nexport function handleKeyboardEvent(\n event: KeyboardEvent,\n shortcuts: KeyboardShortcut[],\n enabled: boolean\n): void {\n if (!enabled) return;\n\n // Ignore key repeat events — holding a key fires keydown repeatedly.\n // Without this guard, holding Space rapidly toggles play/pause.\n if (event.repeat) return;\n\n // A drag that took the key (dnd-kit's pointer sensor, <daw-editor>'s drag\n // cancel) has already prevented its default: an Escape that cancelled a\n // drag does nothing else (#848). Another shortcut list's own prevention\n // does not count: two lists that both bind Escape both run.\n if (event.key === 'Escape' && event.defaultPrevented && !preventedByShortcut.has(event)) return;\n\n if (keyBelongsToFocusedControl(event)) return;\n\n const matchingShortcut = shortcuts.find((shortcut) => matchesKeyBinding(event, shortcut));\n\n if (matchingShortcut) {\n if (matchingShortcut.preventDefault !== false) {\n event.preventDefault();\n preventedByShortcut.add(event);\n }\n matchingShortcut.action();\n }\n}\n","export type RangeSupport = 'supported' | 'unsupported' | 'unknown';\n\ntype FetchLike = (url: string, init?: RequestInit) => Promise<Response>;\n\n/**\n * Probe whether an audio host honors HTTP range requests, so an on-demand\n * player can decide its seeking policy. Range *detection* lives here; range\n * *policy* (disable the scrubber, surface an error, play from start) stays with\n * the consuming component — the detection is generic, the UX is per-component.\n *\n * Sends `GET` with `Range: bytes=0-1` and reads only the status line, aborting\n * the body immediately: on a non-range host the `200` carries the entire\n * (possibly hours-long) file, which must never be downloaded just to detect the\n * failure.\n *\n * - `206` → `'supported'`\n * - `200` (host ignored Range, returned full body) → `'unsupported'`\n * - any throw (network error / CORS-opaque cross-origin) or other status → `'unknown'`\n *\n * **Positive-failure only:** only an observed `200` asserts a failure. A\n * CORS-opaque probe is `'unknown'`, NOT a failure — native `<audio>` seeking\n * works cross-origin *without* CORS, so seeking should stay enabled. A naive\n * \"no 206 ⇒ failure\" would false-positive on every CORS-opaque host.\n *\n * @param url The audio URL to probe.\n * @param fetchImpl Injectable fetch (defaults to the global `fetch`) — pass a\n * stub in tests so no real network is hit, and pass an explicit\n * implementation on runtimes without a global `fetch`.\n */\nexport async function probeRangeSupport(\n url: string,\n fetchImpl: FetchLike = fetch\n): Promise<RangeSupport> {\n const controller = new AbortController();\n try {\n const res = await fetchImpl(url, {\n method: 'GET',\n headers: { Range: 'bytes=0-1' },\n // Bypass the HTTP cache: RFC 7234 lets a UA satisfy a range request from a\n // cached full 200, which would falsely read as the server ignoring Range.\n cache: 'no-store',\n signal: controller.signal,\n });\n if (res.status === 206) return 'supported';\n if (res.status === 200) return 'unsupported';\n return 'unknown';\n } catch {\n return 'unknown';\n } finally {\n // Never consume the body — abort the moment we have the status line.\n controller.abort();\n }\n}\n","/**\n * Framework-agnostic microphone enumeration.\n *\n * Works without requesting a stream, but browsers redact device information\n * until microphone permission is granted: labels are empty everywhere, and\n * Chrome/Safari typically also redact deviceIds (often exposing a single\n * placeholder entry). The `hasLabels` flag tells consumers whether the list\n * is a usable picker or just a \"microphones exist\" signal — re-enumerate\n * after a successful getUserMedia to get the real list.\n *\n * Follows the probeRangeSupport pattern: the browser API is injectable for\n * tests and non-browser environments degrade gracefully.\n */\n\nexport interface MicrophoneDeviceInfo {\n deviceId: string;\n /** Real device label, or a generated fallback name when redacted. */\n label: string;\n groupId: string;\n}\n\nexport interface MicrophoneEnumeration {\n /** False when enumeration is unavailable — SSR/Node, insecure context\n * (mediaDevices requires HTTPS or localhost), or a very old browser. */\n supported: boolean;\n /** True when the browser exposed real device labels. False before\n * microphone permission is granted (labels — and often deviceIds — are\n * redacted); the `devices` labels are then generated fallbacks. */\n hasLabels: boolean;\n devices: MicrophoneDeviceInfo[];\n}\n\nconst UNSUPPORTED: MicrophoneEnumeration = Object.freeze({\n supported: false,\n hasLabels: false,\n devices: [],\n});\n\nfunction resolveMediaDevices(mediaDevices?: MediaDevices): MediaDevices | undefined {\n if (mediaDevices) return mediaDevices;\n return typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;\n}\n\n/**\n * List audio input devices without requesting a stream.\n *\n * @param mediaDevices - Injectable for tests; defaults to `navigator.mediaDevices`.\n */\nexport async function enumerateMicrophones(\n mediaDevices?: MediaDevices\n): Promise<MicrophoneEnumeration> {\n const md = resolveMediaDevices(mediaDevices);\n if (!md || typeof md.enumerateDevices !== 'function') {\n return UNSUPPORTED;\n }\n\n const all = await md.enumerateDevices();\n const inputs = all.filter((device) => device.kind === 'audioinput');\n const hasLabels = inputs.some((device) => device.label.length > 0);\n\n return {\n supported: true,\n hasLabels,\n devices: inputs.map((device, index) => ({\n deviceId: device.deviceId,\n label:\n device.label ||\n // Pre-permission fallbacks: Chrome redacts deviceId to '' as well,\n // so fall through to a positional name when there's nothing to slice.\n (device.deviceId ? `Microphone ${device.deviceId.slice(0, 8)}` : `Microphone ${index + 1}`),\n groupId: device.groupId,\n })),\n };\n}\n\n/**\n * Subscribe to the microphone device list: the listener fires once with the\n * initial enumeration and again on every `devicechange` (hot-plug, permission\n * grant in some browsers). Returns an unsubscribe function.\n *\n * Enumeration failures are logged and skipped — the subscription survives a\n * transient failure and delivers the next successful enumeration.\n *\n * @param mediaDevices - Injectable for tests; defaults to `navigator.mediaDevices`.\n */\nexport function watchMicrophoneDevices(\n listener: (enumeration: MicrophoneEnumeration) => void,\n mediaDevices?: MediaDevices\n): () => void {\n const md = resolveMediaDevices(mediaDevices);\n if (!md || typeof md.enumerateDevices !== 'function') {\n // Deliver asynchronously so subscribe-then-unsubscribe never re-enters\n // the caller synchronously.\n queueMicrotask(() => listener(UNSUPPORTED));\n return () => {};\n }\n\n let active = true;\n\n const deliver = () => {\n enumerateMicrophones(md)\n .then((result) => {\n if (active) listener(result);\n })\n .catch((err) => {\n console.warn('[waveform-playlist] Microphone enumeration failed:', String(err));\n });\n };\n\n md.addEventListener('devicechange', deliver);\n deliver();\n\n return () => {\n active = false;\n md.removeEventListener('devicechange', deliver);\n };\n}\n","import type { AnnotationData } from '../types/annotations';\n\n/** Edges within this distance (seconds) are considered \"linked\". */\nexport const LINK_THRESHOLD = 0.01;\n\n/** Minimum annotation duration (seconds) enforced by boundary edits. */\nexport const MIN_ANNOTATION_DURATION = 0.1;\n\n/** Link threshold for INTEGER TICK positions — closer than half a tick means equal. */\nexport const ANNOTATION_LINK_THRESHOLD_TICKS = 0.5;\n\n/** Minimum tick-annotation duration: a 128th note, floored at 1 tick. */\nexport function annotationMinDurationTicks(ppqn: number): number {\n return Math.max(1, Math.round(ppqn / 32));\n}\n\n/** Unit constants for a boundary-math run. Defaults are the seconds-domain values. */\nexport interface AnnotationBoundaryOptions {\n linkThreshold?: number;\n minDuration?: number;\n}\n\nexport interface AnnotationBoundaryUpdate {\n annotationIndex: number;\n newTime: number;\n isDraggingStart: boolean;\n annotations: readonly AnnotationData[];\n duration: number;\n linkEndpoints: boolean;\n}\n\n/**\n * Pure boundary-update logic shared by the React annotations package and the\n * dawcore annotation web components. Handles linked endpoints (moving one edge\n * drags the linked neighbor edge, with cascade) and collision push-back.\n * Returns a NEW array; never mutates inputs.\n */\nexport function updateAnnotationBoundaries(\n params: AnnotationBoundaryUpdate,\n options: AnnotationBoundaryOptions = {}\n): AnnotationData[] {\n const { annotationIndex, newTime, isDraggingStart, annotations, duration, linkEndpoints } =\n params;\n const linkThreshold = options.linkThreshold ?? LINK_THRESHOLD;\n const minDuration = options.minDuration ?? MIN_ANNOTATION_DURATION;\n\n const updatedAnnotations = [...annotations];\n const annotation = annotations[annotationIndex];\n\n if (isDraggingStart) {\n const constrainedStart = Math.min(annotation.end - minDuration, Math.max(0, newTime));\n\n updatedAnnotations[annotationIndex] = { ...annotation, start: constrainedStart };\n\n if (linkEndpoints && annotationIndex > 0) {\n const prevAnnotation = updatedAnnotations[annotationIndex - 1];\n if (Math.abs(prevAnnotation.end - annotation.start) < linkThreshold) {\n // Linked edges share one position. Setting the neighbour's edge to the\n // dragged edge (not moving it by the same amount) closes a gap smaller\n // than the threshold instead of carrying it along for the whole drag.\n updatedAnnotations[annotationIndex - 1] = {\n ...prevAnnotation,\n end: Math.max(prevAnnotation.start + minDuration, constrainedStart),\n };\n } else if (constrainedStart <= prevAnnotation.end) {\n updatedAnnotations[annotationIndex] = {\n ...updatedAnnotations[annotationIndex],\n start: prevAnnotation.end,\n };\n }\n } else if (\n !linkEndpoints &&\n annotationIndex > 0 &&\n constrainedStart < updatedAnnotations[annotationIndex - 1].end\n ) {\n updatedAnnotations[annotationIndex - 1] = {\n ...updatedAnnotations[annotationIndex - 1],\n end: constrainedStart,\n };\n }\n } else {\n const constrainedEnd = Math.max(annotation.start + minDuration, Math.min(newTime, duration));\n\n updatedAnnotations[annotationIndex] = { ...annotation, end: constrainedEnd };\n\n if (linkEndpoints && annotationIndex < updatedAnnotations.length - 1) {\n const nextAnnotation = updatedAnnotations[annotationIndex + 1];\n if (Math.abs(nextAnnotation.start - annotation.end) < linkThreshold) {\n // As above: the linked edge takes the dragged edge's position.\n updatedAnnotations[annotationIndex + 1] = {\n ...nextAnnotation,\n start: Math.min(nextAnnotation.end - minDuration, constrainedEnd),\n };\n\n let currentIndex = annotationIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n if (Math.abs(next.start - current.end) < linkThreshold) {\n const nextDelta = current.end - annotations[currentIndex].end;\n updatedAnnotations[currentIndex + 1] = {\n ...next,\n start: Math.min(next.end - minDuration, next.start + nextDelta),\n };\n currentIndex++;\n } else {\n break;\n }\n }\n } else if (constrainedEnd >= nextAnnotation.start) {\n updatedAnnotations[annotationIndex] = {\n ...updatedAnnotations[annotationIndex],\n end: nextAnnotation.start,\n };\n }\n } else if (\n !linkEndpoints &&\n annotationIndex < updatedAnnotations.length - 1 &&\n constrainedEnd > updatedAnnotations[annotationIndex + 1].start\n ) {\n const nextAnnotation = updatedAnnotations[annotationIndex + 1];\n updatedAnnotations[annotationIndex + 1] = { ...nextAnnotation, start: constrainedEnd };\n\n let currentIndex = annotationIndex + 1;\n while (currentIndex < updatedAnnotations.length - 1) {\n const current = updatedAnnotations[currentIndex];\n const next = updatedAnnotations[currentIndex + 1];\n if (current.end > next.start) {\n updatedAnnotations[currentIndex + 1] = { ...next, start: current.end };\n currentIndex++;\n } else {\n break;\n }\n }\n }\n }\n\n return updatedAnnotations;\n}\n","import type { KeyBinding } from '../keyboard';\n\nexport type AnnotationShortcutAction =\n | 'selectPrevious'\n | 'selectNext'\n | 'selectFirst'\n | 'selectLast'\n | 'clearSelection'\n | 'moveStartEarlier'\n | 'moveStartLater'\n | 'moveEndEarlier'\n | 'moveEndLater'\n | 'playActive';\n\n/** Key remapping map — null on the consumer means \"use defaults\". */\nexport interface AnnotationShortcutMap {\n selectPrevious?: KeyBinding;\n selectNext?: KeyBinding;\n selectFirst?: KeyBinding;\n selectLast?: KeyBinding;\n clearSelection?: KeyBinding;\n moveStartEarlier?: KeyBinding;\n moveStartLater?: KeyBinding;\n moveEndEarlier?: KeyBinding;\n moveEndLater?: KeyBinding;\n playActive?: KeyBinding;\n}\n\n// Explicit ctrlKey/metaKey: false so browser combos (Cmd+ArrowLeft = history\n// back, Cmd+[ = back, etc.) never trigger annotation actions — same convention\n// as <daw-keyboard-shortcuts> presets.\nconst noMods = { ctrlKey: false as const, metaKey: false as const };\n\nexport const DEFAULT_ANNOTATION_SHORTCUTS: Record<AnnotationShortcutAction, KeyBinding[]> = {\n selectPrevious: [\n { key: 'ArrowUp', ...noMods },\n { key: 'ArrowLeft', ...noMods },\n ],\n selectNext: [\n { key: 'ArrowDown', ...noMods },\n { key: 'ArrowRight', ...noMods },\n ],\n selectFirst: [{ key: 'Home', ...noMods }],\n selectLast: [{ key: 'End', ...noMods }],\n clearSelection: [{ key: 'Escape', ...noMods }],\n moveStartEarlier: [{ key: '[', ...noMods }],\n moveStartLater: [{ key: ']', ...noMods }],\n // '{' / '}' are what event.key reports for Shift+[ / Shift+] — no explicit\n // shiftKey needed; the key value itself encodes it.\n moveEndEarlier: [{ key: '{', ...noMods }],\n moveEndLater: [{ key: '}', ...noMods }],\n playActive: [{ key: 'Enter', ...noMods }],\n};\n\nconst ALL_ACTIONS = Object.keys(DEFAULT_ANNOTATION_SHORTCUTS) as AnnotationShortcutAction[];\n\n/**\n * Flatten defaults + remap into a matchable list. A remapped action replaces\n * ALL of its default bindings with the single provided binding.\n */\nexport function resolveAnnotationShortcuts(\n remap: AnnotationShortcutMap | null\n): Array<{ action: AnnotationShortcutAction; binding: KeyBinding }> {\n return ALL_ACTIONS.flatMap((action) => {\n const override = remap?.[action];\n const bindings = override ? [override] : DEFAULT_ANNOTATION_SHORTCUTS[action];\n return bindings.map((binding) => ({ action, binding }));\n });\n}\n","/**\n * Outside production builds, freeze what the annotation store hands out. The\n * same objects are shared by the store, every reader and every later list\n * built from them, so a write by a consumer would change all of them; frozen,\n * the write throws where it is made (in a module, which is strict code).\n *\n * Frozen: the array, each annotation and its `lines` array.\n *\n * Not exported from the package: core's index re-exports `store.ts` and\n * `bounds.ts` only.\n */\n\nimport type { AnnotationData } from '../types';\n\ndeclare const process: { env: { NODE_ENV?: string } };\n\n/**\n * True unless this is a production build. Bundlers replace\n * `process.env.NODE_ENV` with a literal; where there is no `process` at all\n * (a page that loads the module without a bundler) this is false.\n */\nexport function isDevelopmentBuild(): boolean {\n try {\n return process.env.NODE_ENV !== 'production';\n } catch {\n return false;\n }\n}\n\n/** Freeze `list`, each annotation and its `lines` in development; return `list`. */\nexport function freezeAnnotations(list: readonly AnnotationData[]): readonly AnnotationData[] {\n if (!isDevelopmentBuild()) return list;\n for (const annotation of list) {\n if (Array.isArray(annotation.lines)) Object.freeze(annotation.lines);\n Object.freeze(annotation);\n }\n return Object.freeze(list);\n}\n","import type { AnnotationData } from '../types';\nimport { freezeAnnotations } from './devFreeze';\n\n/**\n * The owner of a list of annotations. The app makes one and gives it to a\n * provider; everything that reads the annotations reads them here, and every\n * change is a call to `set` or `update`.\n */\nexport interface AnnotationStore {\n /**\n * The current annotations. The same array until a change. Never write to\n * it: outside production builds it is frozen.\n */\n getAnnotations(): readonly AnnotationData[];\n /** Be told after every change. Returns the function that unsubscribes. */\n subscribe(listener: () => void): () => void;\n /** Replace the annotations. */\n set(annotations: readonly AnnotationData[]): void;\n /**\n * Change the annotations: `fn` gets the current array and returns the next.\n * The change is applied before `update` returns, so the next call's\n * `current` already holds it. Returning `current` changes nothing.\n */\n update(fn: (current: readonly AnnotationData[]) => readonly AnnotationData[]): void;\n}\n\nexport interface AnnotationStoreOptions {\n /**\n * The app's rule for every change. Gets the proposed list and the current\n * one, returns the list to store: `next` to accept, `current` to refuse,\n * or another list to adjust (e.g. clamp an edge so it does not overlap).\n * Not called for the initial list. A throw from it reaches the caller of\n * `set` or `update`, and the store keeps its value.\n */\n beforeChange?: (\n next: readonly AnnotationData[],\n current: readonly AnnotationData[]\n ) => readonly AnnotationData[];\n}\n\nfunction invalid(message: string): TypeError {\n return new TypeError('[waveform-playlist] Invalid annotations: ' + message);\n}\n\n/** Every annotation has numeric `start` and `end`, and the ids are unique. */\nfunction validateAnnotations(list: readonly AnnotationData[]): void {\n if (!Array.isArray(list)) throw invalid('expected an array.');\n const seen = new Set<string>();\n for (const annotation of list) {\n const { id, start, end } = annotation ?? ({} as AnnotationData);\n if (!Number.isFinite(start) || !Number.isFinite(end)) {\n throw invalid(\n `annotation \"${String(id)}\" needs numeric start and end (got ${typeof start} and ${typeof end}). ` +\n 'Parse text formats first, e.g. parseAeneas() from @waveform-playlist/annotations.'\n );\n }\n if (seen.has(id)) throw invalid(`two annotations have the id \"${id}\".`);\n seen.add(id);\n }\n}\n\n/**\n * Make an annotation store holding `initial` (empty when absent). Throws a\n * `TypeError` for an invalid list: an annotation without numeric `start` and\n * `end`, or two with one id.\n */\nexport function createAnnotationStore(\n initial: readonly AnnotationData[] = [],\n options: AnnotationStoreOptions = {}\n): AnnotationStore {\n validateAnnotations(initial);\n let annotations = freezeAnnotations(initial);\n const listeners = new Set<{ listener: () => void }>();\n const { beforeChange } = options;\n\n const commit = (proposed: readonly AnnotationData[]) => {\n if (proposed === annotations) return;\n validateAnnotations(proposed);\n let next = proposed;\n if (beforeChange) {\n next = beforeChange(proposed, annotations);\n if (next === annotations) return;\n if (next !== proposed) validateAnnotations(next);\n }\n annotations = freezeAnnotations(next);\n for (const entry of [...listeners]) {\n if (!listeners.has(entry)) continue;\n try {\n entry.listener();\n } catch (error) {\n console.warn('[waveform-playlist] Error in an annotation store subscriber:', error);\n }\n }\n };\n\n return {\n getAnnotations: () => annotations,\n subscribe(listener) {\n // Each call gets its own entry, so one function subscribed twice is told twice.\n const entry = { listener };\n listeners.add(entry);\n return () => {\n listeners.delete(entry);\n };\n },\n set(next) {\n commit(next);\n },\n update(fn) {\n commit(fn(annotations));\n },\n };\n}\n","import type { AnnotationData } from '../types';\n\n/** New bounds for the annotation with `id`. */\nexport interface AnnotationBoundsChange {\n id: string;\n start: number;\n end: number;\n}\n\n/**\n * Write `start` and `end` of each change onto the annotation with that id in\n * `current`. Every other field, and every annotation no change names, is kept\n * as it is (the same object). An id that is not in `current` is skipped.\n *\n * Returns `current` itself when nothing changes, so an `update` with it\n * notifies nobody.\n */\nexport function applyAnnotationBounds(\n current: readonly AnnotationData[],\n changes: readonly AnnotationBoundsChange[]\n): readonly AnnotationData[] {\n if (changes.length === 0) return current;\n const byId = new Map(changes.map((change) => [change.id, change]));\n let changed = false;\n const next = current.map((annotation) => {\n const change = byId.get(annotation.id);\n if (!change || (change.start === annotation.start && change.end === annotation.end)) {\n return annotation;\n }\n changed = true;\n return { ...annotation, start: change.start, end: change.end };\n });\n return changed ? next : current;\n}\n","import type { DecidedPanLaw } from './panLaw';\n\nconst PREFIX = '[waveform-playlist] ';\n\n/** Gains of the pan matrix: `out = [[ll, rl], [lr, rr]] · in`, where e.g.\n * `rl` is how much of the input's RIGHT channel reaches the LEFT output. */\nexport interface PanMatrix {\n ll: number;\n lr: number;\n rl: number;\n rr: number;\n}\n\n/**\n * The gains of a pan law at a pan position: exactly the two algorithms of\n * the Web Audio `StereoPannerNode`. Which law a track has is the track's own\n * value (`trackPanLaw`), not a property of the signal that reaches the stage.\n *\n * - `'mono'` — equal-power pan, θ = (pan + 1)·π/4: L × cos θ, R × sin θ.\n * For a mono signal (taken as L = R) that is the mono law, L = m·cos θ and\n * R = m·sin θ: −3 dB per side at centre. A stereo signal from the track's\n * effects is balanced by the same gains, so it stays stereo at the same\n * centre level as the dry signal.\n * - `'stereo'` — the stereo law: centre passes both channels at unity;\n * panning left folds the right channel into the left\n * (L + R·cos x, R·sin x with x = (pan + 1)·π/2), and symmetrically right.\n *\n * `pan` is clamped to −1 … 1; a non-finite value is treated as centre.\n */\nexport function panMatrix(pan: number, panLaw: DecidedPanLaw): PanMatrix {\n const p = Number.isFinite(pan) ? Math.max(-1, Math.min(1, pan)) : 0;\n if (panLaw === 'mono') {\n const theta = ((p + 1) * Math.PI) / 4;\n return { ll: Math.cos(theta), lr: 0, rl: 0, rr: Math.sin(theta) };\n }\n if (p <= 0) {\n const x = ((p + 1) * Math.PI) / 2;\n return { ll: 1, lr: 0, rl: Math.cos(x), rr: Math.sin(x) };\n }\n const x = (p * Math.PI) / 2;\n return { ll: Math.cos(x), lr: Math.sin(x), rl: 0, rr: 1 };\n}\n\n/**\n * The part of an audio context the pan stage needs. Any `AudioContext` or\n * `OfflineAudioContext` satisfies it, and so does the `rawContext` behind\n * Tone.js (native or standardized-audio-context).\n */\nexport type PanStageContext = Pick<\n BaseAudioContext,\n 'createGain' | 'createChannelSplitter' | 'createChannelMerger' | 'currentTime'\n>;\n\n/** How long a switch of pan law takes: the four gains ramp, so a switch during playback does not click (#684). */\nexport const PAN_LAW_RAMP_SECONDS = 0.01;\n\n/** A track's pan stage: `input → … → output`, with `setPan(-1 … 1)`. */\nexport interface PanStage {\n readonly input: AudioNode;\n readonly output: AudioNode;\n setPan(pan: number): void;\n /**\n * Switch the pan law, keeping the pan. The four gains ramp to the new\n * matrix over `PAN_LAW_RAMP_SECONDS`; the law the stage already has does\n * nothing.\n */\n setPanLaw(panLaw: DecidedPanLaw): void;\n /** Disconnect every node of the stage. */\n dispose(): void;\n}\n\n/**\n * Build the pan stage for a track with the pan law `panLaw` (core's\n * `trackPanLaw(track)`; `'mono'` for synth voices).\n *\n * Why this is not a `StereoPannerNode`: a track's pan stage is fed by its\n * effects chain (pre-fader inserts), whose channel layout is not the\n * source's. A `StereoPannerNode` picks its law from the layout it RECEIVES,\n * so a stereo effect on a mono track would jump ~3 dB at centre. And under\n * standardized-audio-context (Tone.js's default context) a panner's channel\n * mode cannot be changed at all (its bug #105), which pins a mono track's\n * panner to one channel.\n *\n * This stage is a 2×2 gain matrix built from plain gain, splitter and merger\n * nodes — none of which is restricted — so it behaves identically on every\n * context, always passes stereo through, and takes its law from the caller.\n */\nexport function createPanStage(\n context: PanStageContext,\n pan: number,\n panLaw: DecidedPanLaw\n): PanStage {\n // Take the incoming signal as stereo regardless of its layout: with an\n // explicit count of 2 (speakers interpretation) mono is upmixed to L = R\n // and stereo passes through unchanged.\n const upmix = context.createGain();\n upmix.channelCount = 2;\n upmix.channelCountMode = 'explicit';\n upmix.channelInterpretation = 'speakers';\n const split = context.createChannelSplitter(2);\n const merge = context.createChannelMerger(2);\n const ll = context.createGain();\n const lr = context.createGain();\n const rl = context.createGain();\n const rr = context.createGain();\n\n let currentPan = pan;\n let currentLaw = panLaw;\n // True from a law switch until the next pan move: a ramp may be scheduled.\n let rampScheduled = false;\n const targets = (): Array<[GainNode, number]> => {\n const matrix = panMatrix(currentPan, currentLaw);\n return [\n [ll, matrix.ll],\n [lr, matrix.lr],\n [rl, matrix.rl],\n [rr, matrix.rr],\n ];\n };\n /** Set the gains now. A scheduled ramp is cancelled first, or its end would override the value. */\n const apply = (): void => {\n for (const [node, value] of targets()) {\n if (rampScheduled) node.gain.cancelScheduledValues(context.currentTime);\n node.gain.value = value;\n }\n rampScheduled = false;\n };\n /** Move the gains to the current matrix over the ramp time, from where each is now. */\n const ramp = (): void => {\n const now = context.currentTime;\n for (const [node, value] of targets()) {\n node.gain.cancelScheduledValues(now);\n node.gain.setValueAtTime(node.gain.value, now);\n node.gain.linearRampToValueAtTime(value, now + PAN_LAW_RAMP_SECONDS);\n }\n rampScheduled = true;\n };\n apply();\n\n upmix.connect(split);\n split.connect(ll, 0, 0);\n split.connect(lr, 0, 0);\n split.connect(rl, 1, 0);\n split.connect(rr, 1, 0);\n ll.connect(merge, 0, 0);\n rl.connect(merge, 0, 0);\n lr.connect(merge, 0, 1);\n rr.connect(merge, 0, 1);\n\n return {\n input: upmix,\n output: merge,\n setPan: (value) => {\n currentPan = value;\n apply();\n },\n setPanLaw: (value) => {\n if (value === currentLaw) return;\n currentLaw = value;\n ramp();\n },\n dispose: () => {\n for (const node of [upmix, split, ll, lr, rl, rr, merge]) {\n try {\n node.disconnect();\n } catch (err) {\n console.warn(PREFIX + 'pan stage: error disconnecting node: ' + String(err));\n }\n }\n },\n };\n}\n","/**\n * A track's pan law (#684).\n *\n * - `'mono'`: equal power, −3 dB per side at centre; the channels are never\n * mixed.\n * - `'stereo'`: unity at centre; panning folds one channel into the other.\n * - `'auto'`: not decided yet. It is the default, and the first decoded\n * audio a track holds decides it (an arrangement stores the result as a\n * mixer value, and a track's clips never change it afterwards).\n *\n * The law says how a track is panned. It converts nothing: a stereo clip on\n * a `'mono'` track still plays in stereo.\n */\nexport type PanLaw = 'auto' | 'mono' | 'stereo';\n\n/** A law a pan stage can apply: every `PanLaw` except `'auto'`. */\nexport type DecidedPanLaw = Exclude<PanLaw, 'auto'>;\n\nexport const DEFAULT_PAN_LAW: PanLaw = 'auto';\n\n/** True for `'mono'` and `'stereo'` only; any other value, of any type, is not a decided law. */\nexport function isDecidedPanLaw(value: unknown): value is DecidedPanLaw {\n return value === 'mono' || value === 'stereo';\n}\n\n/** The part of a track `trackPanLaw` reads: `ClipTrack` satisfies it. */\nexport interface TrackPanLawSource {\n panLaw?: PanLaw;\n clips: ReadonlyArray<{ audioBuffer?: { numberOfChannels: number } }>;\n}\n\n/**\n * The law of the decoded audio a track holds: `'stereo'` when any clip's\n * buffer has two or more channels, `'mono'` when at least one clip has a\n * buffer, `null` when none has (an empty track, loading clips, MIDI clips,\n * clips made from peaks alone).\n */\nexport function audioPanLaw(track: Pick<TrackPanLawSource, 'clips'>): DecidedPanLaw | null {\n let law: DecidedPanLaw | null = null;\n for (const clip of track.clips) {\n const channels = clip.audioBuffer?.numberOfChannels;\n if (channels === undefined) continue;\n if (channels >= 2) return 'stereo';\n law = 'mono';\n }\n return law;\n}\n\n/**\n * The law a renderer pans a track with: the track's own when it is decided;\n * else (`'auto'`, no field, or a value that is not a law) the law of its\n * audio; else `'mono'`.\n */\nexport function trackPanLaw(track: TrackPanLawSource): DecidedPanLaw {\n if (isDecidedPanLaw(track.panLaw)) return track.panLaw;\n return audioPanLaw(track) ?? 'mono';\n}\n","/**\n * A value that changes too often to live in UI state (meter levels, recording\n * progress): read it with `getSnapshot()`, or be told about each new value\n * with `subscribe()`.\n *\n * The pair matches React's `useSyncExternalStore(source.subscribe,\n * source.getSnapshot)`, but nothing here depends on React.\n */\nexport interface ValueSource<T> {\n /**\n * Call `listener` with each new value. Returns the function that removes\n * the subscription.\n */\n subscribe(listener: (value: T) => void): () => void;\n /** The latest value. The same object is returned until the next change. */\n getSnapshot(): T;\n}\n\n/** Per-channel meter readings, each normalized to 0-1. */\nexport interface MeterLevels {\n /** Smoothed peak level per channel. */\n levels: number[];\n /** Highest level seen per channel since the last reset. */\n peakLevels: number[];\n /** RMS level per channel. */\n rmsLevels: number[];\n}\n\nexport type MeterSource = ValueSource<MeterLevels>;\n\n/** What a recording in progress has captured so far. */\nexport interface RecordingProgress {\n /** Elapsed recording time in seconds. */\n duration: number;\n /** Min/max peak pairs per channel, for the live waveform preview. */\n peaks: (Int8Array | Int16Array)[];\n}\n\nexport type RecordingProgressSource = ValueSource<RecordingProgress>;\n\nexport interface ValueSourceHandle<T> {\n /** The read side, safe to hand to consumers. */\n source: ValueSource<T>;\n /** Replace the value and notify listeners. A no-op for the current value. */\n publish(value: T): void;\n}\n\n/** Build a `MeterLevels` of zeros for `channelCount` channels. */\nexport function silentMeterLevels(channelCount: number): MeterLevels {\n const count = Math.max(0, Math.floor(channelCount));\n return {\n levels: new Array<number>(count).fill(0),\n peakLevels: new Array<number>(count).fill(0),\n rmsLevels: new Array<number>(count).fill(0),\n };\n}\n\n/**\n * Create a `ValueSource` together with the function that publishes to it.\n * Published values must be new objects: listeners and `getSnapshot` callers\n * compare by identity.\n */\nexport function createValueSource<T>(initial: T): ValueSourceHandle<T> {\n let current = initial;\n // Keyed by a per-subscription token, so the same function subscribed twice\n // is two subscriptions.\n const listeners = new Map<symbol, (value: T) => void>();\n\n const source: ValueSource<T> = {\n subscribe(listener) {\n const token = Symbol('subscription');\n listeners.set(token, listener);\n return () => {\n listeners.delete(token);\n };\n },\n getSnapshot() {\n return current;\n },\n };\n\n const publish = (value: T) => {\n if (Object.is(value, current)) return;\n current = value;\n // Copy first: a listener may unsubscribe (itself or another) while this runs.\n for (const listener of [...listeners.values()]) {\n try {\n listener(value);\n } catch (err) {\n console.warn('[waveform-playlist] A value source listener threw: ' + String(err));\n }\n }\n };\n\n return { source, publish };\n}\n","import { createValueSource } from './valueSource';\n\nexport type SourceState<V> =\n | { status: 'pending' }\n | { status: 'loaded'; value: V }\n | { status: 'failed'; error: Error };\n\nexport interface SourceLoader<K, V> {\n /** Declare the whole set of keys that are wanted now. */\n setWanted(keys: Iterable<K>): void;\n /** Abort every load in flight. Wanted keys and loaded values are kept. */\n suspend(): void;\n /** Record a value the caller already holds as loaded. */\n provide(key: K, value: V): void;\n /** Start a failed key again. A no-op for any other state. */\n retry(key: K): void;\n /** `ValueSource` shape: a new Map object on every change. */\n subscribe(listener: (states: ReadonlyMap<K, SourceState<V>>) => void): () => void;\n getSnapshot(): ReadonlyMap<K, SourceState<V>>;\n}\n\ninterface Entry<V> {\n state: SourceState<V>;\n /** Present only while a load is in flight. */\n controller?: AbortController;\n /** Identifies the load whose result may still be applied. */\n token: symbol;\n}\n\nfunction toError(reason: unknown): Error {\n return reason instanceof Error ? reason : new Error(String(reason));\n}\n\n/**\n * Loads sources by key. One owner declares the whole set of wanted keys with\n * `setWanted`; a key is loaded once, kept while it stays wanted, and dropped\n * (its load aborted) when it leaves the set. Framework-free: read it with\n * `useSyncExternalStore(loader.subscribe, loader.getSnapshot)`.\n *\n * A rejection is ignored only when the loader aborted that load; a load that\n * rejects with an AbortError of its own is recorded as `failed` (`retry` restarts it).\n */\nexport function createSourceLoader<K, V>(options: {\n load: (key: K, signal: AbortSignal) => Promise<V>;\n}): SourceLoader<K, V> {\n const { load } = options;\n const entries = new Map<K, Entry<V>>();\n // Set by suspend(), cleared by setWanted(): while set, nothing may start a load.\n let suspended = false;\n const { source, publish } = createValueSource<ReadonlyMap<K, SourceState<V>>>(new Map());\n\n const publishEntries = () => {\n const next = new Map<K, SourceState<V>>();\n for (const [key, entry] of entries) next.set(key, entry.state);\n publish(next);\n };\n\n const abort = (entry: Entry<V>) => {\n entry.controller?.abort();\n };\n\n // Start a load for `key`; the caller publishes afterwards.\n const start = (key: K) => {\n const token = Symbol('load');\n const controller = new AbortController();\n const entry: Entry<V> = { state: { status: 'pending' }, controller, token };\n entries.set(key, entry);\n\n const settle = (state: SourceState<V>) => {\n const current = entries.get(key);\n if (!current || current.token !== token) return;\n entries.set(key, { state, token });\n publishEntries();\n };\n\n let promise: Promise<V>;\n try {\n // A plain function that returns the value instead of a promise is accepted.\n promise = Promise.resolve(load(key, controller.signal));\n } catch (err) {\n entries.set(key, { state: { status: 'failed', error: toError(err) }, token });\n return;\n }\n promise.then(\n (value) => settle({ status: 'loaded', value }),\n (err: unknown) => {\n // A load the loader aborted is ignored by the token check in settle()\n // as well; returning here only skips building an Error for it. A load\n // that rejects with its own AbortError is not aborted here: a failure.\n if (controller.signal.aborted) return;\n settle({ status: 'failed', error: toError(err) });\n }\n );\n };\n\n return {\n setWanted(keys) {\n const wanted = new Set(keys);\n suspended = false;\n let changed = false;\n for (const [key, entry] of [...entries]) {\n if (wanted.has(key)) continue;\n abort(entry);\n entries.delete(key);\n changed = true;\n }\n for (const key of wanted) {\n const entry = entries.get(key);\n if (entry && (entry.state.status !== 'pending' || entry.controller)) continue;\n start(key);\n // Restarting a suspended key leaves it pending: nothing to publish unless it failed at once.\n if (!entry || entries.get(key)?.state.status !== 'pending') changed = true;\n }\n if (changed) publishEntries();\n },\n\n suspend() {\n suspended = true;\n for (const [key, entry] of [...entries]) {\n if (entry.state.status !== 'pending' || !entry.controller) continue;\n abort(entry);\n entries.set(key, { state: entry.state, token: Symbol('suspended') });\n }\n },\n\n provide(key, value) {\n const entry = entries.get(key);\n if (entry?.state.status === 'loaded') return;\n if (entry) abort(entry);\n entries.set(key, { state: { status: 'loaded', value }, token: Symbol('provided') });\n publishEntries();\n },\n\n retry(key) {\n if (entries.get(key)?.state.status !== 'failed') return;\n if (suspended) {\n // Nothing would abort a load started now: wait for the next setWanted.\n entries.set(key, { state: { status: 'pending' }, token: Symbol('suspended') });\n } else {\n start(key);\n }\n publishEntries();\n },\n\n subscribe: source.subscribe,\n getSnapshot: source.getSnapshot,\n };\n}\n","import type { Fade } from './types';\nimport type { PanLaw } from './panLaw';\nimport type { RenderMode, SpectrogramConfig, ColorMapValue } from './types/spectrogram';\nimport { createClipFromSeconds, createTrack } from './types/clip';\nimport type {\n AudioClip,\n ClipSource,\n LoadingClip,\n ArrangementTrack,\n WaveformDataObject,\n} from './types/clip';\n\nexport interface AudioTrackOptions {\n /** Track id. Default: generated. An empty string counts as none. */\n id?: string;\n /** Id of the clip. Default: generated. An empty string counts as none. */\n clipId?: string;\n /** Track name. Default: the file name of `src` without its extension, else 'Untitled'. */\n name?: string;\n /** The audio to load. A string is a URL; a Blob or File is keyed by identity. */\n src?: ClipSource;\n /** Audio already in memory. With `src` too, the clip is an `AudioClip` that records `src`. */\n audioBuffer?: AudioBuffer;\n /** Pre-computed peaks. Without `src` or `audioBuffer`, the clip is built from these alone. */\n waveformData?: WaveformDataObject;\n /** Position on the timeline, in seconds. Default 0. */\n start?: number;\n /** Duration in seconds. Default: the whole source from `offset`. */\n duration?: number;\n /** Start within the source, in seconds. Default 0. */\n offset?: number;\n fadeIn?: Fade;\n fadeOut?: Fade;\n /** Clip gain. Default 1. */\n gain?: number;\n color?: string;\n muted?: boolean;\n soloed?: boolean;\n volume?: number;\n pan?: number;\n /** The pan law the track enters with. Default: 'auto', decided by its first decoded audio. */\n panLaw?: PanLaw;\n renderMode?: RenderMode;\n spectrogramConfig?: SpectrogramConfig;\n spectrogramColorMap?: ColorMapValue;\n}\n\n// A copy of the private generateId in types/clip.ts (same id format).\nfunction generateId(): string {\n return `${Date.now()}-${Math.random().toString(36).slice(2, 11)}`;\n}\n\nfunction checkNonNegative(name: string, value: number | undefined): void {\n if (value !== undefined && !(Number.isFinite(value) && value >= 0)) {\n throw new Error(`audioTrack: ${name} must be a finite number of seconds, 0 or more`);\n }\n}\n\nfunction checkOptions(options: AudioTrackOptions): void {\n checkNonNegative('start', options.start);\n checkNonNegative('offset', options.offset);\n const { duration } = options;\n if (duration !== undefined && !(Number.isFinite(duration) && duration > 0)) {\n throw new Error('audioTrack: duration must be a positive finite number of seconds');\n }\n}\n\nfunction decodeName(name: string): string {\n try {\n return decodeURIComponent(name);\n } catch {\n return name; // a malformed sequence keeps the raw name\n }\n}\n\nfunction defaultName(src: ClipSource | undefined): string {\n const raw =\n typeof src === 'string'\n ? src\n : typeof File !== 'undefined' && src instanceof File\n ? src.name\n : '';\n if (/^(data|blob):/i.test(raw)) return 'Untitled';\n const path = raw.split(/[?#]/)[0];\n const file = path.slice(path.lastIndexOf('/') + 1);\n const dot = file.lastIndexOf('.');\n const base = dot > 0 ? file.slice(0, dot) : file;\n return decodeName(base) || 'Untitled';\n}\n\n/**\n * Duration in seconds to build the clip with. An offset at or past the end of\n * the audio throws; a duration that runs past the end is cut to it, with a\n * warning. Compared in samples, with a tolerance of one sample.\n */\nfunction fitToAudio(\n name: string,\n offset: number,\n duration: number | undefined,\n sampleRate: number,\n sourceSamples: number\n): number {\n const offsetSamples = Math.round(offset * sampleRate);\n if (offsetSamples >= sourceSamples) {\n throw new Error('audioTrack: offset is past the end of the audio');\n }\n const remaining = sourceSamples - offsetSamples;\n if (duration === undefined) return remaining / sampleRate;\n const wanted = Math.round(duration * sampleRate);\n if (offsetSamples + wanted > sourceSamples + 1) {\n console.warn(\n `[waveform-playlist] audioTrack: offset + duration of \"${name}\" runs past the end of the audio; the clip is cut to the end.`\n );\n }\n return Math.min(wanted, remaining) / sampleRate;\n}\n\nfunction buildLoadingClip(\n id: string,\n src: ClipSource,\n name: string,\n options: AudioTrackOptions\n): LoadingClip {\n const given = {\n start: options.start,\n duration: options.duration,\n offset: options.offset,\n gain: options.gain,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n color: options.color,\n waveformData: options.waveformData,\n };\n const present = Object.entries(given).filter(([, value]) => value !== undefined);\n return { id, src, name, ...Object.fromEntries(present) };\n}\n\nfunction buildClip(options: AudioTrackOptions, name: string): AudioClip | LoadingClip {\n const { audioBuffer, waveformData, start = 0, offset = 0, duration } = options;\n const src = options.src || undefined; // '' counts as none\n const id = options.clipId || generateId();\n if (src !== undefined && !audioBuffer) return buildLoadingClip(id, src, name, options);\n if (!audioBuffer && !waveformData) {\n throw new Error('audioTrack: give src, audioBuffer or waveformData');\n }\n // The length of the audio in samples: the buffer's own length, or the\n // waveform data's duration rounded up, as createClipFromSeconds rounds it.\n const sampleRate = audioBuffer?.sampleRate ?? waveformData?.sample_rate ?? 0;\n const sourceSamples =\n audioBuffer?.length ?? Math.ceil((waveformData?.duration ?? 0) * sampleRate);\n const clipSeconds = fitToAudio(name, offset, duration, sampleRate, sourceSamples);\n const clip = createClipFromSeconds({\n audioBuffer,\n waveformData,\n startTime: start,\n offset,\n duration: clipSeconds,\n name,\n gain: options.gain,\n fadeIn: options.fadeIn,\n fadeOut: options.fadeOut,\n color: options.color,\n src,\n });\n return { ...clip, id };\n}\n\n/**\n * Builds a track whose one clip names its audio. With `src` and no\n * `audioBuffer` the clip is a `LoadingClip` (audio not loaded yet); with\n * `audioBuffer`, or `waveformData` and no `src`, it is an `AudioClip` built now.\n * A duration that runs past the end of the audio is cut to it, with a warning.\n */\nexport function audioTrack(options: AudioTrackOptions): ArrangementTrack {\n checkOptions(options);\n const name = options.name ?? defaultName(options.src);\n const clip = buildClip(options, name);\n const base = createTrack({\n name,\n muted: options.muted,\n soloed: options.soloed,\n volume: options.volume,\n pan: options.pan,\n spectrogramConfig: options.spectrogramConfig,\n spectrogramColorMap: options.spectrogramColorMap,\n color: options.color,\n });\n const track: ArrangementTrack = {\n ...base,\n id: options.id || base.id,\n clips: [clip],\n renderMode: options.renderMode,\n ...(options.panLaw !== undefined && { panLaw: options.panLaw }),\n };\n return track;\n}\n","/**\n * One gesture on a mixer control (a fader drag, a held arrow key) as one\n * undo step (#843). The mixer setters join changes that carry the same\n * `gesture` id into one step; this helper makes the id, and ends the gesture\n * so that the next change starts a new one.\n *\n * Framework-free: React's sliders and dawcore's elements both use it. One\n * helper per control, so two sliders never share an id. It lives in core,\n * not beside the setters in the engine, because `<daw-editor>` loads the\n * engine with a dynamic `import()`: a value import of the engine would put\n * it back in dawcore's first bundle.\n */\n\nexport interface MixerGesture {\n /** The id to pass while a gesture is going on. */\n readonly id: string;\n /** The gesture is over: the next change starts a new one. */\n end(): void;\n /** Ends the gesture on the input's own events; returns the detach function. */\n attach(input: HTMLInputElement): () => void;\n}\n\n/**\n * The keys that move a range input. While one is down the browser repeats\n * it, and the input fires `change` on each step: the gesture lasts until the\n * key comes up.\n */\nconst RANGE_KEYS: ReadonlySet<string> = new Set([\n 'ArrowUp',\n 'ArrowDown',\n 'ArrowLeft',\n 'ArrowRight',\n 'PageUp',\n 'PageDown',\n 'Home',\n 'End',\n]);\n\n/**\n * Made once per copy of this module, so two copies of the package installed\n * side by side (each with its own counter) never make the same id.\n */\nconst ID_PREFIX = Math.random().toString(36).slice(2, 10);\nlet idCount = 0;\n\nfunction nextId(): string {\n idCount += 1;\n return `mg-${ID_PREFIX}-${idCount}`;\n}\n\n/**\n * Make the gesture helper of one mixer control.\n *\n * ```ts\n * const gesture = createMixerGesture();\n * const detach = gesture.attach(slider);\n * slider.addEventListener('input', () =>\n * engine.setTrackVolume(trackId, slider.valueAsNumber, { gesture: gesture.id })\n * );\n * ```\n *\n * `attach` ends the gesture on the input's `change` (the end of a pointer\n * drag), except while a key that moves the input is held down; then on that\n * key's `keyup`. A `blur` ends it too. Mute and solo buttons need no helper:\n * each click is a step of its own.\n */\nexport function createMixerGesture(): MixerGesture {\n let id = nextId();\n const end = (): void => {\n id = nextId();\n };\n\n const attach = (input: HTMLInputElement): (() => void) => {\n let heldKey: string | null = null;\n\n const onKeyDown = (event: Event): void => {\n const { key } = event as KeyboardEvent;\n if (RANGE_KEYS.has(key)) heldKey = key;\n };\n const onKeyUp = (event: Event): void => {\n if ((event as KeyboardEvent).key !== heldKey) return;\n heldKey = null;\n end();\n };\n const onChange = (): void => {\n if (heldKey === null) end();\n };\n const onBlur = (): void => {\n heldKey = null;\n end();\n };\n\n input.addEventListener('keydown', onKeyDown);\n input.addEventListener('keyup', onKeyUp);\n input.addEventListener('change', onChange);\n input.addEventListener('blur', onBlur);\n return () => {\n input.removeEventListener('keydown', onKeyDown);\n input.removeEventListener('keyup', onKeyUp);\n input.removeEventListener('change', onChange);\n input.removeEventListener('blur', onBlur);\n };\n };\n\n return {\n get id() {\n return id;\n },\n end,\n attach,\n };\n}\n","/**\n * The effect registry shared by `<daw-editor>` and the React effects hooks:\n * one `registerEffect()` call makes a custom effect (an AudioWorklet, or any\n * chain of native nodes) available to both. Nothing here creates an audio\n * node; definitions are handed the context they must build on.\n */\n\n/** Range/display metadata for one effect parameter. */\nexport interface EffectParamDef {\n min: number;\n max: number;\n step?: number;\n /** 's', 'ms', 'Hz', 'dB', '%' … */\n unit?: string;\n /** Display name for a parameter panel. Defaults to the parameter's key. */\n label?: string;\n}\n\n/**\n * A live, wired effect. `input`/`output` are the chain attachment points\n * (the same node for single-node effects). `applyParams` updates AudioParams\n * in place — the chain never rebuilds for parameter changes.\n *\n * The host owns every connection OUT of `output`: when it rewires the chain\n * it disconnects all of them. Do not connect `output` to anything inside the\n * effect (a feedback path, say); take such a tap from a node before it.\n */\nexport interface NativeEffectInstance {\n input: AudioNode;\n output: AudioNode;\n applyParams: (params: Record<string, number>) => void;\n dispose?: () => void;\n /** Serializable snapshot of plugin-internal state (WAM getState). */\n getState?: () => Promise<unknown>;\n /** Builds the plugin's own GUI element (WAM createGui). GUI lifecycle is\n * independent of audio — hiding/destroying a GUI never stops processing. */\n createGui?: () => Promise<HTMLElement>;\n /** Releases a GUI element previously built by `createGui` (WAM destroyGui). */\n destroyGui?: (gui: HTMLElement) => void;\n /** Parameter metadata for the generic fallback panel (WAM getParameterInfo). */\n getParameterInfo?: () => Promise<unknown>;\n}\n\n/** A registered effect type. `create` must work on any BaseAudioContext so\n * the same definitions serve offline rendering. */\nexport interface NativeEffectDefinition {\n label: string;\n category: string;\n defaults: Record<string, number>;\n params: Record<string, EffectParamDef>;\n /** Name of the wet/dry param, when the effect has one. Bypass zeroes it\n * (storing the original); effects without one are bypassed by\n * disconnection. */\n wetParam?: string;\n /**\n * Optional async setup that must finish before `create` can run on a given\n * context — typically `audioContext.audioWorklet.addModule(url)` for an\n * AudioWorklet-backed effect. Worklet modules are context-bound, so this\n * runs once per context, including the OfflineAudioContext of every export\n * (which the consumer never sees). Hosts await it wherever they can: the\n * React hooks' `addEffect`, both surfaces' exports, `<daw-editor>`'s\n * `setEffectsState()`. `<daw-editor>`'s `addEffect()` is synchronous and\n * cannot — call `editor.prepareEffect(type)` first.\n *\n * Must be safe to run more than once on the same context: it runs again\n * after a failed attempt and when the type is re-registered.\n */\n prepare?: (audioContext: BaseAudioContext) => Promise<void>;\n create: (audioContext: BaseAudioContext, params: Record<string, number>) => NativeEffectInstance;\n /**\n * Set by a host library on the effects of its own catalogue (dawcore's\n * `native-*`), never by an app. The registry is shared between hosts, and a\n * host lists its own catalogue plus what the app registered, not another\n * host's catalogue: the React effect picker leaves these out. The effect\n * can still be added by id anywhere.\n */\n builtIn?: boolean;\n}\n\n/** Result of creating an effect via the registry. */\nexport interface CreatedNativeEffect {\n instance: NativeEffectInstance;\n params: Record<string, number>;\n wetParam?: string;\n}\n\ninterface PreparedRecord {\n /** The definition this preparation ran for — a re-registered type must\n * prepare again with its new definition. */\n definition: NativeEffectDefinition;\n promise: Promise<void>;\n settled: boolean;\n}\n\ninterface RegistryState {\n definitions: Map<string, NativeEffectDefinition>;\n /** Per-context preparation state. Weak: an OfflineAudioContext (one per\n * export) must not be kept alive by the registry. */\n prepared: WeakMap<BaseAudioContext, Map<string, PreparedRecord>>;\n}\n\n/**\n * The registry lives on `globalThis`, not in this module. An app can end up\n * with two copies of this package (its own version, and the exact version a\n * dependent pins); with a module-level map an effect registered through one\n * copy would be unknown to hosts using the other.\n */\n// Versioned: every copy that shares the state must agree on its shape. A\n// change to `RegistryState` needs a new key.\nconst REGISTRY_KEY = Symbol.for('@waveform-playlist/core/effect-registry/v1');\n\nfunction registryState(): RegistryState {\n const holder = globalThis as unknown as Record<symbol, RegistryState | undefined>;\n const existing = holder[REGISTRY_KEY];\n if (existing) return existing;\n const created: RegistryState = { definitions: new Map(), prepared: new WeakMap() };\n holder[REGISTRY_KEY] = created;\n return created;\n}\n\nconst registry = registryState().definitions;\nconst prepared = registryState().prepared;\n\nexport function registerEffect(type: string, definition: NativeEffectDefinition): void {\n if (registry.has(type)) {\n console.warn(\n '[waveform-playlist] registerEffect: overwriting existing effect type \"' + type + '\"'\n );\n }\n registry.set(type, definition);\n}\n\n/** Remove a registered type. Returns whether it was registered. Effects\n * already created from it keep working. */\nexport function unregisterEffect(type: string): boolean {\n return registry.delete(type);\n}\n\n/** A copy — mutating the returned map does not affect the registry. */\nexport function getEffectDefinitions(): Map<string, NativeEffectDefinition> {\n return new Map(registry);\n}\n\n/**\n * Run a registered effect's `prepare` hook for one context, once. Concurrent\n * and later calls share the same run; a failed run is forgotten so the next\n * call retries. Resolves immediately for definitions without a hook, and for\n * unknown types (creating the effect reports those).\n */\nexport function prepareEffect(type: string, audioContext: BaseAudioContext): Promise<void> {\n const definition = registry.get(type);\n if (!definition?.prepare) {\n return Promise.resolve();\n }\n const forContext = prepared.get(audioContext) ?? new Map<string, PreparedRecord>();\n prepared.set(audioContext, forContext);\n const existing = forContext.get(type);\n if (existing && existing.definition === definition) {\n return existing.promise;\n }\n\n const prepare = definition.prepare;\n const record: PreparedRecord = {\n definition,\n settled: false,\n // The async wrapper turns a synchronous throw into a rejection.\n promise: (async () => prepare(audioContext))().then(\n () => {\n record.settled = true;\n },\n (err: unknown) => {\n if (forContext.get(type) === record) {\n forContext.delete(type);\n }\n throw err;\n }\n ),\n };\n forContext.set(type, record);\n return record.promise;\n}\n\nfunction isPrepared(\n type: string,\n definition: NativeEffectDefinition,\n audioContext: BaseAudioContext\n): boolean {\n const record = prepared.get(audioContext)?.get(type);\n return record !== undefined && record.definition === definition && record.settled;\n}\n\n/**\n * Whether `type` has a prepare hook that has not completed on this context\n * for its CURRENT definition. Synchronous, so async callers can skip the\n * await (and stay synchronous) for the common case of effects without one.\n */\nexport function needsPrepare(type: string, audioContext: BaseAudioContext): boolean {\n const definition = registry.get(type);\n return definition?.prepare !== undefined && !isPrepared(type, definition, audioContext);\n}\n\n/**\n * Await a type's preparation until it holds for the definition registered\n * NOW. A type re-registered while its old definition was preparing would\n * otherwise reach `create` unprepared. Rejects with the hook's own error.\n */\nexport async function ensureEffectPrepared(\n type: string,\n audioContext: BaseAudioContext\n): Promise<void> {\n while (needsPrepare(type, audioContext)) {\n await prepareEffect(type, audioContext);\n }\n}\n\nexport function createEffectInstance(\n type: string,\n audioContext: BaseAudioContext,\n params: Record<string, number> = {}\n): CreatedNativeEffect {\n const definition = registry.get(type);\n if (!definition) {\n throw new Error(\n '[waveform-playlist] createEffectInstance: unknown effect type \"' +\n type +\n '\". Available types: ' +\n [...registry.keys()].join(', ')\n );\n }\n const merged = { ...definition.defaults, ...params };\n let instance: NativeEffectInstance;\n try {\n instance = definition.create(audioContext, merged);\n } catch (err) {\n if (!definition.prepare || isPrepared(type, definition, audioContext)) {\n throw err;\n }\n // The likeliest cause by far: an AudioWorklet module that was never\n // added to THIS context. Name the fix; keep the original message.\n const hinted = new Error(\n '[waveform-playlist] effect \"' +\n type +\n '\" has a prepare() step that has not completed on this audio context — ' +\n \"await prepareEffect('\" +\n type +\n \"', audioContext) before creating it (on <daw-editor>: await editor.prepareEffect('\" +\n type +\n \"') before addEffect). Original error: \" +\n (err instanceof Error ? err.message : String(err))\n ) as Error & { cause?: unknown };\n // Keep the original (its name, type and stack) reachable: the hint is a\n // guess at the cause, and `create` may have thrown for a real bug.\n hinted.cause = err;\n throw hinted;\n }\n try {\n instance.applyParams(merged);\n } catch (err) {\n // The caller never sees this instance, so nobody else can release it.\n try {\n instance.dispose?.();\n } catch {\n // The applyParams error is the one to report.\n }\n throw err;\n }\n return { instance, params: merged, wetParam: definition.wetParam };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACKO,IAAM,mBAAmB;;;AC4KzB,IAAM,oBAAoB;AAAA,EAC/B;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AACF;AAcO,SAAS,cAAc,MAAoD;AAChF,SAAO,EAAE,gBAAgB,SAAS,KAAK,cAAc;AACvD;AA0LO,SAAS,oBAAoB,SAA4C;AAC9E,QAAM,EAAE,WAAW,gBAAgB,KAAK,KAAK,IAAI;AAEjD,MAAI,YAAY,GAAG;AACjB,UAAM,IAAI,MAAM,qDAAqD;AAAA,EACvE;AAEA,MAAI;AACJ,MAAI,gBAAgB;AAClB,gBAAY;AAAA,EACd,WAAW,QAAQ,UAAa,SAAS,QAAW;AAClD,gBAAY,CAAC,SAAkB,OAAO,MAAO,OAAO;AAAA,EACtD,OAAO;A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AAAA,IACpD;AAGA,WAAO,QAAQ;AACf,UAAM;AAAA,EACR;AACA,MAAI;AACF,aAAS,YAAY,MAAM;AAAA,EAC7B,SAAS,KAAK;AAEZ,QAAI;AACF,eAAS,UAAU;AAAA,IACrB,QAAQ;AAAA,IAER;AACA,UAAM;AAAA,EACR;AACA,SAAO,EAAE,UAAU,QAAQ,QAAQ,UAAU,WAAW,SAAS;AACnE;","names":["InteractionState","label","ts","tpBar","tpBeat","offset","barIndexInSegment","beatInBar","newPeaks","result","x","generateId"]}