@waveform-playlist/recording 14.0.0-next.2 → 14.0.0-next.21
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +10 -9
- package/dist/index.d.mts +42 -26
- package/dist/index.d.ts +42 -26
- package/dist/index.js +174 -76
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +175 -77
- package/dist/index.mjs.map +1 -1
- package/package.json +8 -7
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/hooks/useRecording.ts","../src/hooks/useMicrophoneAccess.ts","../src/hooks/useMicrophoneLevel.ts","../src/hooks/useIntegratedRecording.ts","../src/hooks/takeTarget.ts","../src/hooks/useRecordingProgress.ts"],"sourcesContent":["/**\n * @waveform-playlist/recording\n *\n * Audio recording support using AudioWorklet for waveform-playlist\n */\n\n// Hooks\nexport {\n useRecording,\n useMicrophoneAccess,\n useMicrophoneLevel,\n useIntegratedRecording,\n useRecordingProgress,\n} from './hooks';\nexport type {\n UseMicrophoneLevelOptions,\n UseMicrophoneLevelReturn,\n UseIntegratedRecordingReturn,\n IntegratedRecordingOptions,\n} from './hooks';\n\n// Types\nexport type {\n RecordingState,\n RecordingData,\n MicrophoneDevice,\n RecordingOptions,\n UseRecordingReturn,\n UseMicrophoneAccessReturn,\n} from './types';\n","/**\n * Main recording hook using AudioWorklet\n */\n\nimport { useState, useRef, useCallback, useEffect } from 'react';\nimport { UseRecordingReturn, RecordingOptions } from '../types';\nimport {\n concatenateAudioData,\n createAudioBuffer,\n appendPeaks,\n createValueSource,\n type RecordingProgress,\n} from '@waveform-playlist/core';\nimport { getGlobalContext } from '@waveform-playlist/playout';\nimport { addRecordingWorkletModule } from '@waveform-playlist/worklets';\n\nfunction emptyPeaks(bits: 8 | 16): Int8Array | Int16Array {\n return bits === 8 ? new Int8Array(0) : new Int16Array(0);\n}\n\nexport function useRecording(\n stream: MediaStream | null,\n options: RecordingOptions = {}\n): UseRecordingReturn {\n const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;\n\n // State\n const [isRecording, setIsRecording] = useState(false);\n const [isPaused, setIsPaused] = useState(false);\n const [audioBuffer, setAudioBuffer] = useState<AudioBuffer | null>(null);\n const [error, setError] = useState<Error | null>(null);\n // Elapsed time changes every animation frame and the per-channel preview\n // peaks on every worklet message, so both live in a source instead of\n // state: the component using this hook does not re-render while recording.\n const [{ source: progress, publish: publishProgressValue }] = useState(() =>\n createValueSource<RecordingProgress>({ duration: 0, peaks: [emptyPeaks(bits)] })\n );\n\n // Per-instance flag to prevent loading worklet multiple times within the same hook instance.\n // Note: Multiple hook instances each have their own ref — see \"Multi-Instance Worklet\n // Registration Gap\" in recording/CLAUDE.md for the known limitation and planned fix.\n const workletLoadedRef = useRef<boolean>(false);\n\n // Refs for AudioWorklet and data accumulation\n const workletNodeRef = useRef<AudioWorkletNode | null>(null);\n const mediaStreamSourceRef = useRef<MediaStreamAudioSourceNode | null>(null);\n // Per-channel sample accumulation: recordedChunksRef[channelIndex] = Float32Array[]\n const recordedChunksRef = useRef<Float32Array[][]>([]);\n const totalSamplesRef = useRef(0);\n const animationFrameRef = useRef<number | null>(null);\n const startTimeRef = useRef<number>(0);\n const isRecordingRef = useRef<boolean>(false);\n const isPausedRef = useRef<boolean>(false);\n const audioTrackRef = useRef<MediaStreamTrack | null>(null);\n const onTrackEndedRef = useRef<(() => void) | null>(null);\n const stopRecordingRef = useRef<(() => Promise<AudioBuffer | null>) | null>(null);\n // Resolved when the worklet posts the final done message after a stop command.\n const stopAckResolveRef = useRef<(() => void) | null>(null);\n // True from the start of stopRecording until it resolves. Distinct from\n // isPausedRef (user explicitly paused) — both freeze the duration tick,\n // but conflating them risks pauseRecording becoming a no-op while we're\n // stopping, or vice versa.\n const isStoppingRef = useRef<boolean>(false);\n // In-flight stop result — re-entrant stopRecording calls await this\n // instead of running a second handshake.\n const stopPromiseRef = useRef<Promise<AudioBuffer | null> | null>(null);\n // Assigned each render below (same pattern as stopRecordingRef) so the\n // stable stopRecording callback can invoke the handshake implementation.\n const finishStopRecordingRef = useRef<(() => Promise<AudioBuffer | null>) | null>(null);\n // Set synchronously at startRecording entry. isRecordingRef only flips\n // after several awaits — without this, two rapid start calls both pass\n // the guard and build two capture pipelines feeding one chunk store.\n const isStartingRef = useRef<boolean>(false);\n // Set by the unmount cleanup so a startRecording continuation that was\n // parked on an await doesn't build an ownerless capture graph.\n const isUnmountedRef = useRef<boolean>(false);\n // Elapsed seconds, and the preview peaks accumulated so far. Written by the\n // duration loop and the worklet handler; published together, at most once\n // per animation frame, by publishProgress.\n const durationRef = useRef<number>(0);\n const peaksRef = useRef<(Int8Array | Int16Array)[]>(progress.getSnapshot().peaks);\n\n const publishProgress = useCallback(() => {\n const current = progress.getSnapshot();\n if (current.duration === durationRef.current && current.peaks === peaksRef.current) return;\n publishProgressValue({ duration: durationRef.current, peaks: peaksRef.current });\n }, [progress, publishProgressValue]);\n\n // Shared duration update loop — starts a rAF loop that updates duration\n // from performance.now() and publishes the progress once per frame. Used by\n // both startRecording and resumeRecording.\n const startDurationLoop = useCallback(() => {\n const tick = () => {\n if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {\n durationRef.current = (performance.now() - startTimeRef.current) / 1000;\n publishProgress();\n animationFrameRef.current = requestAnimationFrame(tick);\n }\n };\n tick();\n }, [publishProgress]);\n\n // Load AudioWorklet module\n const loadWorklet = useCallback(async () => {\n // Skip if already loaded to prevent \"already registered\" error\n if (workletLoadedRef.current) {\n return;\n }\n\n try {\n const context = getGlobalContext();\n // Use addRecordingWorkletModule with rawContext.audioWorklet.addModule callback.\n // Can't use Tone.js addAudioWorkletModule — it caches a single _workletPromise\n // per context, silently skipping subsequent URLs.\n const rawCtx = context.rawContext as AudioContext;\n await addRecordingWorkletModule((url) => rawCtx.audioWorklet.addModule(url));\n workletLoadedRef.current = true;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to load AudioWorklet module:', String(err));\n const error = new Error('Failed to load recording processor: ' + String(err));\n throw error;\n }\n }, []);\n\n // Start recording. Resolves true when the capture pipeline started.\n const startRecording = useCallback(async (): Promise<boolean> => {\n if (isRecordingRef.current || isStartingRef.current) return false;\n if (!stream) {\n setError(new Error('No microphone stream available'));\n return false;\n }\n isStartingRef.current = true;\n\n try {\n setError(null);\n\n // Use Tone.js Context for cross-browser compatibility\n const context = getGlobalContext();\n\n // Resume AudioContext if suspended\n if (context.state === 'suspended') {\n await context.resume();\n }\n\n // Load worklet module\n await loadWorklet();\n\n // Unmounted while awaiting resume/module load — abort before any graph\n // nodes exist. A continuation past this point would start an ownerless\n // session: the rAF loop reschedules forever and chunks accumulate with\n // nothing left to stop them.\n if (isUnmountedRef.current) return false;\n\n // Create MediaStreamSource from Tone's context\n // Each hook creates its own source to avoid cross-context issues in Firefox\n const source = context.createMediaStreamSource(stream);\n mediaStreamSourceRef.current = source;\n\n // Use the stream track's actual channel count from getSettings().\n // source.channelCount defaults to 2 per Web Audio spec (not the mic's\n // real count). Fall back to user-provided channelCount if unavailable.\n const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;\n if (detectedChannelCount === undefined) {\n console.warn(\n `[waveform-playlist] Could not detect stream channel count, using fallback: ${channelCount}`\n );\n }\n const streamChannelCount = detectedChannelCount ?? channelCount;\n\n const workletNode = context.createAudioWorkletNode('recording-processor', {\n channelCount: streamChannelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n });\n workletNodeRef.current = workletNode;\n\n workletNode.onprocessorerror = (event) => {\n console.warn('[waveform-playlist] Recording worklet processor error:', String(event));\n setError(new Error('Recording processor encountered an error'));\n };\n\n // Reset state before connecting — prevents race where a worklet message\n // arrives before refs are cleared, corrupting samplesProcessedBefore calculations\n recordedChunksRef.current = Array.from({ length: streamChannelCount }, () => []);\n totalSamplesRef.current = 0;\n durationRef.current = 0;\n peaksRef.current = Array.from({ length: streamChannelCount }, () => emptyPeaks(bits));\n publishProgress();\n setAudioBuffer(null);\n\n // Listen for audio data from worklet\n workletNode.port.onmessage = (event: MessageEvent) => {\n const { channels, done } = event.data as {\n channels: Float32Array[];\n done?: boolean;\n };\n\n // Empty messages can arrive from the final stop ack when nothing was buffered.\n // Handle channels first if present, then resolve the stop barrier.\n if (channels && channels.length > 0 && channels[0] && channels[0].length > 0) {\n for (let ch = 0; ch < channels.length; ch++) {\n if (!recordedChunksRef.current[ch]) {\n console.warn(\n `[waveform-playlist] Unexpected channel ${ch} from worklet (expected ${recordedChunksRef.current.length})`\n );\n recordedChunksRef.current[ch] = [];\n }\n recordedChunksRef.current[ch].push(channels[ch]);\n }\n // Capture sample offset before incrementing — used by peak alignment\n const samplesProcessedBefore = totalSamplesRef.current;\n totalSamplesRef.current += channels[0].length;\n\n // Skip live-preview peak updates while stop is in flight. The\n // queue may have many flushes pending; updating peaks for each\n // would let the live-preview waveform grow visibly past where\n // the user stopped, only to be replaced moments later by the\n // final clip (which is shorter due to latency compensation).\n // Chunks are already pushed above so no audio is lost.\n if (stopAckResolveRef.current === null) {\n // A new outer array per message (one entry per channel); the\n // duration loop publishes it on the next frame.\n const previous = peaksRef.current;\n peaksRef.current = channels.map((channel, ch) =>\n appendPeaks(\n previous[ch] ?? emptyPeaks(bits),\n channel,\n samplesPerPixel,\n samplesProcessedBefore,\n bits\n )\n );\n // While paused the loop is not running; messages already queued\n // when the pause was sent still belong in the preview.\n if (isPausedRef.current) publishProgress();\n }\n }\n\n if (done) {\n stopAckResolveRef.current?.();\n stopAckResolveRef.current = null;\n }\n\n // Note: VU meter levels come from useMicrophoneLevel (meter-processor worklet)\n // We don't update level/peakLevel here to avoid conflicting state updates\n };\n\n // Connect and start — after state reset and handler setup\n source.connect(workletNode);\n // Do NOT send sampleRate — worklet uses its global sampleRate (always correct)\n workletNode.port.postMessage({ command: 'start', channelCount: streamChannelCount });\n\n // Listen on MediaStreamTrack for mic unplug (MediaStream has no 'ended' event)\n const audioTrack = stream.getAudioTracks()[0] ?? null;\n audioTrackRef.current = audioTrack;\n if (audioTrack) {\n const onEnded = () => {\n console.warn('[waveform-playlist] Audio track ended (mic unplugged or revoked)');\n // Stop recording to clean up worklet, rAF loop, and UI state\n stopRecordingRef.current?.();\n setError(new Error('Microphone disconnected during recording'));\n };\n onTrackEndedRef.current = onEnded;\n audioTrack.addEventListener('ended', onEnded);\n }\n\n isRecordingRef.current = true;\n isPausedRef.current = false;\n setIsRecording(true);\n setIsPaused(false);\n startTimeRef.current = performance.now();\n startDurationLoop();\n return true;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to start recording:', String(err));\n setError(err instanceof Error ? err : new Error('Failed to start recording'));\n return false;\n } finally {\n isStartingRef.current = false;\n }\n }, [\n stream,\n channelCount,\n samplesPerPixel,\n bits,\n loadWorklet,\n startDurationLoop,\n publishProgress,\n ]);\n\n // Stop recording\n const stopRecording = useCallback(async (): Promise<AudioBuffer | null> => {\n if (!isRecordingRef.current) {\n return null;\n }\n // Re-entrant stop (double-click, unmount cleanup while a stop is\n // pending): a second handshake would overwrite the ack resolver —\n // stranding the first call on its safety timeout — and post a redundant\n // stop command. Both callers observe the same in-flight stop.\n if (isStoppingRef.current) {\n return stopPromiseRef.current ?? null;\n }\n // Freeze the duration tick immediately so the live-preview width\n // (progress.duration * sampleRate) doesn't keep growing\n // during the worklet stop handshake / queue drain. isStoppingRef\n // stops the rAF tick from rescheduling; cancelling animationFrameRef\n // kills any frame already queued.\n isStoppingRef.current = true;\n const stopPromise = finishStopRecordingRef.current!();\n stopPromiseRef.current = stopPromise;\n return stopPromise;\n }, []);\n\n // The actual stop handshake — only ever invoked via stopRecording's\n // re-entrancy gate above.\n const finishStopRecording = useCallback(async (): Promise<AudioBuffer | null> => {\n try {\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n\n // Remove mic-unplug listener\n if (audioTrackRef.current && onTrackEndedRef.current) {\n audioTrackRef.current.removeEventListener('ended', onTrackEndedRef.current);\n audioTrackRef.current = null;\n onTrackEndedRef.current = null;\n }\n\n // Stop the worklet and wait for its final flush message before reading chunks.\n // Without the await, the partial buffer at the end of recording arrives after\n // the AudioBuffer is built and is silently dropped.\n // Snapshot the worklet node once — the drain loop yields the event loop\n // for up to 250ms, during which an unmount-cleanup could null the ref.\n const node = workletNodeRef.current;\n if (node) {\n const stopAck = new Promise<void>((resolve) => {\n stopAckResolveRef.current = resolve;\n });\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n // Safety timeout (1s) — purely a circuit breaker for a truly failed\n // worklet (crashed, context closed). The drain loop below catches\n // any straggler flush messages that were queued before the timeout\n // fired, so chunks are complete even when this fires.\n const timeout = new Promise<void>((resolve) => {\n timeoutId = setTimeout(resolve, 1000);\n });\n\n node.port.postMessage({ command: 'stop' });\n await Promise.race([stopAck, timeout]);\n clearTimeout(timeoutId);\n stopAckResolveRef.current = null;\n\n // Drain the event-loop queue. During recording the worklet posts a\n // flush every ~16ms; if main was slower than that, messages back up.\n // Yield repeatedly until totalSamplesRef stabilizes for several\n // consecutive ticks — at that point the queue is empty.\n let lastSamples = -1;\n let stable = 0;\n for (let i = 0; i < 50; i++) {\n if (totalSamplesRef.current === lastSamples) {\n if (++stable >= 3) break;\n } else {\n stable = 0;\n lastSamples = totalSamplesRef.current;\n }\n await new Promise<void>((r) => setTimeout(r, 5));\n }\n\n // Null the handler so any late delivery from this worklet doesn't\n // contaminate a subsequent recording session's chunks.\n node.port.onmessage = null;\n\n // Disconnect worklet from source\n if (mediaStreamSourceRef.current) {\n try {\n mediaStreamSourceRef.current.disconnect(node);\n } catch (err) {\n console.warn('[waveform-playlist] Source disconnect during stop:', String(err));\n }\n }\n node.disconnect();\n\n // Session fully torn down — null the refs so the unmount cleanup\n // doesn't post a redundant stop to the already-stopped worklet.\n workletNodeRef.current = null;\n mediaStreamSourceRef.current = null;\n }\n\n // Create final AudioBuffer from accumulated per-channel chunks\n const context = getGlobalContext();\n const rawContext = context.rawContext as AudioContext;\n const numChannels = recordedChunksRef.current.length || channelCount;\n const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));\n const totalSamples = channelData[0]?.length ?? 0;\n\n // Guard: if no samples were captured (e.g., stop called immediately after start),\n // return null instead of creating a 0-length AudioBuffer which throws\n if (totalSamples === 0) {\n console.warn('[waveform-playlist] Recording stopped with 0 samples captured — discarding');\n return null;\n }\n\n const buffer = createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);\n\n setAudioBuffer(buffer);\n durationRef.current = buffer.duration;\n publishProgress();\n\n return buffer;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to stop recording:', String(err));\n setError(err instanceof Error ? err : new Error('Failed to stop recording'));\n return null;\n } finally {\n // Always clear recording flags, even on failure — otherwise the UI gets\n // stuck in \"recording\" state if AudioBuffer creation throws.\n isRecordingRef.current = false;\n isPausedRef.current = false;\n isStoppingRef.current = false;\n setIsRecording(false);\n setIsPaused(false);\n }\n }, [channelCount, publishProgress]);\n stopRecordingRef.current = stopRecording;\n finishStopRecordingRef.current = finishStopRecording;\n\n // Pause recording — guards read refs, not state: a pause in the same tick\n // as start/resume closes over stale state and silently no-ops while the\n // worklet keeps capturing (only visible in the resulting buffer length).\n const pauseRecording = useCallback(() => {\n if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {\n workletNodeRef.current?.port.postMessage({ command: 'pause' });\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n isPausedRef.current = true;\n // The loop that publishes once per frame has just been cancelled: show\n // what arrived since its last frame.\n publishProgress();\n setIsPaused(true);\n }\n }, [publishProgress]);\n\n // Resume recording — same ref-based guards as pauseRecording.\n const resumeRecording = useCallback(() => {\n if (isRecordingRef.current && isPausedRef.current && !isStoppingRef.current) {\n workletNodeRef.current?.port.postMessage({ command: 'resume' });\n isPausedRef.current = false;\n setIsPaused(false);\n startTimeRef.current = performance.now() - durationRef.current * 1000;\n startDurationLoop();\n }\n }, [startDurationLoop]);\n\n // Cleanup on unmount — read refs in cleanup, not effect body.\n // Pattern #16 (copy refs in effect body) doesn't apply to [] deps — refs are\n // null at mount and only set later during startRecording.\n useEffect(() => {\n // Reset on (re)mount — StrictMode dev remounts reuse the same hook\n // instance, so a flag left true by the probe-unmount's cleanup would\n // make startRecording abort forever.\n isUnmountedRef.current = false;\n return () => {\n // Abort any startRecording continuation parked on an await — it must\n // not build the capture graph after unmount.\n isUnmountedRef.current = true;\n // Remove mic-unplug listener\n if (audioTrackRef.current && onTrackEndedRef.current) {\n audioTrackRef.current.removeEventListener('ended', onTrackEndedRef.current);\n }\n if (workletNodeRef.current) {\n workletNodeRef.current.port.postMessage({ command: 'stop' });\n // Nothing the worklet still sends may reach `progress`: a subscriber\n // can outlive this hook, and while paused a message publishes directly.\n workletNodeRef.current.port.onmessage = null;\n\n // Disconnect worklet from source\n if (mediaStreamSourceRef.current) {\n try {\n mediaStreamSourceRef.current.disconnect(workletNodeRef.current);\n } catch (err) {\n console.warn('[waveform-playlist] Source disconnect during cleanup:', String(err));\n }\n }\n try {\n workletNodeRef.current.disconnect();\n } catch (err) {\n console.warn('[waveform-playlist] Worklet disconnect during cleanup:', String(err));\n }\n }\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n }\n // Don't close the global AudioContext - it's shared across the app\n };\n }, []);\n\n return {\n isRecording,\n isPaused,\n progress,\n audioBuffer,\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n error,\n };\n}\n","/**\n * Hook for managing microphone access and device enumeration\n */\n\nimport { useState, useEffect, useCallback, useRef } from 'react';\nimport { enumerateMicrophones } from '@waveform-playlist/core';\nimport { UseMicrophoneAccessReturn, MicrophoneDevice } from '../types';\n\nexport function useMicrophoneAccess(): UseMicrophoneAccessReturn {\n const [stream, setStream] = useState<MediaStream | null>(null);\n const [devices, setDevices] = useState<MicrophoneDevice[]>([]);\n const [hasPermission, setHasPermission] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Mirrors the stream state so unmount cleanup and overlapping requests\n // operate on the CURRENT stream, not a stale closure capture.\n const streamRef = useRef<MediaStream | null>(null);\n // Generation token: bumped by every requestAccess (and by stopStream /\n // unmount). A getUserMedia grant belonging to an older generation is a\n // stale request — its stream must be stopped, not installed, or the mic\n // stays hot with no owner (permission prompt resolving after unmount,\n // or the slower of two overlapping requests).\n const requestGenerationRef = useRef(0);\n // Set by unmount cleanup (plain assignment — the exhaustive-deps rule\n // rejects read-modify-writes like a generation bump in cleanup functions).\n const isUnmountedRef = useRef(false);\n\n // Enumerate audio input devices — delegates to the framework-agnostic core\n // helper (redaction-aware fallback labels, SSR/insecure-context safe).\n const enumerateDevices = useCallback(async () => {\n try {\n const { devices: audioInputs } = await enumerateMicrophones();\n setDevices(audioInputs);\n } catch (err) {\n console.error('Failed to enumerate devices:', err);\n setError(err instanceof Error ? err : new Error('Failed to enumerate devices'));\n }\n }, []);\n\n // Request microphone access\n const requestAccess = useCallback(\n async (deviceId?: string, audioConstraints?: MediaTrackConstraints) => {\n const generation = ++requestGenerationRef.current;\n setIsLoading(true);\n setError(null);\n\n try {\n // Stop and clear the existing stream. Clearing state (not just\n // stopping tracks) matters on failure: consumers left holding a\n // stopped stream silently record silence with no error.\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n setStream(null);\n }\n\n // Build audio constraints\n const audio: MediaTrackConstraints & { latency?: number } = {\n // Recording-optimized defaults: prioritize raw audio quality and low latency\n echoCancellation: false,\n noiseSuppression: false,\n autoGainControl: false,\n latency: 0, // Low latency mode (not in TS types yet, but supported in modern browsers)\n // User-provided constraints override defaults\n ...audioConstraints,\n // Device ID override (if specified)\n ...(deviceId && { deviceId: { exact: deviceId } }),\n };\n\n const constraints: MediaStreamConstraints = {\n audio,\n video: false,\n };\n\n const newStream = await navigator.mediaDevices.getUserMedia(constraints);\n\n // Superseded by a newer request, stopStream, or unmount while the\n // permission prompt was open — stop the just-granted stream instead\n // of installing it (a hot mic nobody owns).\n if (generation !== requestGenerationRef.current || isUnmountedRef.current) {\n newStream.getTracks().forEach((track) => track.stop());\n return;\n }\n\n streamRef.current = newStream;\n setStream(newStream);\n setHasPermission(true);\n\n // Enumerate devices after getting permission (labels will be available)\n await enumerateDevices();\n } catch (err) {\n console.error('Failed to access microphone:', err);\n if (generation === requestGenerationRef.current) {\n setError(err instanceof Error ? err : new Error('Failed to access microphone'));\n setHasPermission(false);\n }\n } finally {\n if (generation === requestGenerationRef.current) {\n setIsLoading(false);\n }\n }\n },\n [enumerateDevices]\n );\n\n // Stop the stream and revoke access\n const stopStream = useCallback(() => {\n // Invalidate any in-flight request so a pending grant can't re-arm the mic\n requestGenerationRef.current++;\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n setStream(null);\n setHasPermission(false);\n }\n }, []);\n\n // Check initial permission state, enumerate devices, and listen for hot-plug changes\n useEffect(() => {\n // Reset on (re)mount — StrictMode dev remounts reuse the same hook\n // instance, so a flag left true by the probe-unmount's cleanup would\n // stop every future getUserMedia grant as \"stale\".\n isUnmountedRef.current = false;\n // Try to enumerate devices (labels won't be available without permission)\n enumerateDevices();\n\n // Re-enumerate when devices are plugged in or removed\n navigator.mediaDevices.addEventListener('devicechange', enumerateDevices);\n\n // Cleanup on unmount\n return () => {\n navigator.mediaDevices.removeEventListener('devicechange', enumerateDevices);\n // Invalidate any in-flight request (a grant arriving after unmount is\n // stopped by the isUnmounted check) and stop the current stream.\n isUnmountedRef.current = true;\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n }\n };\n }, [enumerateDevices]);\n\n return {\n stream,\n devices,\n hasPermission,\n isLoading,\n requestAccess,\n stopStream,\n error,\n };\n}\n","/**\n * Hook for monitoring microphone input levels\n *\n * Uses an AudioWorklet-based meter processor for sample-accurate\n * peak and RMS metering without requestAnimationFrame overhead.\n */\n\nimport { useEffect, useState, useRef, useCallback } from 'react';\nimport { getGlobalContext } from '@waveform-playlist/playout';\nimport {\n createValueSource,\n readMeterMessage,\n silentMeterLevels,\n type MeterLevels,\n type MeterSource,\n} from '@waveform-playlist/core';\nimport { addMeterWorkletModule, type MeterMessage } from '@waveform-playlist/worklets';\n\nexport interface UseMicrophoneLevelOptions {\n /**\n * How often to update the level (in Hz)\n * Default: 60 (60fps)\n */\n updateRate?: number;\n\n /**\n * Number of channels to meter (1 = mono, 2 = stereo)\n * Default: 1\n */\n channelCount?: number;\n}\n\nexport interface UseMicrophoneLevelReturn {\n /**\n * The live levels. Its identity is stable for the life of the hook, and the\n * hook does NOT re-render when levels change: pass it to\n * `<SegmentedVUMeter meter={meter} />`, call `meter.subscribe()`, or use\n * `useMeterLevels(meter)` for throttled React state.\n *\n * Each array has one entry per metered channel: the mic's auto-detected\n * channels, with mono repeated up to the requested `channelCount`. A mic\n * with MORE channels than `channelCount` yields one entry per actual channel.\n */\n meter: MeterSource;\n\n /**\n * Reset the held peak levels\n */\n resetPeak: () => void;\n\n /**\n * Error from meter setup (worklet load failure, context issues, etc.)\n * Null when metering is working normally.\n */\n error: Error | null;\n}\n\n/**\n * Monitor microphone input levels in real-time\n *\n * @param stream - MediaStream from getUserMedia\n * @param options - Configuration options\n * @returns A meter source, a peak reset, and any setup error\n *\n * @example\n * ```typescript\n * const { stream } = useMicrophoneAccess();\n * const { meter } = useMicrophoneLevel(stream, { channelCount: 2 });\n *\n * return <SegmentedVUMeter meter={meter} />;\n * ```\n */\nexport function useMicrophoneLevel(\n stream: MediaStream | null,\n options: UseMicrophoneLevelOptions = {}\n): UseMicrophoneLevelReturn {\n const { updateRate = 60, channelCount = 1 } = options;\n\n // Levels change ~60 times a second, so they live in a source, not in state.\n const [{ source: meter, publish }] = useState(() =>\n createValueSource<MeterLevels>(silentMeterLevels(channelCount))\n );\n const [meterError, setMeterError] = useState<Error | null>(null);\n\n const workletNodeRef = useRef<AudioWorkletNode | null>(null);\n const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);\n const smoothedPeakRef = useRef<number[]>([]);\n\n const resetPeak = useCallback(() => {\n const current = meter.getSnapshot();\n publish({ ...current, peakLevels: current.peakLevels.map(() => 0) });\n }, [meter, publish]);\n\n useEffect(() => {\n if (!stream) {\n smoothedPeakRef.current = [];\n publish(silentMeterLevels(channelCount));\n return;\n }\n\n let isMounted = true;\n\n const setupMonitoring = async () => {\n if (!isMounted) return;\n\n const context = getGlobalContext();\n if (context.state === 'suspended') {\n await context.resume();\n }\n if (!isMounted) return;\n\n // Auto-detect actual mic channel count from stream\n const trackSettings = stream.getAudioTracks()[0]?.getSettings();\n const actualChannels = trackSettings?.channelCount ?? channelCount;\n\n // Use addMeterWorkletModule with rawContext.audioWorklet.addModule callback.\n // Can't use Tone.js addAudioWorkletModule — it caches a single _workletPromise\n // per context, silently skipping subsequent URLs.\n const rawCtx = context.rawContext as AudioContext;\n await addMeterWorkletModule((url) => rawCtx.audioWorklet.addModule(url));\n if (!isMounted) return;\n\n // Use Tone.js's createAudioWorkletNode — avoids rawContext identity issues\n // in webpack-aliased environments (Docusaurus)\n const workletNode = context.createAudioWorkletNode('meter-processor', {\n channelCount: actualChannels,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n processorOptions: {\n numberOfChannels: actualChannels,\n updateRate,\n },\n });\n workletNodeRef.current = workletNode;\n\n workletNode.onprocessorerror = (event) => {\n console.warn('[waveform-playlist] Mic meter worklet processor error:', String(event));\n };\n\n // Create source and connect: source → meter\n // Don't connect output to destination — mic monitoring would cause feedback\n const source = context.createMediaStreamSource(stream);\n sourceRef.current = source;\n source.connect(workletNode);\n\n smoothedPeakRef.current = [];\n\n // Listen for meter data from worklet\n workletNode.port.onmessage = (event: MessageEvent) => {\n if (!isMounted) return;\n\n const reading = readMeterMessage({\n data: event.data as MeterMessage,\n previousSmoothedPeaks: smoothedPeakRef.current,\n heldPeakLevels: meter.getSnapshot().peakLevels,\n // Mirror mono to fill the requested channelCount\n minChannels: channelCount,\n });\n smoothedPeakRef.current = reading.smoothedPeaks;\n publish(reading.levels);\n };\n\n // Setup succeeded — clear any error from a previous failed attempt so\n // the UI doesn't show a permanent failure while metering works.\n setMeterError(null);\n };\n\n setupMonitoring().catch((err) => {\n console.warn('[waveform-playlist] Failed to set up mic level monitoring:', String(err));\n if (isMounted) {\n setMeterError(err instanceof Error ? err : new Error(String(err)));\n }\n });\n\n return () => {\n isMounted = false;\n\n if (sourceRef.current) {\n try {\n sourceRef.current.disconnect();\n } catch (err) {\n console.warn('[waveform-playlist] Mic source disconnect during cleanup:', String(err));\n }\n sourceRef.current = null;\n }\n\n if (workletNodeRef.current) {\n try {\n workletNodeRef.current.disconnect();\n workletNodeRef.current.port.close();\n } catch (err) {\n console.warn('[waveform-playlist] Mic meter disconnect during cleanup:', String(err));\n }\n workletNodeRef.current = null;\n }\n };\n }, [stream, updateRate, channelCount, meter, publish]);\n\n return {\n meter,\n resetPeak,\n error: meterError,\n };\n}\n","/**\n * Hook for integrated multi-track recording: the microphone, the take, and\n * the take added to the arrangement that owns the tracks (#812).\n */\n\nimport { useState, useCallback, useEffect, useRef } from 'react';\nimport { useRecording } from './useRecording';\nimport { useMicrophoneAccess } from './useMicrophoneAccess';\nimport { useMicrophoneLevel } from './useMicrophoneLevel';\nimport { takeNotSaved, takeRefusal, withTake } from './takeTarget';\nimport type { MicrophoneDevice } from '../types';\nimport {\n type AudioClip,\n type MeterSource,\n type RecordingProgressSource,\n resolveRecordingOffsetSamples,\n} from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport {\n resumeGlobalAudioContext,\n getGlobalAudioContext,\n getGlobalContext,\n} from '@waveform-playlist/playout';\n\nexport interface IntegratedRecordingOptions {\n /**\n * Current playback/cursor position in seconds.\n * Punch-in semantics (#579): the recorded clip lands exactly at this\n * position and REPLACES any existing clip content it overlaps — partial\n * overlaps are trimmed, fully-covered clips removed, spanning clips split.\n */\n currentTime?: number;\n\n /**\n * MediaTrackConstraints for audio recording\n * These will override the recording-optimized defaults (echo cancellation off, low latency)\n */\n audioConstraints?: MediaTrackConstraints;\n\n /**\n * Number of channels to record (1 = mono, 2 = stereo)\n * Default: 1 (mono)\n */\n channelCount?: number;\n\n /**\n * Samples per pixel for peak generation\n * Default: 1024\n */\n samplesPerPixel?: number;\n\n /**\n * Latency offset to skip at the start of the recording, in **seconds**.\n * Absolute replacement for the auto-computed `outputLatency + lookAhead` value\n * — use this to apply an externally-measured round-trip latency. `0` disables\n * compensation; when omitted, the auto-computed value is used. Pass the same\n * value into the preview's `recordingState.latencyOffset`\n * (`<WaveformRecordingPreview recordingState>`) so the live preview\n * matches the finalized clip. Negative or non-finite values are treated as 0.\n */\n latencyOffset?: number;\n}\n\nexport interface UseIntegratedRecordingReturn {\n // Recording state\n isRecording: boolean;\n isPaused: boolean;\n /**\n * The id of the track the running take will be added to: the track that was\n * selected when `startRecording()` was called, whatever is selected since.\n * `null` whenever `isRecording` is false. Use it, not the selected track,\n * for the live preview (`recordingState.trackId`).\n */\n recordingTrackId: string | null;\n /**\n * Live microphone levels (`useMicrophoneLevel`'s `meter`). The hook does not\n * re-render as they change: pass it to `<SegmentedVUMeter meter={meter} />`\n * or read it with `meter.subscribe()` / `useMeterLevels(meter)`.\n */\n meter: MeterSource;\n /**\n * Elapsed time and live-preview peaks of the take (`useRecording`'s\n * `progress`). The hook does not re-render as they change: pass it to\n * `<WaveformRecordingPreview recordingState={{ …, progress }} />` or read it with\n * `progress.subscribe()` / `useRecordingProgress(progress)`.\n */\n progress: RecordingProgressSource;\n error: Error | null;\n\n // Microphone state\n stream: MediaStream | null;\n devices: MicrophoneDevice[];\n hasPermission: boolean;\n selectedDevice: string | null;\n\n // Recording controls\n /** Start capturing on the selected track. Resolves `true` when the capture\n * pipeline actually started — callers that synchronize playback with\n * recording (overdub) should check this before starting playback.\n * Resolves `false` and sets `error`, recording nothing, when no track is\n * selected, when the arrangement holds no track of the selected id, for a\n * MIDI track, and for a track that holds a clip whose audio is not loaded\n * (still loading, failed to load, or a clip that cannot be made from it). */\n startRecording: () => Promise<boolean>;\n /** Stop the take and add it to the track it was started on, with one\n * `arrangement.updateTrack()`: one undo step. */\n stopRecording: () => void;\n pauseRecording: () => void;\n resumeRecording: () => void;\n requestMicAccess: () => Promise<void>;\n changeDevice: (deviceId: string) => Promise<void>;\n}\n\n/**\n * @param arrangement the owner of the tracks (`useCreateArrangement` from\n * `@waveform-playlist/browser`). The hook reads its tracks when a take starts\n * and ends and keeps no copy of them.\n * @param selectedTrackId the track the next take is recorded onto\n */\nexport function useIntegratedRecording(\n arrangement: Arrangement,\n selectedTrackId: string | null,\n options: IntegratedRecordingOptions = {}\n): UseIntegratedRecordingReturn {\n const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;\n\n // Track if we're currently monitoring (for auto-resume audio context)\n const [isMonitoring, setIsMonitoring] = useState(false);\n const [selectedDevice, setSelectedDevice] = useState<string | null>(null);\n const [hookError, setHookError] = useState<Error | null>(null);\n\n // Capture timeline position when recording starts (not at stop time)\n const recordingStartTimeRef = useRef(0);\n // The track the take was started on (an audio track: startRecording\n // checks). The take lands there whatever is selected when it stops: the\n // target cannot be switched mid-take, as in dawcore, where the session is\n // keyed by the track id.\n const recordingTrackIdRef = useRef<string | null>(null);\n const [recordingTrackId, setRecordingTrackId] = useState<string | null>(null);\n // True from the moment startRecording() begins its async startup until it\n // settles. isRecording only turns true a render after the startup succeeds,\n // so without this a second call in that window would re-capture the track.\n const isStartingRef = useRef(false);\n\n // Keep selectedTrackId and currentTime in refs for use in callbacks.\n // Avoids stale closures and keeps the callbacks from being recreated when\n // either changes (currentTime is the resting position: it changes on seek,\n // pause and stop, not while playing).\n const selectedTrackIdRef = useRef(selectedTrackId);\n selectedTrackIdRef.current = selectedTrackId;\n const currentTimeRef = useRef(currentTime);\n currentTimeRef.current = currentTime;\n\n // Microphone access\n const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();\n\n // Microphone level (for VU meter)\n const {\n meter,\n resetPeak,\n error: meterError,\n } = useMicrophoneLevel(stream, {\n channelCount: recordingOptions.channelCount,\n });\n\n // Recording\n const {\n isRecording,\n isPaused,\n progress,\n startRecording: startRec,\n stopRecording: stopRec,\n pauseRecording,\n resumeRecording,\n error: recError,\n } = useRecording(stream, recordingOptions);\n\n // Start recording handler. Reads selectedTrackId from its ref, and the\n // tracks from the arrangement as they are now: a track the app added in the\n // same handler is there (arrangement.addTrack is synchronous).\n const startRecording = useCallback(async (): Promise<boolean> => {\n // A take is running or starting: starting again must not re-capture its\n // track or its start position (useRecording would refuse further down,\n // after both had been overwritten).\n if (isRecordingRef.current || isStartingRef.current) return false;\n if (!selectedTrackIdRef.current) {\n setHookError(\n new Error('Cannot start recording: no track selected. Select or create a track first.')\n );\n return false;\n }\n // Refuse before anything is captured: a track that is not there, a MIDI\n // track (#756), a track holding a clip whose audio is not loaded.\n const refusal = takeRefusal(arrangement, selectedTrackIdRef.current);\n if (refusal) {\n setHookError(refusal);\n return false;\n }\n\n isStartingRef.current = true;\n try {\n setHookError(null);\n // Resume audio context if needed\n if (!isMonitoring) {\n await resumeGlobalAudioContext();\n setIsMonitoring(true);\n }\n\n // Capture timeline position NOW — before recording starts.\n // The position at stop time would be wrong: the caller may pass a new\n // `currentTime` (a seek, a pause) while the take is running.\n recordingStartTimeRef.current = currentTimeRef.current;\n recordingTrackIdRef.current = selectedTrackIdRef.current;\n setRecordingTrackId(selectedTrackIdRef.current);\n\n const started = await startRec();\n if (!started) setRecordingTrackId(null);\n return started;\n } catch (err) {\n setRecordingTrackId(null);\n setHookError(err instanceof Error ? err : new Error(String(err)));\n return false;\n } finally {\n isStartingRef.current = false;\n }\n }, [arrangement, isMonitoring, startRec]);\n\n // Stop recording and add the take to the track it was started on\n const stopRecording = useCallback(async () => {\n let buffer: AudioBuffer | null;\n try {\n buffer = await stopRec();\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n return;\n } finally {\n setRecordingTrackId(null);\n }\n\n // The track the take was started on, not the one selected now (#756),\n // read from the arrangement after the stop handshake (which can take more\n // than a second): an edit made meanwhile is in its tracks.\n const trackId = recordingTrackIdRef.current;\n if (buffer && trackId) {\n if (!arrangement.getTracks().some((t) => t.id === trackId)) {\n const err = new Error(\n `Recording completed but track \"${trackId}\" no longer exists. The recorded audio could not be saved.`\n );\n console.warn(`[waveform-playlist] ${err.message}`);\n setHookError(err);\n return;\n }\n\n // Use the start time captured when the take began, not the current `currentTime`.\n // Punch-in replace (#579): the take lands exactly here; overlapped\n // content is carved out below when the clip list is assembled.\n const startSample = Math.floor(recordingStartTimeRef.current * buffer.sampleRate);\n\n // Latency compensation: an explicit latencyOffset (seconds) replaces the\n // auto-computed outputLatency + lookAhead window. Shared resolver with the\n // live preview (`WaveformRecordingPreview`) — keep both using the same value so\n // trim widths match.\n const audioContext = getGlobalAudioContext();\n const outputLatency = audioContext.outputLatency ?? 0;\n const toneContext = getGlobalContext();\n const lookAhead = toneContext.lookAhead ?? 0;\n const latencyOffsetSamples = resolveRecordingOffsetSamples({\n overrideSeconds: latencyOffset,\n outputLatency,\n lookAhead,\n sampleRate: buffer.sampleRate,\n });\n\n // Guard: very short recordings (< latency compensation) would produce negative duration\n const effectiveDuration = Math.max(0, buffer.length - latencyOffsetSamples);\n if (effectiveDuration === 0) {\n console.warn(\n '[waveform-playlist] Recording too short for latency compensation — discarding'\n );\n setHookError(new Error('Recording was too short to save. Try recording for longer.'));\n return;\n }\n\n // Create new clip from recording\n const newClip: AudioClip = {\n id: `clip-${Date.now()}`,\n audioBuffer: buffer,\n startSample,\n durationSamples: effectiveDuration,\n offsetSamples: latencyOffsetSamples,\n sampleRate: buffer.sampleRate,\n sourceDurationSamples: buffer.length,\n gain: 1.0,\n name: `Recording ${new Date().toLocaleTimeString()}`,\n };\n\n // One edit, one undo step: the take, and the carve of what it overlaps.\n try {\n arrangement.updateTrack(trackId, (track) => withTake(track, newClip));\n } catch (err) {\n // The arrangement refused the track (its kind changed during the take).\n const notSaved = takeNotSaved(trackId, err);\n console.warn(`[waveform-playlist] ${notSaved.message}`);\n setHookError(notSaved);\n }\n }\n }, [arrangement, stopRec, latencyOffset]);\n\n // Auto-select first device when available, or fallback if selected device was unplugged\n useEffect(() => {\n if (!hasPermission || devices.length === 0) return;\n\n if (selectedDevice === null) {\n // First-time selection\n setSelectedDevice(devices[0].deviceId);\n } else if (!devices.some((d) => d.deviceId === selectedDevice)) {\n // Selected device was removed — fall back to first available\n const fallbackId = devices[0].deviceId;\n setSelectedDevice(fallbackId);\n resetPeak();\n requestAccess(fallbackId, audioConstraints);\n }\n }, [hasPermission, devices, selectedDevice, resetPeak, requestAccess, audioConstraints]);\n\n // Mirror isRecording for the device-switch guards below — reading the\n // state directly would churn the callbacks every recording toggle.\n const isRecordingRef = useRef(isRecording);\n isRecordingRef.current = isRecording;\n\n // Request microphone access\n const requestMicAccess = useCallback(async () => {\n // requestAccess stops the current stream's tracks, and track.stop() fires\n // no 'ended' event — the recording's source is never rewired, so the rest\n // of the take silently records silence. Refuse while recording.\n if (isRecordingRef.current) {\n setHookError(new Error('Cannot request microphone access while recording. Stop first.'));\n return;\n }\n try {\n setHookError(null);\n await requestAccess(undefined, audioConstraints);\n await resumeGlobalAudioContext();\n setIsMonitoring(true);\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n }, [requestAccess, audioConstraints]);\n\n // Change device\n const changeDevice = useCallback(\n async (deviceId: string) => {\n // Same silent-silence hazard as requestMicAccess above.\n if (isRecordingRef.current) {\n setHookError(new Error('Cannot switch microphone while recording. Stop first.'));\n return;\n }\n try {\n setHookError(null);\n setSelectedDevice(deviceId);\n resetPeak();\n await requestAccess(deviceId, audioConstraints);\n await resumeGlobalAudioContext();\n setIsMonitoring(true);\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n },\n [requestAccess, audioConstraints, resetPeak]\n );\n\n return {\n // Recording state\n isRecording,\n isPaused,\n // Only while a take is running: a take can also end without our\n // stopRecording (the microphone is unplugged and useRecording stops itself).\n recordingTrackId: isRecording ? recordingTrackId : null,\n meter,\n progress,\n error: hookError || micError || meterError || recError,\n\n // Microphone state\n stream,\n devices,\n hasPermission,\n selectedDevice,\n\n // Recording controls\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n requestMicAccess,\n changeDevice,\n };\n}\n","/**\n * The track a take is recorded onto, in the arrangement that owns it (#812):\n * whether a take may start there, and the track with the take added.\n */\nimport {\n type ArrangementTrack,\n type AudioClip,\n type LoadingClip,\n carveClipRange,\n isLoadingClip,\n trackKind,\n} from '@waveform-playlist/core';\nimport type { Arrangement, ArrangementSourceState } from '@waveform-playlist/engine';\n\nconst PREFIX = 'Cannot start recording: ';\n\nfunction label(track: ArrangementTrack): string {\n return '\"' + (track.name || track.id) + '\"';\n}\n\n/**\n * True when the source shows as failed because a clip of it could not be\n * made from its audio, not because its load failed. The arrangement names\n * such a failure `clip \"<id>\": <reason>`, after the first clip of the\n * current tracks it could not make from that source.\n */\nfunction isUnusableClipFailure(\n arrangement: Arrangement,\n clip: LoadingClip,\n state: ArrangementSourceState\n): boolean {\n const message = state.error?.message ?? '';\n return arrangement\n .getTracks()\n .some((t) =>\n t.clips.some(\n (c) => isLoadingClip(c) && c.src === clip.src && message.startsWith(`clip \"${c.id}\": `)\n )\n );\n}\n\n/** Why a take cannot be recorded over a clip whose audio is not loaded. */\nfunction loadingClipRefusal(\n arrangement: Arrangement,\n track: ArrangementTrack,\n clip: LoadingClip\n): Error {\n const state = arrangement.sources.getSnapshot().sources.get(clip.src);\n if (state?.status !== 'failed') {\n return new Error(\n `${PREFIX}${label(track)} holds a clip whose audio is still loading (\"${clip.id}\"). ` +\n 'Start the take once it has loaded.'\n );\n }\n const reason = state.error?.message ?? 'unknown error';\n if (isUnusableClipFailure(arrangement, clip, state)) {\n return new Error(\n `${PREFIX}a clip on ${label(track)} cannot be made from its audio (${reason}). ` +\n 'Correct or remove the clip.'\n );\n }\n return new Error(\n `${PREFIX}the audio of clip \"${clip.id}\" on ${label(track)} could not be loaded ` +\n `(${reason}). Retry it with arrangement.retry(), or remove the clip.`\n );\n}\n\n/**\n * Why a take cannot start on `trackId`, or `null` when it can. Read from the\n * arrangement's tracks as they are now.\n */\nexport function takeRefusal(arrangement: Arrangement, trackId: string): Error | null {\n const target = arrangement.getTracks().find((t) => t.id === trackId);\n if (!target) {\n return new Error(\n `${PREFIX}the selected track \"${trackId}\" is not in the arrangement. ` +\n 'Add it with arrangement.addTrack() first.'\n );\n }\n // A track holds one kind of clip (#756): a take is audio.\n if (trackKind(target) === 'midi') {\n return new Error(\n `${PREFIX}${label(target)} is a MIDI track. Select or create an audio track first.`\n );\n }\n // A punch-in carves the clips it overlaps, and only a loaded clip can be carved.\n const loading = target.clips.find(isLoadingClip);\n return loading ? loadingClipRefusal(arrangement, target, loading) : null;\n}\n\n/**\n * The error for a take the arrangement refused at the end (its track's kind\n * changed during the take): says the recorded audio is lost, and keeps the\n * arrangement's error as `cause`.\n */\nexport function takeNotSaved(trackId: string, refusal: unknown): Error {\n const cause = refusal instanceof Error ? refusal : new Error(String(refusal));\n return Object.assign(\n new Error(\n `Recording completed but the take could not be saved on track \"${trackId}\": ` + cause.message\n ),\n { cause }\n );\n}\n\n/**\n * The track with the take added: the take owns [start, start + duration) and\n * the loaded clips it overlaps are trimmed, removed or split (#579). A clip\n * that is still loading (one an undo brought back during the take) is kept\n * as it is.\n */\nexport function withTake(track: ArrangementTrack, take: AudioClip): ArrangementTrack {\n const loaded = track.clips.filter((c): c is AudioClip => !isLoadingClip(c));\n const loading = track.clips.filter(isLoadingClip);\n const end = take.startSample + take.durationSamples;\n return {\n ...track,\n clips: [...carveClipRange(loaded, take.startSample, end), ...loading, take],\n };\n}\n","import type { RecordingProgress, RecordingProgressSource } from '@waveform-playlist/core';\nimport { useThrottledValue, type UseThrottledValueOptions } from '@waveform-playlist/ui-components';\n\n/**\n * A recording's elapsed time and preview peaks as React state, at most\n * `updateRate` times a second (default 10). Use it for slow displays such as\n * an elapsed-time label; the live waveform takes the source itself\n * (`<WaveformRecordingPreview recordingState={{ …, progress }} />`).\n */\nexport function useRecordingProgress(\n progress: RecordingProgressSource,\n options: UseThrottledValueOptions = {}\n): RecordingProgress {\n return useThrottledValue(progress, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,mBAAyD;AAEzD,kBAMO;AACP,qBAAiC;AACjC,sBAA0C;AAE1C,SAAS,WAAW,MAAsC;AACxD,SAAO,SAAS,IAAI,IAAI,UAAU,CAAC,IAAI,IAAI,WAAW,CAAC;AACzD;AAEO,SAAS,aACd,QACA,UAA4B,CAAC,GACT;AACpB,QAAM,EAAE,eAAe,GAAG,kBAAkB,MAAM,OAAO,GAAG,IAAI;AAGhE,QAAM,CAAC,aAAa,cAAc,QAAI,uBAAS,KAAK;AACpD,QAAM,CAAC,UAAU,WAAW,QAAI,uBAAS,KAAK;AAC9C,QAAM,CAAC,aAAa,cAAc,QAAI,uBAA6B,IAAI;AACvE,QAAM,CAAC,OAAO,QAAQ,QAAI,uBAAuB,IAAI;AAIrD,QAAM,CAAC,EAAE,QAAQ,UAAU,SAAS,qBAAqB,CAAC,QAAI;AAAA,IAAS,UACrE,+BAAqC,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC;AAAA,EACjF;AAKA,QAAM,uBAAmB,qBAAgB,KAAK;AAG9C,QAAM,qBAAiB,qBAAgC,IAAI;AAC3D,QAAM,2BAAuB,qBAA0C,IAAI;AAE3E,QAAM,wBAAoB,qBAAyB,CAAC,CAAC;AACrD,QAAM,sBAAkB,qBAAO,CAAC;AAChC,QAAM,wBAAoB,qBAAsB,IAAI;AACpD,QAAM,mBAAe,qBAAe,CAAC;AACrC,QAAM,qBAAiB,qBAAgB,KAAK;AAC5C,QAAM,kBAAc,qBAAgB,KAAK;AACzC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AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;AE1YA,2BAAiE;AAQ1D,SAAS,qBACd,UACA,UAAoC,CAAC,GAClB;AACnB,aAAO,wCAAkB,UAAU,OAAO;AAC5C;","names":["error","import_react","import_core","import_react","import_playout","import_core","import_worklets","import_react","import_core","import_core","import_playout"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/hooks/useRecording.ts","../src/hooks/useMicrophoneAccess.ts","../src/hooks/useMicrophoneLevel.ts","../src/hooks/useIntegratedRecording.ts","../src/hooks/takeTarget.ts","../src/hooks/useRecordingProgress.ts"],"sourcesContent":["/**\n * @waveform-playlist/recording\n *\n * Audio recording support using AudioWorklet for waveform-playlist\n */\n\n// Hooks\nexport {\n useRecording,\n useMicrophoneAccess,\n useMicrophoneLevel,\n useIntegratedRecording,\n useRecordingProgress,\n} from './hooks';\nexport type {\n UseMicrophoneLevelOptions,\n UseMicrophoneLevelReturn,\n UseIntegratedRecordingReturn,\n IntegratedRecordingOptions,\n} from './hooks';\n\n// Types\nexport type {\n MicrophoneDevice,\n RecordingOptions,\n UseRecordingReturn,\n UseMicrophoneAccessReturn,\n} from './types';\n","/**\n * Main recording hook using AudioWorklet\n */\n\nimport { useState, useRef, useCallback, useEffect } from 'react';\nimport { UseRecordingReturn, RecordingOptions } from '../types';\nimport {\n concatenateAudioData,\n createAudioBuffer,\n appendPeaks,\n createValueSource,\n type RecordingProgress,\n} from '@waveform-playlist/core';\nimport { getGlobalContext } from '@waveform-playlist/playout';\nimport { addRecordingWorkletModule } from '@waveform-playlist/worklets';\n\nfunction emptyPeaks(bits: 8 | 16): Int8Array | Int16Array {\n return bits === 8 ? new Int8Array(0) : new Int16Array(0);\n}\n\n/**\n * Called with the take when it ends without a call to `stopRecording()`: the\n * microphone track ended, or the hook's effect cleanup ran mid-take (unmount,\n * Fast Refresh, a hidden `<Activity>`). `null` when no samples were captured.\n */\nexport type TakeEndedListener = (buffer: AudioBuffer | null) => void;\n\nexport function useRecording(\n stream: MediaStream | null,\n options: RecordingOptions = {}\n): UseRecordingReturn {\n return useRecordingWithTakeEnded(stream, options);\n}\n\n/**\n * `useRecording`, plus a listener for a take that ends by itself. Internal:\n * `useIntegratedRecording` uses it to add such a take to its track (#822).\n * The package exports `useRecording` only.\n */\nexport function useRecordingWithTakeEnded(\n stream: MediaStream | null,\n options: RecordingOptions = {},\n onTakeEnded?: TakeEndedListener\n): UseRecordingReturn {\n const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;\n\n // State\n const [isRecording, setIsRecording] = useState(false);\n const [isPaused, setIsPaused] = useState(false);\n const [audioBuffer, setAudioBuffer] = useState<AudioBuffer | null>(null);\n const [error, setError] = useState<Error | null>(null);\n // Elapsed time changes every animation frame and the per-channel preview\n // peaks on every worklet message, so both live in a source instead of\n // state: the component using this hook does not re-render while recording.\n const [{ source: progress, publish: publishProgressValue }] = useState(() =>\n createValueSource<RecordingProgress>({ duration: 0, peaks: [emptyPeaks(bits)] })\n );\n\n // Per-instance flag to prevent loading worklet multiple times within the same hook instance.\n // Note: Multiple hook instances each have their own ref — see \"Multi-Instance Worklet\n // Registration Gap\" in recording/CLAUDE.md for the known limitation and planned fix.\n const workletLoadedRef = useRef<boolean>(false);\n\n // Refs for AudioWorklet and data accumulation\n const workletNodeRef = useRef<AudioWorkletNode | null>(null);\n const mediaStreamSourceRef = useRef<MediaStreamAudioSourceNode | null>(null);\n // Per-channel sample accumulation: recordedChunksRef[channelIndex] = Float32Array[]\n const recordedChunksRef = useRef<Float32Array[][]>([]);\n const totalSamplesRef = useRef(0);\n const animationFrameRef = useRef<number | null>(null);\n const startTimeRef = useRef<number>(0);\n const isRecordingRef = useRef<boolean>(false);\n const isPausedRef = useRef<boolean>(false);\n const audioTrackRef = useRef<MediaStreamTrack | null>(null);\n const onTrackEndedRef = useRef<(() => void) | null>(null);\n const stopRecordingRef = useRef<(() => Promise<AudioBuffer | null>) | null>(null);\n // Resolved when the worklet posts the final done message after a stop command.\n const stopAckResolveRef = useRef<(() => void) | null>(null);\n // True from the start of stopRecording until it resolves. Distinct from\n // isPausedRef (user explicitly paused) — both freeze the duration tick,\n // but conflating them risks pauseRecording becoming a no-op while we're\n // stopping, or vice versa.\n const isStoppingRef = useRef<boolean>(false);\n // In-flight stop result — re-entrant stopRecording calls await this\n // instead of running a second handshake.\n const stopPromiseRef = useRef<Promise<AudioBuffer | null> | null>(null);\n // Assigned each render below (same pattern as stopRecordingRef) so the\n // stable stopRecording callback can invoke the handshake implementation.\n const finishStopRecordingRef = useRef<(() => Promise<AudioBuffer | null>) | null>(null);\n // The mount epoch of the start in progress, null when none. Set\n // synchronously at startRecording entry. isRecordingRef only flips after\n // several awaits — without this, two rapid start calls both pass the guard\n // and build two capture pipelines feeding one chunk store. A start parked\n // from before a cleanup does not block one made after it: it returns false\n // at its epoch check, the last step before building anything (#947).\n const startingEpochRef = useRef<number | null>(null);\n // Set by the unmount cleanup so a startRecording continuation that was\n // parked on an await doesn't build an ownerless capture graph.\n const isUnmountedRef = useRef<boolean>(false);\n // Counts the effect's cleanups. A startRecording that was parked on an await\n // across a cleanup and a new setup (Fast Refresh, an <Activity> hidden and\n // shown) finds isUnmountedRef reset; the count tells it the cleanup ran, and\n // with it the cleanup of whoever owns the stream, which stops it. Counted in\n // the cleanup, not the setup: a start made on mount before this hook's\n // effect runs (a child's effect, any layout effect) belongs to this mount\n // (#947).\n const mountEpochRef = useRef(0);\n // Elapsed seconds, and the preview peaks accumulated so far. Written by the\n // duration loop and the worklet handler; published together, at most once\n // per animation frame, by publishProgress.\n const durationRef = useRef<number>(0);\n // Read when a take ends by itself, which can be long after the render that\n // passed the listener.\n const onTakeEndedRef = useRef(onTakeEnded);\n onTakeEndedRef.current = onTakeEnded;\n const peaksRef = useRef<(Int8Array | Int16Array)[]>(progress.getSnapshot().peaks);\n\n const publishProgress = useCallback(() => {\n const current = progress.getSnapshot();\n if (current.duration === durationRef.current && current.peaks === peaksRef.current) return;\n publishProgressValue({ duration: durationRef.current, peaks: peaksRef.current });\n }, [progress, publishProgressValue]);\n\n // Shared duration update loop — starts a rAF loop that updates duration\n // from performance.now() and publishes the progress once per frame. Used by\n // both startRecording and resumeRecording.\n const startDurationLoop = useCallback(() => {\n const tick = () => {\n if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {\n durationRef.current = (performance.now() - startTimeRef.current) / 1000;\n publishProgress();\n animationFrameRef.current = requestAnimationFrame(tick);\n }\n };\n tick();\n }, [publishProgress]);\n\n // Load AudioWorklet module\n const loadWorklet = useCallback(async () => {\n // Skip if already loaded to prevent \"already registered\" error\n if (workletLoadedRef.current) {\n return;\n }\n\n try {\n const context = getGlobalContext();\n // Use addRecordingWorkletModule with rawContext.audioWorklet.addModule callback.\n // Can't use Tone.js addAudioWorkletModule — it caches a single _workletPromise\n // per context, silently skipping subsequent URLs.\n const rawCtx = context.rawContext as AudioContext;\n await addRecordingWorkletModule((url) => rawCtx.audioWorklet.addModule(url));\n workletLoadedRef.current = true;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to load AudioWorklet module:', String(err));\n const error = new Error('Failed to load recording processor: ' + String(err));\n throw error;\n }\n }, []);\n\n // Start recording. Resolves true when the capture pipeline started.\n const startRecording = useCallback(async (): Promise<boolean> => {\n const refuseEndedStream = (message: string): boolean => {\n if (stream?.getAudioTracks()[0]?.readyState !== 'ended') return false;\n setError(new Error(message));\n return true;\n };\n if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;\n if (!stream) {\n setError(new Error('No microphone stream available'));\n return false;\n }\n // An ended track delivers silence and fires no further event.\n // useMicrophoneAccess clears such a stream; one the app passes in itself\n // can still be ended. Refuse, in place of a silent take.\n if (\n refuseEndedStream(\n 'The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again.'\n )\n )\n return false;\n const mountEpoch = mountEpochRef.current;\n startingEpochRef.current = mountEpoch;\n\n try {\n setError(null);\n\n // Use Tone.js Context for cross-browser compatibility\n const context = getGlobalContext();\n\n // Resume AudioContext if suspended\n if (context.state === 'suspended') {\n await context.resume();\n }\n\n // Load worklet module\n await loadWorklet();\n\n // Unmounted while awaiting resume/module load — abort before any graph\n // nodes exist. A continuation past this point would start an ownerless\n // session: the rAF loop reschedules forever and chunks accumulate with\n // nothing left to stop them.\n // The same after a cleanup followed by a new setup: the take would read\n // a stream its owner stopped in that cleanup (#822).\n if (isUnmountedRef.current || mountEpoch !== mountEpochRef.current) return false;\n // The stream can have ended during the awaits: its owner opened another\n // microphone (a stopped track fires no `ended`), or it was unplugged\n // before the take's own listener exists. Refuse, in place of a take\n // that records silence and does not end by itself (#947).\n if (\n refuseEndedStream(\n 'The microphone changed or was disconnected while recording was starting. Start recording again.'\n )\n )\n return false;\n\n // Create MediaStreamSource from Tone's context\n // Each hook creates its own source to avoid cross-context issues in Firefox\n const source = context.createMediaStreamSource(stream);\n mediaStreamSourceRef.current = source;\n\n // Use the stream track's actual channel count from getSettings().\n // source.channelCount defaults to 2 per Web Audio spec (not the mic's\n // real count). Fall back to user-provided channelCount if unavailable.\n const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;\n if (detectedChannelCount === undefined) {\n console.warn(\n `[waveform-playlist] Could not detect stream channel count, using fallback: ${channelCount}`\n );\n }\n const streamChannelCount = detectedChannelCount ?? channelCount;\n\n const workletNode = context.createAudioWorkletNode('recording-processor', {\n channelCount: streamChannelCount,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n });\n workletNodeRef.current = workletNode;\n\n workletNode.onprocessorerror = (event) => {\n console.warn('[waveform-playlist] Recording worklet processor error:', String(event));\n setError(new Error('Recording processor encountered an error'));\n };\n\n // Reset state before connecting — prevents race where a worklet message\n // arrives before refs are cleared, corrupting samplesProcessedBefore calculations\n recordedChunksRef.current = Array.from({ length: streamChannelCount }, () => []);\n totalSamplesRef.current = 0;\n durationRef.current = 0;\n peaksRef.current = Array.from({ length: streamChannelCount }, () => emptyPeaks(bits));\n publishProgress();\n setAudioBuffer(null);\n\n // Listen for audio data from worklet\n workletNode.port.onmessage = (event: MessageEvent) => {\n const { channels, done } = event.data as {\n channels: Float32Array[];\n done?: boolean;\n };\n\n // Empty messages can arrive from the final stop ack when nothing was buffered.\n // Handle channels first if present, then resolve the stop barrier.\n if (channels && channels.length > 0 && channels[0] && channels[0].length > 0) {\n for (let ch = 0; ch < channels.length; ch++) {\n if (!recordedChunksRef.current[ch]) {\n console.warn(\n `[waveform-playlist] Unexpected channel ${ch} from worklet (expected ${recordedChunksRef.current.length})`\n );\n recordedChunksRef.current[ch] = [];\n }\n recordedChunksRef.current[ch].push(channels[ch]);\n }\n // Capture sample offset before incrementing — used by peak alignment\n const samplesProcessedBefore = totalSamplesRef.current;\n totalSamplesRef.current += channels[0].length;\n\n // Skip live-preview peak updates while stop is in flight. The\n // queue may have many flushes pending; updating peaks for each\n // would let the live-preview waveform grow visibly past where\n // the user stopped, only to be replaced moments later by the\n // final clip (which is shorter due to latency compensation).\n // Chunks are already pushed above so no audio is lost.\n if (stopAckResolveRef.current === null) {\n // A new outer array per message (one entry per channel); the\n // duration loop publishes it on the next frame.\n const previous = peaksRef.current;\n peaksRef.current = channels.map((channel, ch) =>\n appendPeaks(\n previous[ch] ?? emptyPeaks(bits),\n channel,\n samplesPerPixel,\n samplesProcessedBefore,\n bits\n )\n );\n // While paused the loop is not running; messages already queued\n // when the pause was sent still belong in the preview.\n if (isPausedRef.current) publishProgress();\n }\n }\n\n if (done) {\n stopAckResolveRef.current?.();\n stopAckResolveRef.current = null;\n }\n\n // Note: VU meter levels come from useMicrophoneLevel (meter-processor worklet)\n // We don't update level/peakLevel here to avoid conflicting state updates\n };\n\n // Connect and start — after state reset and handler setup\n source.connect(workletNode);\n // Do NOT send sampleRate — worklet uses its global sampleRate (always correct)\n workletNode.port.postMessage({ command: 'start', channelCount: streamChannelCount });\n\n // Listen on MediaStreamTrack for mic unplug (MediaStream has no 'ended' event)\n const audioTrack = stream.getAudioTracks()[0] ?? null;\n audioTrackRef.current = audioTrack;\n if (audioTrack) {\n const onEnded = () => {\n console.warn('[waveform-playlist] Audio track ended (mic unplugged or revoked)');\n // Stop recording to clean up worklet, rAF loop, and UI state. The\n // take up to here is kept: it is in `audioBuffer`, and goes to the\n // listener.\n const stopped = stopRecordingRef.current?.();\n setError(new Error('Microphone disconnected during recording'));\n stopped?.then((buffer) => onTakeEndedRef.current?.(buffer));\n };\n onTrackEndedRef.current = onEnded;\n audioTrack.addEventListener('ended', onEnded);\n }\n\n isRecordingRef.current = true;\n isPausedRef.current = false;\n setIsRecording(true);\n setIsPaused(false);\n startTimeRef.current = performance.now();\n startDurationLoop();\n return true;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to start recording:', String(err));\n setError(err instanceof Error ? err : new Error('Failed to start recording'));\n return false;\n } finally {\n // A start made after a cleanup owns the flag now.\n if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;\n }\n }, [\n stream,\n channelCount,\n samplesPerPixel,\n bits,\n loadWorklet,\n startDurationLoop,\n publishProgress,\n ]);\n\n // Stop recording\n const stopRecording = useCallback(async (): Promise<AudioBuffer | null> => {\n if (!isRecordingRef.current) {\n return null;\n }\n // Re-entrant stop (double-click, unmount cleanup while a stop is\n // pending): a second handshake would overwrite the ack resolver —\n // stranding the first call on its safety timeout — and post a redundant\n // stop command. Both callers observe the same in-flight stop.\n if (isStoppingRef.current) {\n return stopPromiseRef.current ?? null;\n }\n // Freeze the duration tick immediately so the live-preview width\n // (progress.duration * sampleRate) doesn't keep growing\n // during the worklet stop handshake / queue drain. isStoppingRef\n // stops the rAF tick from rescheduling; cancelling animationFrameRef\n // kills any frame already queued.\n isStoppingRef.current = true;\n const stopPromise = finishStopRecordingRef.current!();\n stopPromiseRef.current = stopPromise;\n return stopPromise;\n }, []);\n\n // The AudioBuffer of the chunks received so far; null when there are none\n // (stop called immediately after start): a 0-length AudioBuffer throws.\n const buildTakeBuffer = useCallback((): AudioBuffer | null => {\n const context = getGlobalContext();\n const rawContext = context.rawContext as AudioContext;\n const numChannels = recordedChunksRef.current.length || channelCount;\n const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));\n const totalSamples = channelData[0]?.length ?? 0;\n if (totalSamples === 0) {\n console.warn('[waveform-playlist] Recording stopped with 0 samples captured — discarding');\n return null;\n }\n return createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);\n }, [channelCount]);\n\n // The actual stop handshake — only ever invoked via stopRecording's\n // re-entrancy gate above.\n const finishStopRecording = useCallback(async (): Promise<AudioBuffer | null> => {\n try {\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n\n // Remove mic-unplug listener\n if (audioTrackRef.current && onTrackEndedRef.current) {\n audioTrackRef.current.removeEventListener('ended', onTrackEndedRef.current);\n audioTrackRef.current = null;\n onTrackEndedRef.current = null;\n }\n\n // Stop the worklet and wait for its final flush message before reading chunks.\n // Without the await, the partial buffer at the end of recording arrives after\n // the AudioBuffer is built and is silently dropped.\n // Snapshot the worklet node once — the drain loop yields the event loop\n // for up to 250ms, during which an unmount-cleanup could null the ref.\n const node = workletNodeRef.current;\n if (node) {\n const stopAck = new Promise<void>((resolve) => {\n stopAckResolveRef.current = resolve;\n });\n let timeoutId: ReturnType<typeof setTimeout> | undefined;\n // Safety timeout (1s) — purely a circuit breaker for a truly failed\n // worklet (crashed, context closed). The drain loop below catches\n // any straggler flush messages that were queued before the timeout\n // fired, so chunks are complete even when this fires.\n const timeout = new Promise<void>((resolve) => {\n timeoutId = setTimeout(resolve, 1000);\n });\n\n node.port.postMessage({ command: 'stop' });\n await Promise.race([stopAck, timeout]);\n clearTimeout(timeoutId);\n stopAckResolveRef.current = null;\n\n // Drain the event-loop queue. During recording the worklet posts a\n // flush every ~16ms; if main was slower than that, messages back up.\n // Yield repeatedly until totalSamplesRef stabilizes for several\n // consecutive ticks — at that point the queue is empty.\n let lastSamples = -1;\n let stable = 0;\n for (let i = 0; i < 50; i++) {\n if (totalSamplesRef.current === lastSamples) {\n if (++stable >= 3) break;\n } else {\n stable = 0;\n lastSamples = totalSamplesRef.current;\n }\n await new Promise<void>((r) => setTimeout(r, 5));\n }\n\n // Null the handler so any late delivery from this worklet doesn't\n // contaminate a subsequent recording session's chunks.\n node.port.onmessage = null;\n\n // Disconnect worklet from source\n if (mediaStreamSourceRef.current) {\n try {\n mediaStreamSourceRef.current.disconnect(node);\n } catch (err) {\n console.warn('[waveform-playlist] Source disconnect during stop:', String(err));\n }\n }\n node.disconnect();\n\n // Session fully torn down — null the refs so the unmount cleanup\n // doesn't post a redundant stop to the already-stopped worklet.\n workletNodeRef.current = null;\n mediaStreamSourceRef.current = null;\n }\n\n // Create final AudioBuffer from accumulated per-channel chunks\n const buffer = buildTakeBuffer();\n if (!buffer) return null;\n\n setAudioBuffer(buffer);\n durationRef.current = buffer.duration;\n publishProgress();\n\n return buffer;\n } catch (err) {\n console.warn('[waveform-playlist] Failed to stop recording:', String(err));\n setError(err instanceof Error ? err : new Error('Failed to stop recording'));\n return null;\n } finally {\n // Always clear recording flags, even on failure — otherwise the UI gets\n // stuck in \"recording\" state if AudioBuffer creation throws.\n isRecordingRef.current = false;\n isPausedRef.current = false;\n isStoppingRef.current = false;\n setIsRecording(false);\n setIsPaused(false);\n }\n }, [buildTakeBuffer, publishProgress]);\n stopRecordingRef.current = stopRecording;\n finishStopRecordingRef.current = finishStopRecording;\n const buildTakeBufferRef = useRef(buildTakeBuffer);\n buildTakeBufferRef.current = buildTakeBuffer;\n\n // Pause recording — guards read refs, not state: a pause in the same tick\n // as start/resume closes over stale state and silently no-ops while the\n // worklet keeps capturing (only visible in the resulting buffer length).\n const pauseRecording = useCallback(() => {\n if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {\n workletNodeRef.current?.port.postMessage({ command: 'pause' });\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n isPausedRef.current = true;\n // The loop that publishes once per frame has just been cancelled: show\n // what arrived since its last frame.\n publishProgress();\n setIsPaused(true);\n }\n }, [publishProgress]);\n\n // Resume recording — same ref-based guards as pauseRecording.\n const resumeRecording = useCallback(() => {\n if (isRecordingRef.current && isPausedRef.current && !isStoppingRef.current) {\n workletNodeRef.current?.port.postMessage({ command: 'resume' });\n isPausedRef.current = false;\n setIsPaused(false);\n startTimeRef.current = performance.now() - durationRef.current * 1000;\n startDurationLoop();\n }\n }, [startDurationLoop]);\n\n // Cleanup on unmount — read refs in cleanup, not effect body.\n // Pattern #16 (copy refs in effect body) doesn't apply to [] deps — refs are\n // null at mount and only set later during startRecording.\n useEffect(() => {\n // Reset on (re)mount — StrictMode dev remounts reuse the same hook\n // instance, so a flag left true by the probe-unmount's cleanup would\n // make startRecording abort forever.\n isUnmountedRef.current = false;\n // The cleanup moves the epoch on from this value (a plain assignment).\n const epoch = mountEpochRef.current;\n return () => {\n // Abort any startRecording continuation parked on an await — it must\n // not build the capture graph after unmount.\n isUnmountedRef.current = true;\n mountEpochRef.current = epoch + 1;\n // Remove mic-unplug listener\n if (audioTrackRef.current && onTrackEndedRef.current) {\n audioTrackRef.current.removeEventListener('ended', onTrackEndedRef.current);\n }\n if (workletNodeRef.current) {\n workletNodeRef.current.port.postMessage({ command: 'stop' });\n // Nothing the worklet still sends may reach `progress`: a subscriber\n // can outlive this hook, and while paused a message publishes directly.\n workletNodeRef.current.port.onmessage = null;\n\n // Disconnect worklet from source\n if (mediaStreamSourceRef.current) {\n try {\n mediaStreamSourceRef.current.disconnect(workletNodeRef.current);\n } catch (err) {\n console.warn('[waveform-playlist] Source disconnect during cleanup:', String(err));\n }\n }\n try {\n workletNodeRef.current.disconnect();\n } catch (err) {\n console.warn('[waveform-playlist] Worklet disconnect during cleanup:', String(err));\n }\n }\n if (animationFrameRef.current !== null) {\n cancelAnimationFrame(animationFrameRef.current);\n animationFrameRef.current = null;\n }\n // Don't close the global AudioContext - it's shared across the app\n\n // The same cleanup runs for Fast Refresh and a hidden <Activity>, after\n // which this hook lives on: the capture graph above is gone, so the take\n // is over and the state has to say so (#822). A stop already in flight\n // finishes by itself (its worklet no longer answers, so on its safety\n // timeout) and delivers the take to its caller.\n if (!isRecordingRef.current || isStoppingRef.current) return;\n isRecordingRef.current = false;\n isPausedRef.current = false;\n workletNodeRef.current = null;\n mediaStreamSourceRef.current = null;\n audioTrackRef.current = null;\n onTrackEndedRef.current = null;\n // What was received so far is the take. The worklet's last partial\n // flush and any message it had posted that was not delivered yet are\n // not in it: a cleanup cannot wait for the stop handshake and its drain.\n let buffer: AudioBuffer | null = null;\n try {\n buffer = buildTakeBufferRef.current();\n } catch (err) {\n console.warn('[waveform-playlist] Failed to keep the interrupted take:', String(err));\n }\n setIsRecording(false);\n setIsPaused(false);\n if (buffer) setAudioBuffer(buffer);\n try {\n onTakeEndedRef.current?.(buffer);\n } catch (err) {\n // A throw must not leave an effect cleanup.\n console.warn('[waveform-playlist] Failed to hand over the interrupted take:', String(err));\n }\n };\n }, []);\n\n return {\n isRecording,\n isPaused,\n progress,\n audioBuffer,\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n error,\n };\n}\n","/**\n * Hook for managing microphone access and device enumeration\n */\n\nimport { useState, useEffect, useCallback, useRef } from 'react';\nimport { enumerateMicrophones } from '@waveform-playlist/core';\nimport { UseMicrophoneAccessReturn, MicrophoneDevice } from '../types';\n\nexport function useMicrophoneAccess(): UseMicrophoneAccessReturn {\n const [stream, setStream] = useState<MediaStream | null>(null);\n const [devices, setDevices] = useState<MicrophoneDevice[]>([]);\n // Whether `devices` names the real microphones (core's `hasLabels`).\n const [hasLabels, setHasLabels] = useState(false);\n const [isLoading, setIsLoading] = useState(false);\n const [error, setError] = useState<Error | null>(null);\n\n // Mirrors the stream state so unmount cleanup and overlapping requests\n // operate on the CURRENT stream, not a stale closure capture.\n const streamRef = useRef<MediaStream | null>(null);\n // Generation token: bumped by every requestAccess (and by stopStream /\n // unmount). A getUserMedia grant belonging to an older generation is a\n // stale request — its stream must be stopped, not installed, or the mic\n // stays hot with no owner (permission prompt resolving after unmount,\n // or the slower of two overlapping requests).\n const requestGenerationRef = useRef(0);\n // Set by unmount cleanup (plain assignment — the exhaustive-deps rule\n // rejects read-modify-writes like a generation bump in cleanup functions).\n const isUnmountedRef = useRef(false);\n // Counts the mount effect's cleanups. A request saves it on entry: one that\n // started before a hide (or Fast Refresh) is stale after the show, though\n // the setup has reset isUnmountedRef by then (#947). No microphone is\n // opened for a hidden component; the app asks again (#822). Counted in the\n // cleanup, not the setup: a request made on mount before this hook's effect\n // runs (a child's effect, any layout effect) belongs to this mount.\n const mountEpochRef = useRef(0);\n\n // Enumerate audio input devices — delegates to the framework-agnostic core\n // helper (redaction-aware fallback labels, SSR/insecure-context safe).\n const enumerateDevices = useCallback(async () => {\n try {\n const { devices: audioInputs, hasLabels: labelled } = await enumerateMicrophones();\n setDevices(audioInputs);\n setHasLabels(labelled);\n } catch (err) {\n console.warn('[waveform-playlist] Failed to enumerate devices:', String(err));\n setError(err instanceof Error ? err : new Error('Failed to enumerate devices'));\n }\n }, []);\n\n // Request microphone access\n const requestAccess = useCallback(\n async (deviceId?: string, audioConstraints?: MediaTrackConstraints) => {\n const generation = ++requestGenerationRef.current;\n const mountEpoch = mountEpochRef.current;\n // Superseded by a newer request or stopStream, or begun before an\n // unmount or a hide: its result is not this hook's state any more.\n const isStale = () =>\n generation !== requestGenerationRef.current ||\n mountEpoch !== mountEpochRef.current ||\n isUnmountedRef.current;\n setIsLoading(true);\n setError(null);\n\n try {\n // Stop and clear the existing stream. Clearing state (not just\n // stopping tracks) matters on failure: consumers left holding a\n // stopped stream silently record silence with no error.\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n setStream(null);\n }\n\n // Build audio constraints\n const audio: MediaTrackConstraints & { latency?: number } = {\n // Recording-optimized defaults: prioritize raw audio quality and low latency\n echoCancellation: false,\n noiseSuppression: false,\n autoGainControl: false,\n latency: 0, // Low latency mode (not in TS types yet, but supported in modern browsers)\n // User-provided constraints override defaults\n ...audioConstraints,\n // Device ID override (if specified)\n ...(deviceId && { deviceId: { exact: deviceId } }),\n };\n\n const constraints: MediaStreamConstraints = {\n audio,\n video: false,\n };\n\n // Undefined on an insecure origin (http that is not localhost) and in\n // very old browsers: say so, in place of a TypeError about `undefined`.\n const mediaDevices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;\n if (!mediaDevices || typeof mediaDevices.getUserMedia !== 'function') {\n throw new Error(\n 'Microphone access is not available: navigator.mediaDevices is undefined. ' +\n 'It needs a secure context (https or localhost).'\n );\n }\n\n const newStream = await mediaDevices.getUserMedia(constraints);\n\n // Stale while the permission prompt was open: stop the just-granted\n // stream instead of installing it (a hot mic nobody owns).\n if (isStale()) {\n newStream.getTracks().forEach((track) => track.stop());\n return;\n }\n\n streamRef.current = newStream;\n setStream(newStream);\n\n // The microphone is unplugged, or its permission revoked: the track\n // ends and delivers silence from then on. The state must not keep\n // offering it, and nothing is opened in its place: the app asks again\n // (maintainer, #944). Our own track.stop() fires no `ended`, and a\n // stream that has been replaced since is not this hook's any more.\n const onEnded = () => {\n if (streamRef.current !== newStream) return;\n streamRef.current = null;\n setStream(null);\n setError(\n new Error(\n 'The microphone was disconnected or its permission was revoked. Request microphone access again.'\n )\n );\n };\n newStream\n .getTracks()\n .forEach((track) => track.addEventListener('ended', onEnded, { once: true }));\n\n // Enumerate devices after getting permission (labels will be available)\n await enumerateDevices();\n } catch (err) {\n console.warn('[waveform-playlist] Failed to access microphone:', String(err));\n if (!isStale()) {\n setError(err instanceof Error ? err : new Error('Failed to access microphone'));\n }\n } finally {\n // A newer request owns isLoading. stopStream and the cleanup have\n // already cleared it for the request they made stale.\n if (generation === requestGenerationRef.current) {\n setIsLoading(false);\n }\n }\n },\n [enumerateDevices]\n );\n\n // Stop the stream and revoke access\n const stopStream = useCallback(() => {\n // Invalidate any in-flight request so a pending grant can't re-arm the mic;\n // its finally no longer clears isLoading, so do it here (#947).\n requestGenerationRef.current++;\n setIsLoading(false);\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n setStream(null);\n }\n }, []);\n\n // Check initial permission state, enumerate devices, and listen for hot-plug changes\n useEffect(() => {\n // Reset on (re)mount — StrictMode dev remounts reuse the same hook\n // instance, so a flag left true by the probe-unmount's cleanup would\n // stop every future getUserMedia grant as \"stale\".\n isUnmountedRef.current = false;\n // The cleanup moves the epoch on from this value: a plain assignment\n // (see isUnmountedRef), and it makes every earlier request stale (#947).\n const epoch = mountEpochRef.current;\n // Try to enumerate devices (labels won't be available without permission)\n enumerateDevices();\n\n // Re-enumerate when devices are plugged in or removed. Undefined on an\n // insecure origin (http that is not localhost): nothing to listen to\n // there, and the enumeration above gave no devices.\n const mediaDevices = typeof navigator !== 'undefined' ? navigator.mediaDevices : undefined;\n mediaDevices?.addEventListener('devicechange', enumerateDevices);\n\n return () => {\n mediaDevices?.removeEventListener('devicechange', enumerateDevices);\n // Invalidate any in-flight request (a grant arriving after unmount is\n // stopped by the isUnmounted check, one arriving after a show by the\n // mount epoch) and stop the current stream.\n isUnmountedRef.current = true;\n mountEpochRef.current = epoch + 1;\n // The request it made stale will not clear isLoading.\n setIsLoading(false);\n if (streamRef.current) {\n streamRef.current.getTracks().forEach((track) => track.stop());\n streamRef.current = null;\n // This cleanup also runs for Fast Refresh and a hidden <Activity>,\n // after which the hook lives on: its state must not keep offering a\n // stopped stream (#822). As after stopStream(), the app asks again.\n setStream(null);\n }\n };\n }, [enumerateDevices]);\n\n return {\n stream,\n devices,\n hasLabels,\n isLoading,\n requestAccess,\n stopStream,\n error,\n };\n}\n","/**\n * Hook for monitoring microphone input levels\n *\n * Uses an AudioWorklet-based meter processor for sample-accurate\n * peak and RMS metering without requestAnimationFrame overhead.\n */\n\nimport { useEffect, useState, useRef, useCallback } from 'react';\nimport { getGlobalContext } from '@waveform-playlist/playout';\nimport {\n createValueSource,\n readMeterMessage,\n silentMeterLevels,\n type MeterLevels,\n type MeterSource,\n} from '@waveform-playlist/core';\nimport { addMeterWorkletModule, type MeterMessage } from '@waveform-playlist/worklets';\n\nexport interface UseMicrophoneLevelOptions {\n /**\n * How often to update the level (in Hz)\n * Default: 60 (60fps)\n */\n updateRate?: number;\n\n /**\n * Number of channels to meter (1 = mono, 2 = stereo)\n * Default: 1\n */\n channelCount?: number;\n}\n\nexport interface UseMicrophoneLevelReturn {\n /**\n * The live levels. Its identity is stable for the life of the hook, and the\n * hook does NOT re-render when levels change: pass it to\n * `<SegmentedVUMeter meter={meter} />`, call `meter.subscribe()`, or use\n * `useMeterLevels(meter)` for throttled React state.\n *\n * Each array has one entry per metered channel: the mic's auto-detected\n * channels, with mono repeated up to the requested `channelCount`. A mic\n * with MORE channels than `channelCount` yields one entry per actual channel.\n */\n meter: MeterSource;\n\n /**\n * Reset the held peak levels\n */\n resetPeak: () => void;\n\n /**\n * Error from meter setup (worklet load failure, context issues, etc.)\n * Null when metering is working normally.\n */\n error: Error | null;\n}\n\n/**\n * Monitor microphone input levels in real-time\n *\n * @param stream - MediaStream from getUserMedia\n * @param options - Configuration options\n * @returns A meter source, a peak reset, and any setup error\n *\n * @example\n * ```typescript\n * const { stream } = useMicrophoneAccess();\n * const { meter } = useMicrophoneLevel(stream, { channelCount: 2 });\n *\n * return <SegmentedVUMeter meter={meter} />;\n * ```\n */\nexport function useMicrophoneLevel(\n stream: MediaStream | null,\n options: UseMicrophoneLevelOptions = {}\n): UseMicrophoneLevelReturn {\n const { updateRate = 60, channelCount = 1 } = options;\n\n // Levels change ~60 times a second, so they live in a source, not in state.\n const [{ source: meter, publish }] = useState(() =>\n createValueSource<MeterLevels>(silentMeterLevels(channelCount))\n );\n const [meterError, setMeterError] = useState<Error | null>(null);\n\n const workletNodeRef = useRef<AudioWorkletNode | null>(null);\n const sourceRef = useRef<MediaStreamAudioSourceNode | null>(null);\n const smoothedPeakRef = useRef<number[]>([]);\n\n const resetPeak = useCallback(() => {\n const current = meter.getSnapshot();\n publish({ ...current, peakLevels: current.peakLevels.map(() => 0) });\n }, [meter, publish]);\n\n useEffect(() => {\n if (!stream) {\n smoothedPeakRef.current = [];\n publish(silentMeterLevels(channelCount));\n return;\n }\n\n let isMounted = true;\n\n const setupMonitoring = async () => {\n if (!isMounted) return;\n\n const context = getGlobalContext();\n if (context.state === 'suspended') {\n await context.resume();\n }\n if (!isMounted) return;\n\n // Auto-detect actual mic channel count from stream\n const trackSettings = stream.getAudioTracks()[0]?.getSettings();\n const actualChannels = trackSettings?.channelCount ?? channelCount;\n\n // Use addMeterWorkletModule with rawContext.audioWorklet.addModule callback.\n // Can't use Tone.js addAudioWorkletModule — it caches a single _workletPromise\n // per context, silently skipping subsequent URLs.\n const rawCtx = context.rawContext as AudioContext;\n await addMeterWorkletModule((url) => rawCtx.audioWorklet.addModule(url));\n if (!isMounted) return;\n\n // Use Tone.js's createAudioWorkletNode — avoids rawContext identity issues\n // in webpack-aliased environments (Docusaurus)\n const workletNode = context.createAudioWorkletNode('meter-processor', {\n channelCount: actualChannels,\n channelCountMode: 'explicit' as globalThis.ChannelCountMode,\n processorOptions: {\n numberOfChannels: actualChannels,\n updateRate,\n },\n });\n workletNodeRef.current = workletNode;\n\n workletNode.onprocessorerror = (event) => {\n console.warn('[waveform-playlist] Mic meter worklet processor error:', String(event));\n };\n\n // Create source and connect: source → meter\n // Don't connect output to destination — mic monitoring would cause feedback\n const source = context.createMediaStreamSource(stream);\n sourceRef.current = source;\n source.connect(workletNode);\n\n smoothedPeakRef.current = [];\n\n // Listen for meter data from worklet\n workletNode.port.onmessage = (event: MessageEvent) => {\n if (!isMounted) return;\n\n const reading = readMeterMessage({\n data: event.data as MeterMessage,\n previousSmoothedPeaks: smoothedPeakRef.current,\n heldPeakLevels: meter.getSnapshot().peakLevels,\n // Mirror mono to fill the requested channelCount\n minChannels: channelCount,\n });\n smoothedPeakRef.current = reading.smoothedPeaks;\n publish(reading.levels);\n };\n\n // Setup succeeded — clear any error from a previous failed attempt so\n // the UI doesn't show a permanent failure while metering works.\n setMeterError(null);\n };\n\n setupMonitoring().catch((err) => {\n console.warn('[waveform-playlist] Failed to set up mic level monitoring:', String(err));\n if (isMounted) {\n setMeterError(err instanceof Error ? err : new Error(String(err)));\n }\n });\n\n return () => {\n isMounted = false;\n\n if (sourceRef.current) {\n try {\n sourceRef.current.disconnect();\n } catch (err) {\n console.warn('[waveform-playlist] Mic source disconnect during cleanup:', String(err));\n }\n sourceRef.current = null;\n }\n\n if (workletNodeRef.current) {\n try {\n workletNodeRef.current.disconnect();\n workletNodeRef.current.port.close();\n } catch (err) {\n console.warn('[waveform-playlist] Mic meter disconnect during cleanup:', String(err));\n }\n workletNodeRef.current = null;\n }\n };\n }, [stream, updateRate, channelCount, meter, publish]);\n\n return {\n meter,\n resetPeak,\n error: meterError,\n };\n}\n","/**\n * Hook for integrated multi-track recording: the microphone, the take, and\n * the take added to the arrangement that owns the tracks (#812).\n */\n\nimport { useState, useCallback, useEffect, useMemo, useRef } from 'react';\nimport { useRecordingWithTakeEnded } from './useRecording';\nimport { useMicrophoneAccess } from './useMicrophoneAccess';\nimport { useMicrophoneLevel } from './useMicrophoneLevel';\nimport { takeNotSaved, takeRefusal, withTake } from './takeTarget';\nimport type { MicrophoneDevice } from '../types';\nimport {\n type AudioClip,\n type MeterSource,\n type RecordingProgressSource,\n resolveRecordingOffsetSamples,\n} from '@waveform-playlist/core';\nimport type { Arrangement } from '@waveform-playlist/engine';\nimport {\n resumeGlobalAudioContext,\n getGlobalAudioContext,\n getGlobalContext,\n} from '@waveform-playlist/playout';\n\nexport interface IntegratedRecordingOptions {\n /**\n * Current playback/cursor position in seconds.\n * Punch-in semantics (#579): the recorded clip lands exactly at this\n * position and REPLACES any existing clip content it overlaps — partial\n * overlaps are trimmed, fully-covered clips removed, spanning clips split.\n */\n currentTime?: number;\n\n /**\n * MediaTrackConstraints for audio recording\n * These will override the recording-optimized defaults (echo cancellation off, low latency)\n */\n audioConstraints?: MediaTrackConstraints;\n\n /**\n * Number of channels to record (1 = mono, 2 = stereo)\n * Default: 1 (mono)\n */\n channelCount?: number;\n\n /**\n * Samples per pixel for peak generation\n * Default: 1024\n */\n samplesPerPixel?: number;\n\n /**\n * Latency offset to skip at the start of the recording, in **seconds**.\n * Absolute replacement for the auto-computed `outputLatency + lookAhead` value\n * — use this to apply an externally-measured round-trip latency. `0` disables\n * compensation; when omitted, the auto-computed value is used. Pass the same\n * value into the preview's `recordingState.latencyOffset`\n * (`<WaveformRecordingPreview recordingState>`) so the live preview\n * matches the finalized clip. Negative or non-finite values are treated as 0.\n */\n latencyOffset?: number;\n}\n\nexport interface UseIntegratedRecordingReturn {\n // Recording state\n isRecording: boolean;\n isPaused: boolean;\n /**\n * The id of the track the running take will be added to: the track that was\n * selected when `startRecording()` was called, whatever is selected since.\n * `null` whenever `isRecording` is false. Use it, not the selected track,\n * for the live preview (`recordingState.trackId`).\n */\n recordingTrackId: string | null;\n /**\n * Live microphone levels (`useMicrophoneLevel`'s `meter`). The hook does not\n * re-render as they change: pass it to `<SegmentedVUMeter meter={meter} />`\n * or read it with `meter.subscribe()` / `useMeterLevels(meter)`.\n */\n meter: MeterSource;\n /**\n * Elapsed time and live-preview peaks of the take (`useRecording`'s\n * `progress`). The hook does not re-render as they change: pass it to\n * `<WaveformRecordingPreview recordingState={{ …, progress }} />` or read it with\n * `progress.subscribe()` / `useRecordingProgress(progress)`.\n */\n progress: RecordingProgressSource;\n error: Error | null;\n\n // Microphone state\n /** `useMicrophoneAccess`'s `stream`: the open microphone, `null` while none\n * is open. A microphone is open when `stream !== null`. */\n stream: MediaStream | null;\n devices: MicrophoneDevice[];\n /** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real\n * microphones, so a picker can offer them before one is open and open only\n * the one chosen, with `changeDevice(id)`. */\n hasLabels: boolean;\n /**\n * The id of the microphone that is open: the device the stream's track\n * reports (`getSettings().deviceId`), `null` while no stream is open (also\n * while a request is opening one: it closes the open stream first). It is\n * read from the stream, so it names the microphone that records; a picker\n * shows it only when `devices` holds it. For a stream opened without an id\n * (`requestMicAccess()`), Chromium reported `'default'`, the id of its list's\n * default entry, and Firefox and WebKit the device's own id (headless runs\n * with fake devices).\n */\n selectedDevice: string | null;\n\n // Recording controls\n /** Start capturing on the selected track. Resolves `true` when the capture\n * pipeline actually started — callers that synchronize playback with\n * recording (overdub) should check this before starting playback.\n * Resolves `false` and sets `error`, recording nothing, when no track is\n * selected, when the arrangement holds no track of the selected id, for a\n * MIDI track, and for a track that holds a clip whose audio is not loaded\n * (still loading, failed to load, or a clip that cannot be made from it). */\n startRecording: () => Promise<boolean>;\n /** Stop the take and add it to the track it was started on, with one\n * `arrangement.updateTrack()`: one undo step. Resolves when the take is on\n * its track (or was refused, with `error` set); it never rejects.\n *\n * A take that ends without this call is added the same way: when the\n * microphone is unplugged (`error` then says so), and when the component\n * using the hook unmounts or is hidden mid-take. */\n stopRecording: () => Promise<void>;\n pauseRecording: () => void;\n resumeRecording: () => void;\n requestMicAccess: () => Promise<void>;\n changeDevice: (deviceId: string) => Promise<void>;\n}\n\n/**\n * @param arrangement the owner of the tracks (`useCreateArrangement` from\n * `@waveform-playlist/browser`). The hook reads its tracks when a take starts\n * and ends and keeps no copy of them.\n * @param selectedTrackId the track the next take is recorded onto\n */\nexport function useIntegratedRecording(\n arrangement: Arrangement,\n selectedTrackId: string | null,\n options: IntegratedRecordingOptions = {}\n): UseIntegratedRecordingReturn {\n const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;\n\n // True once this hook has resumed the audio context. Nothing draws it, so\n // it is a ref: as state it gave startRecording a new identity.\n const audioResumedRef = useRef(false);\n const [hookError, setHookError] = useState<Error | null>(null);\n\n // Capture timeline position when recording starts (not at stop time)\n const recordingStartTimeRef = useRef(0);\n // The track the take was started on (an audio track: startRecording\n // checks). The take lands there whatever is selected when it stops: the\n // target cannot be switched mid-take, as in dawcore, where the session is\n // keyed by the track id.\n const recordingTrackIdRef = useRef<string | null>(null);\n const [recordingTrackId, setRecordingTrackId] = useState<string | null>(null);\n // The mount epoch of the startRecording() in progress, null when none:\n // set when its async startup begins, cleared when it settles. isRecording\n // only turns true a render after the startup succeeds, so without this a\n // second call in that window would re-capture the track. A start parked\n // from before a cleanup (a hide, Fast Refresh, StrictMode's) does not block\n // one made after it, and resolves false without touching its state (#947,\n // as in useRecording).\n const startingEpochRef = useRef<number | null>(null);\n // Moved on by the effect cleanup below. It must move with useRecording's\n // and useMicrophoneAccess's epochs (the same component's cleanups, in the\n // same commit): keep this effect's dependencies empty, as theirs are stable.\n const mountEpochRef = useRef(0);\n useEffect(() => {\n const epoch = mountEpochRef.current;\n return () => {\n mountEpochRef.current = epoch + 1;\n };\n }, []);\n\n // Keep selectedTrackId and currentTime in refs for use in callbacks.\n // Avoids stale closures and keeps the callbacks from being recreated when\n // either changes (currentTime is the resting position: it changes on seek,\n // pause and stop, not while playing).\n const selectedTrackIdRef = useRef(selectedTrackId);\n selectedTrackIdRef.current = selectedTrackId;\n const currentTimeRef = useRef(currentTime);\n currentTimeRef.current = currentTime;\n // The app usually writes the constraints inline, a new object each render.\n const audioConstraintsRef = useRef(audioConstraints);\n audioConstraintsRef.current = audioConstraints;\n\n // Assigned below, where finishTake is made; useRecording reads it when a\n // take ends by itself.\n const finishTakeRef = useRef<(buffer: AudioBuffer | null) => void>(() => {});\n\n // Microphone access\n const { stream, devices, hasLabels, requestAccess, error: micError } = useMicrophoneAccess();\n // The microphone that is open, read from its owner (#945). The hook keeps\n // no choice of its own: one it kept named another device than the open one\n // (the first of the list, a changeDevice that failed).\n const selectedDevice = useMemo(() => openDeviceId(stream), [stream]);\n\n // Microphone level (for VU meter)\n const {\n meter,\n resetPeak,\n error: meterError,\n } = useMicrophoneLevel(stream, {\n channelCount: recordingOptions.channelCount,\n });\n\n // Recording\n const {\n isRecording,\n isPaused,\n progress,\n startRecording: startRec,\n stopRecording: stopRec,\n pauseRecording,\n resumeRecording,\n error: recError,\n } = useRecordingWithTakeEnded(stream, recordingOptions, (buffer) =>\n // The take ended without our stopRecording(): keep it (#822).\n finishTakeRef.current(buffer)\n );\n // The start below can wait on the audio context first. It then calls the\n // startRec of the latest render: the one it closed over may hold a stream\n // that a cleanup has stopped meanwhile (a hide and a reveal).\n const startRecRef = useRef(startRec);\n startRecRef.current = startRec;\n\n // Start recording handler. Reads selectedTrackId from its ref, and the\n // tracks from the arrangement as they are now: a track the app added in the\n // same handler is there (arrangement.addTrack is synchronous).\n const startRecording = useCallback(async (): Promise<boolean> => {\n // A take is running or starting: starting again must not re-capture its\n // track or its start position (useRecording would refuse further down,\n // after both had been overwritten).\n if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;\n if (!selectedTrackIdRef.current) {\n setHookError(\n new Error('Cannot start recording: no track selected. Select or create a track first.')\n );\n return false;\n }\n // Refuse before anything is captured: a track that is not there, a MIDI\n // track (#756), a track holding a clip whose audio is not loaded.\n const refusal = takeRefusal(arrangement, selectedTrackIdRef.current);\n if (refusal) {\n setHookError(refusal);\n return false;\n }\n\n const mountEpoch = mountEpochRef.current;\n startingEpochRef.current = mountEpoch;\n // A cleanup ran since this start began: it is not this mount's any more.\n const isStale = () => mountEpoch !== mountEpochRef.current;\n try {\n setHookError(null);\n // Resume audio context if needed\n if (!audioResumedRef.current) {\n await resumeGlobalAudioContext();\n audioResumedRef.current = true;\n }\n // Before the track and the position are captured: they belong to a\n // start made after the cleanup, if there is one.\n if (isStale()) return false;\n\n // Capture timeline position NOW — before recording starts.\n // The position at stop time would be wrong: the caller may pass a new\n // `currentTime` (a seek, a pause) while the take is running.\n recordingStartTimeRef.current = currentTimeRef.current;\n recordingTrackIdRef.current = selectedTrackIdRef.current;\n setRecordingTrackId(selectedTrackIdRef.current);\n\n const started = await startRecRef.current();\n // useRecording refuses a start that a cleanup made stale, as here.\n if (!started && !isStale()) setRecordingTrackId(null);\n return started;\n } catch (err) {\n if (!isStale()) {\n setRecordingTrackId(null);\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n return false;\n } finally {\n // A start made after a cleanup owns the claim now.\n if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;\n }\n }, [arrangement]);\n\n // Add a finished take to the track it was started on. Called once per take\n // by whichever saw it end: stopRecording below, or useRecording when the\n // take ended by itself. Synchronous, so an effect cleanup can call it.\n const finishTake = useCallback(\n (buffer: AudioBuffer | null) => {\n // The track the take was started on, not the one selected now (#756).\n // Taken out of the ref: a Stop pressed while an unplug is being handled\n // receives the same buffer, and must not add it a second time.\n // Nothing was captured (also a stop while the next take is still\n // starting, which must leave that take's track alone): nothing to add.\n if (!buffer) return;\n const trackId = recordingTrackIdRef.current;\n recordingTrackIdRef.current = null;\n setRecordingTrackId(null);\n if (!trackId) return;\n\n // Read from the arrangement now, after the stop handshake (which can\n // take more than a second): an edit made meanwhile is in its tracks.\n if (!arrangement.getTracks().some((t) => t.id === trackId)) {\n const err = new Error(\n `Recording completed but track \"${trackId}\" no longer exists. The recorded audio could not be saved.`\n );\n console.warn(`[waveform-playlist] ${err.message}`);\n setHookError(err);\n return;\n }\n\n // Use the start time captured when the take began, not the current `currentTime`.\n // Punch-in replace (#579): the take lands exactly here; overlapped\n // content is carved out below when the clip list is assembled.\n const startSample = Math.floor(recordingStartTimeRef.current * buffer.sampleRate);\n\n // Latency compensation: an explicit latencyOffset (seconds) replaces the\n // auto-computed outputLatency + lookAhead window. Shared resolver with the\n // live preview (`WaveformRecordingPreview`) — keep both using the same value so\n // trim widths match.\n const audioContext = getGlobalAudioContext();\n const outputLatency = audioContext.outputLatency ?? 0;\n const toneContext = getGlobalContext();\n const lookAhead = toneContext.lookAhead ?? 0;\n const latencyOffsetSamples = resolveRecordingOffsetSamples({\n overrideSeconds: latencyOffset,\n outputLatency,\n lookAhead,\n sampleRate: buffer.sampleRate,\n });\n\n // Guard: very short recordings (< latency compensation) would produce negative duration\n const effectiveDuration = Math.max(0, buffer.length - latencyOffsetSamples);\n if (effectiveDuration === 0) {\n console.warn(\n '[waveform-playlist] Recording too short for latency compensation — discarding'\n );\n setHookError(new Error('Recording was too short to save. Try recording for longer.'));\n return;\n }\n\n // Create new clip from recording\n const newClip: AudioClip = {\n id: `clip-${Date.now()}`,\n audioBuffer: buffer,\n startSample,\n durationSamples: effectiveDuration,\n offsetSamples: latencyOffsetSamples,\n sampleRate: buffer.sampleRate,\n sourceDurationSamples: buffer.length,\n gain: 1.0,\n name: `Recording ${new Date().toLocaleTimeString()}`,\n };\n\n // One edit, one undo step: the take, and the carve of what it overlaps.\n try {\n arrangement.updateTrack(trackId, (track) => withTake(track, newClip));\n } catch (err) {\n // The arrangement refused the track (its kind changed during the take).\n const notSaved = takeNotSaved(trackId, err);\n console.warn(`[waveform-playlist] ${notSaved.message}`);\n setHookError(notSaved);\n }\n },\n [arrangement, latencyOffset]\n );\n finishTakeRef.current = finishTake;\n\n // Stop recording and add the take to the track it was started on\n const stopRecording = useCallback(async (): Promise<void> => {\n let buffer: AudioBuffer | null = null;\n try {\n buffer = await stopRec();\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n finishTakeRef.current(buffer);\n }, [stopRec]);\n\n // Mirror isRecording for the device-switch guards below — reading the\n // state directly would churn the callbacks every recording toggle.\n const isRecordingRef = useRef(isRecording);\n isRecordingRef.current = isRecording;\n\n // Request microphone access\n const requestMicAccess = useCallback(async () => {\n // requestAccess stops the current stream's tracks, and track.stop() fires\n // no 'ended' event — the recording's source is never rewired, so the rest\n // of the take silently records silence. Refuse while recording.\n if (isRecordingRef.current) {\n setHookError(new Error('Cannot request microphone access while recording. Stop first.'));\n return;\n }\n try {\n setHookError(null);\n // This opens the default device (or the one audioConstraints names),\n // whatever was chosen before; selectedDevice then names it. A specific\n // microphone is opened with changeDevice(), by exact id (maintainer,\n // #944). The hook opens a microphone only when the app asks, never by\n // itself: an unplugged one ends its stream, useMicrophoneAccess clears\n // it, and the app asks again.\n await requestAccess(undefined, audioConstraintsRef.current);\n await resumeGlobalAudioContext();\n audioResumedRef.current = true;\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n }, [requestAccess]);\n\n // Change device\n const changeDevice = useCallback(\n async (deviceId: string) => {\n // Same silent-silence hazard as requestMicAccess above.\n if (isRecordingRef.current) {\n setHookError(new Error('Cannot switch microphone while recording. Stop first.'));\n return;\n }\n try {\n setHookError(null);\n resetPeak();\n await requestAccess(deviceId, audioConstraintsRef.current);\n await resumeGlobalAudioContext();\n audioResumedRef.current = true;\n } catch (err) {\n setHookError(err instanceof Error ? err : new Error(String(err)));\n }\n },\n [requestAccess, resetPeak]\n );\n\n return {\n // Recording state\n isRecording,\n isPaused,\n // Only while a take is running: a take can also end without our\n // stopRecording (the microphone is unplugged and useRecording stops itself).\n recordingTrackId: isRecording ? recordingTrackId : null,\n meter,\n progress,\n error: hookError || micError || meterError || recError,\n\n // Microphone state\n stream,\n devices,\n hasLabels,\n selectedDevice,\n\n // Recording controls\n startRecording,\n stopRecording,\n pauseRecording,\n resumeRecording,\n requestMicAccess,\n changeDevice,\n };\n}\n\n/** The device the stream's microphone track reports; `null` without one. */\nfunction openDeviceId(stream: MediaStream | null): string | null {\n const track = stream?.getAudioTracks()[0];\n // getSettings is missing in very old browsers; an empty id names nothing.\n return track?.getSettings?.().deviceId || null;\n}\n","/**\n * The track a take is recorded onto, in the arrangement that owns it (#812):\n * whether a take may start there, and the track with the take added.\n */\nimport {\n type ArrangementTrack,\n type AudioClip,\n type LoadingClip,\n carveClipRange,\n isLoadingClip,\n trackKind,\n} from '@waveform-playlist/core';\nimport type { Arrangement, ArrangementSourceState } from '@waveform-playlist/engine';\n\nconst PREFIX = 'Cannot start recording: ';\n\nfunction label(track: ArrangementTrack): string {\n return '\"' + (track.name || track.id) + '\"';\n}\n\n/**\n * True when the source shows as failed because a clip of it could not be\n * made from its audio, not because its load failed. The arrangement names\n * such a failure `clip \"<id>\": <reason>`, after the first clip of the\n * current tracks it could not make from that source.\n */\nfunction isUnusableClipFailure(\n arrangement: Arrangement,\n clip: LoadingClip,\n state: ArrangementSourceState\n): boolean {\n const message = state.error?.message ?? '';\n return arrangement\n .getTracks()\n .some((t) =>\n t.clips.some(\n (c) => isLoadingClip(c) && c.src === clip.src && message.startsWith(`clip \"${c.id}\": `)\n )\n );\n}\n\n/** Why a take cannot be recorded over a clip whose audio is not loaded. */\nfunction loadingClipRefusal(\n arrangement: Arrangement,\n track: ArrangementTrack,\n clip: LoadingClip\n): Error {\n const state = arrangement.sources.getSnapshot().sources.get(clip.src);\n if (state?.status !== 'failed') {\n return new Error(\n `${PREFIX}${label(track)} holds a clip whose audio is still loading (\"${clip.id}\"). ` +\n 'Start the take once it has loaded.'\n );\n }\n const reason = state.error?.message ?? 'unknown error';\n if (isUnusableClipFailure(arrangement, clip, state)) {\n return new Error(\n `${PREFIX}a clip on ${label(track)} cannot be made from its audio (${reason}). ` +\n 'Correct or remove the clip.'\n );\n }\n return new Error(\n `${PREFIX}the audio of clip \"${clip.id}\" on ${label(track)} could not be loaded ` +\n `(${reason}). Retry it with arrangement.retry(), or remove the clip.`\n );\n}\n\n/**\n * Why a take cannot start on `trackId`, or `null` when it can. Read from the\n * arrangement's tracks as they are now.\n */\nexport function takeRefusal(arrangement: Arrangement, trackId: string): Error | null {\n const target = arrangement.getTracks().find((t) => t.id === trackId);\n if (!target) {\n return new Error(\n `${PREFIX}the selected track \"${trackId}\" is not in the arrangement. ` +\n 'Add it with arrangement.addTrack() first.'\n );\n }\n // A track holds one kind of clip (#756): a take is audio.\n if (trackKind(target) === 'midi') {\n return new Error(\n `${PREFIX}${label(target)} is a MIDI track. Select or create an audio track first.`\n );\n }\n // A punch-in carves the clips it overlaps, and only a loaded clip can be carved.\n const loading = target.clips.find(isLoadingClip);\n return loading ? loadingClipRefusal(arrangement, target, loading) : null;\n}\n\n/**\n * The error for a take the arrangement refused at the end (its track's kind\n * changed during the take): says the recorded audio is lost, and keeps the\n * arrangement's error as `cause`.\n */\nexport function takeNotSaved(trackId: string, refusal: unknown): Error {\n const cause = refusal instanceof Error ? refusal : new Error(String(refusal));\n return Object.assign(\n new Error(\n `Recording completed but the take could not be saved on track \"${trackId}\": ` + cause.message\n ),\n { cause }\n );\n}\n\n/**\n * The track with the take added: the take owns [start, start + duration) and\n * the loaded clips it overlaps are trimmed, removed or split (#579). A clip\n * that is still loading (one an undo brought back during the take) is kept\n * as it is.\n */\nexport function withTake(track: ArrangementTrack, take: AudioClip): ArrangementTrack {\n const loaded = track.clips.filter((c): c is AudioClip => !isLoadingClip(c));\n const loading = track.clips.filter(isLoadingClip);\n const end = take.startSample + take.durationSamples;\n return {\n ...track,\n clips: [...carveClipRange(loaded, take.startSample, end), ...loading, take],\n };\n}\n","import type { RecordingProgress, RecordingProgressSource } from '@waveform-playlist/core';\nimport { useThrottledValue, type UseThrottledValueOptions } from '@waveform-playlist/ui-components';\n\n/**\n * A recording's elapsed time and preview peaks as React state, at most\n * `updateRate` times a second (default 10). Use it for slow displays such as\n * an elapsed-time label; the live waveform takes the source itself\n * (`<WaveformRecordingPreview recordingState={{ …, progress }} />`).\n */\nexport function useRecordingProgress(\n progress: RecordingProgressSource,\n options: UseThrottledValueOptions = {}\n): RecordingProgress {\n return useThrottledValue(progress, options);\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACIA,mBAAyD;AAEzD,kBAMO;AACP,qBAAiC;AACjC,sBAA0C;AAE1C,SAAS,WAAW,MAAsC;AACxD,SAAO,SAAS,IAAI,IAAI,UAAU,CAAC,IAAI,IAAI,WAAW,CAAC;AACzD;AASO,SAAS,aACd,QACA,UAA4B,CAAC,GACT;AACpB,SAAO,0BAA0B,QAAQ,OAAO;AAClD;AAOO,SAAS,0BACd,QACA,UAA4B,CAAC,GAC7B,aACoB;AACpB,QAAM,EAAE,eAAe,GAAG,kBAAkB,MAAM,OAAO,GAAG,IAAI;AAGhE,QAAM,CAAC,aAAa,cAAc,QAAI,uBAAS,KAAK;AACpD,QAAM,CAAC,UAAU,W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UAAU;AAAA,MAC5B,SAAS,KAAK;AACZ,qBAAa,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;AAAA,MAClE;AAAA,IACF;AAAA,IACA,CAAC,eAAe,SAAS;AAAA,EAC3B;AAEA,SAAO;AAAA;AAAA,IAEL;AAAA,IACA;AAAA;AAAA;AAAA,IAGA,kBAAkB,cAAc,mBAAmB;AAAA,IACnD;AAAA,IACA;AAAA,IACA,OAAO,aAAa,YAAY,cAAc;AAAA;AAAA,IAG9C;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA;AAAA,IAGA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;AAGA,SAAS,aAAa,QAA2C;AAC/D,QAAM,QAAQ,QAAQ,eAAe,EAAE,CAAC;AAExC,SAAO,OAAO,cAAc,EAAE,YAAY;AAC5C;;;AEndA,2BAAiE;AAQ1D,SAAS,qBACd,UACA,UAAoC,CAAC,GAClB;AACnB,aAAO,wCAAkB,UAAU,OAAO;AAC5C;","names":["error","import_react","import_core","import_react","import_playout","import_core","import_worklets","import_react","import_core","import_core","import_playout"]}
|