@waveform-playlist/recording 14.0.0-next.18 → 14.0.0-next.19

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -166,6 +166,7 @@ Manages microphone permission, device enumeration, and hot-plug detection.
166
166
  **Returns (`UseMicrophoneAccessReturn`):**
167
167
  - `stream: MediaStream | null`
168
168
  - `devices: MicrophoneDevice[]` — `{ deviceId, label, groupId }`
169
+ - `hasLabels: boolean` — `devices` names the real microphones. Browsers hide them until microphone permission is granted (usually one entry with an empty `deviceId`). In our runs (headless, fake devices) Chromium holding the permission named them before any stream was open, so a picker can offer them and `requestAccess(deviceId)` opens only the one chosen; Firefox and WebKit named them only once a stream was open
169
170
  - `hasPermission: boolean`
170
171
  - `isLoading: boolean`
171
172
  - `requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>`
@@ -226,7 +227,7 @@ Batteries-included hook: wires `useMicrophoneAccess` + `useMicrophoneLevel` + `u
226
227
  - `samplesPerPixel?: number` (default: `1024`)
227
228
  - `latencyOffset?: number` — seconds; overrides the auto-computed `outputLatency + lookAhead` compensation applied to the clip's start. `0` disables compensation; omit to auto-compute
228
229
 
229
- **Returns (`UseIntegratedRecordingReturn`):** recording state (`isRecording`, `isPaused`, `recordingTrackId`: the track the running take was started on, `null` when none is running), the two live sources (`meter`: microphone levels; `progress`: the take's elapsed time and per-channel preview peaks), microphone state (`stream`, `devices`, `hasPermission`, `selectedDevice`), controls (`startRecording` — resolves `true` when capture actually started, `false` with `error` set when the take is refused, `stopRecording`, `pauseRecording`, `resumeRecording`, `requestMicAccess`, `changeDevice`), and a combined `error`.
230
+ **Returns (`UseIntegratedRecordingReturn`):** recording state (`isRecording`, `isPaused`, `recordingTrackId`: the track the running take was started on, `null` when none is running), the two live sources (`meter`: microphone levels; `progress`: the take's elapsed time and per-channel preview peaks), microphone state (`stream`, `devices`, `hasLabels`, `hasPermission`, and `selectedDevice`: the id the open stream reports, `null` while no microphone is open; `'default'` in Chromium for the default microphone), controls (`startRecording` — resolves `true` when capture actually started, `false` with `error` set when the take is refused, `stopRecording`, `pauseRecording`, `resumeRecording`, `requestMicAccess`, `changeDevice`), and a combined `error`.
230
231
 
231
232
  **Recording into a `@waveform-playlist/browser` playlist:** call `useRecordingSession({ isRecording, trackId: recordingTrackId })` (from `@waveform-playlist/browser`) in the component that calls `useIntegratedRecording`; the view's `<WaveformRecordingPreview>` only draws the take. For an overdub, also call `useEditorControls().setRecordingActive(true, trackId)` *before* `play()` — while the session is active the end-of-timeline auto-stop is suppressed (the take can run past existing audio) and the recorded-over track plays muted for the take (punch-in replaces what it holds; `arrangement.setTrackRecording`, which leaves the track's own mute in the arrangement's mix alone): the mixer and the track's Mute button show it, the built-in `<TrackMuteButton />` is disabled, and `useTrack().isRecording` is true for it. A mute set on the track during the take stays after it. Both reset automatically when the recording ends; check `startRecording()`'s boolean and release the session on `false`. `play()` does nothing before the playlist's first ready, so a take started during the first load records without playback.
232
233
 
package/dist/index.d.mts CHANGED
@@ -58,6 +58,17 @@ interface UseRecordingReturn {
58
58
  interface UseMicrophoneAccessReturn {
59
59
  stream: MediaStream | null;
60
60
  devices: MicrophoneDevice[];
61
+ /**
62
+ * True when `devices` names the real microphones, with their ids and
63
+ * labels. Browsers hide them until microphone permission is granted (the
64
+ * list is then usually one entry with an empty `deviceId`). Chromium holding
65
+ * the permission listed them before any stream was open (headless runs with
66
+ * fake devices), so a picker can offer them and open only the one chosen,
67
+ * with `requestAccess(deviceId)`; Firefox and WebKit listed them only once a
68
+ * stream was open. Changes only when the list is read again (mount,
69
+ * `devicechange`, a grant), and not when an enumeration fails.
70
+ */
71
+ hasLabels: boolean;
61
72
  hasPermission: boolean;
62
73
  isLoading: boolean;
63
74
  requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
@@ -200,7 +211,21 @@ interface UseIntegratedRecordingReturn {
200
211
  error: Error | null;
201
212
  stream: MediaStream | null;
202
213
  devices: MicrophoneDevice[];
214
+ /** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
215
+ * microphones, so a picker can offer them before one is open and open only
216
+ * the one chosen, with `changeDevice(id)`. */
217
+ hasLabels: boolean;
203
218
  hasPermission: boolean;
219
+ /**
220
+ * The id of the microphone that is open: the device the stream's track
221
+ * reports (`getSettings().deviceId`), `null` while no stream is open (also
222
+ * while a request is opening one: it closes the open stream first). It is
223
+ * read from the stream, so it names the microphone that records; a picker
224
+ * shows it only when `devices` holds it. For a stream opened without an id
225
+ * (`requestMicAccess()`), Chromium reported `'default'`, the id of its list's
226
+ * default entry, and Firefox and WebKit the device's own id (headless runs
227
+ * with fake devices).
228
+ */
204
229
  selectedDevice: string | null;
205
230
  /** Start capturing on the selected track. Resolves `true` when the capture
206
231
  * pipeline actually started — callers that synchronize playback with
package/dist/index.d.ts CHANGED
@@ -58,6 +58,17 @@ interface UseRecordingReturn {
58
58
  interface UseMicrophoneAccessReturn {
59
59
  stream: MediaStream | null;
60
60
  devices: MicrophoneDevice[];
61
+ /**
62
+ * True when `devices` names the real microphones, with their ids and
63
+ * labels. Browsers hide them until microphone permission is granted (the
64
+ * list is then usually one entry with an empty `deviceId`). Chromium holding
65
+ * the permission listed them before any stream was open (headless runs with
66
+ * fake devices), so a picker can offer them and open only the one chosen,
67
+ * with `requestAccess(deviceId)`; Firefox and WebKit listed them only once a
68
+ * stream was open. Changes only when the list is read again (mount,
69
+ * `devicechange`, a grant), and not when an enumeration fails.
70
+ */
71
+ hasLabels: boolean;
61
72
  hasPermission: boolean;
62
73
  isLoading: boolean;
63
74
  requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
@@ -200,7 +211,21 @@ interface UseIntegratedRecordingReturn {
200
211
  error: Error | null;
201
212
  stream: MediaStream | null;
202
213
  devices: MicrophoneDevice[];
214
+ /** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
215
+ * microphones, so a picker can offer them before one is open and open only
216
+ * the one chosen, with `changeDevice(id)`. */
217
+ hasLabels: boolean;
203
218
  hasPermission: boolean;
219
+ /**
220
+ * The id of the microphone that is open: the device the stream's track
221
+ * reports (`getSettings().deviceId`), `null` while no stream is open (also
222
+ * while a request is opening one: it closes the open stream first). It is
223
+ * read from the stream, so it names the microphone that records; a picker
224
+ * shows it only when `devices` holds it. For a stream opened without an id
225
+ * (`requestMicAccess()`), Chromium reported `'default'`, the id of its list's
226
+ * default entry, and Firefox and WebKit the device's own id (headless runs
227
+ * with fake devices).
228
+ */
204
229
  selectedDevice: string | null;
205
230
  /** Start capturing on the selected track. Resolves `true` when the capture
206
231
  * pipeline actually started — callers that synchronize playback with
package/dist/index.js CHANGED
@@ -403,6 +403,7 @@ var import_core2 = require("@waveform-playlist/core");
403
403
  function useMicrophoneAccess() {
404
404
  const [stream, setStream] = (0, import_react2.useState)(null);
405
405
  const [devices, setDevices] = (0, import_react2.useState)([]);
406
+ const [hasLabels, setHasLabels] = (0, import_react2.useState)(false);
406
407
  const [hasPermission, setHasPermission] = (0, import_react2.useState)(false);
407
408
  const [isLoading, setIsLoading] = (0, import_react2.useState)(false);
408
409
  const [error, setError] = (0, import_react2.useState)(null);
@@ -411,8 +412,9 @@ function useMicrophoneAccess() {
411
412
  const isUnmountedRef = (0, import_react2.useRef)(false);
412
413
  const enumerateDevices = (0, import_react2.useCallback)(async () => {
413
414
  try {
414
- const { devices: audioInputs } = await (0, import_core2.enumerateMicrophones)();
415
+ const { devices: audioInputs, hasLabels: labelled } = await (0, import_core2.enumerateMicrophones)();
415
416
  setDevices(audioInputs);
417
+ setHasLabels(labelled);
416
418
  } catch (err) {
417
419
  console.warn("[waveform-playlist] Failed to enumerate devices:", String(err));
418
420
  setError(err instanceof Error ? err : new Error("Failed to enumerate devices"));
@@ -514,6 +516,7 @@ function useMicrophoneAccess() {
514
516
  return {
515
517
  stream,
516
518
  devices,
519
+ hasLabels,
517
520
  hasPermission,
518
521
  isLoading,
519
522
  requestAccess,
@@ -697,7 +700,6 @@ var import_playout3 = require("@waveform-playlist/playout");
697
700
  function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
698
701
  const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
699
702
  const audioResumedRef = (0, import_react4.useRef)(false);
700
- const [selectedDevice, setSelectedDevice] = (0, import_react4.useState)(null);
701
703
  const [hookError, setHookError] = (0, import_react4.useState)(null);
702
704
  const recordingStartTimeRef = (0, import_react4.useRef)(0);
703
705
  const recordingTrackIdRef = (0, import_react4.useRef)(null);
@@ -711,7 +713,15 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
711
713
  audioConstraintsRef.current = audioConstraints;
712
714
  const finishTakeRef = (0, import_react4.useRef)(() => {
713
715
  });
714
- const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();
716
+ const {
717
+ stream,
718
+ devices,
719
+ hasLabels,
720
+ hasPermission,
721
+ requestAccess,
722
+ error: micError
723
+ } = useMicrophoneAccess();
724
+ const selectedDevice = (0, import_react4.useMemo)(() => openDeviceId(stream), [stream]);
715
725
  const {
716
726
  meter,
717
727
  resetPeak,
@@ -837,12 +847,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
837
847
  }
838
848
  finishTakeRef.current(buffer);
839
849
  }, [stopRec]);
840
- (0, import_react4.useEffect)(() => {
841
- if (!hasPermission || devices.length === 0) return;
842
- if (selectedDevice === null || !devices.some((d) => d.deviceId === selectedDevice)) {
843
- setSelectedDevice(devices[0].deviceId);
844
- }
845
- }, [hasPermission, devices, selectedDevice]);
846
850
  const isRecordingRef = (0, import_react4.useRef)(isRecording);
847
851
  isRecordingRef.current = isRecording;
848
852
  const requestMicAccess = (0, import_react4.useCallback)(async () => {
@@ -852,7 +856,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
852
856
  }
853
857
  try {
854
858
  setHookError(null);
855
- setSelectedDevice(null);
856
859
  await requestAccess(void 0, audioConstraintsRef.current);
857
860
  await (0, import_playout3.resumeGlobalAudioContext)();
858
861
  audioResumedRef.current = true;
@@ -868,7 +871,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
868
871
  }
869
872
  try {
870
873
  setHookError(null);
871
- setSelectedDevice(deviceId);
872
874
  resetPeak();
873
875
  await requestAccess(deviceId, audioConstraintsRef.current);
874
876
  await (0, import_playout3.resumeGlobalAudioContext)();
@@ -892,6 +894,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
892
894
  // Microphone state
893
895
  stream,
894
896
  devices,
897
+ hasLabels,
895
898
  hasPermission,
896
899
  selectedDevice,
897
900
  // Recording controls
@@ -903,6 +906,10 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
903
906
  changeDevice
904
907
  };
905
908
  }
909
+ function openDeviceId(stream) {
910
+ const track = stream?.getAudioTracks()[0];
911
+ return track?.getSettings?.().deviceId || null;
912
+ }
906
913
 
907
914
  // src/hooks/useRecordingProgress.ts
908
915
  var import_ui_components = require("@waveform-playlist/ui-components");
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 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 // 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 // Counts the effect's setups. 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.\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 if (isRecordingRef.current || isStartingRef.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 (stream.getAudioTracks()[0]?.readyState === 'ended') {\n setError(\n new Error(\n 'The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again.'\n )\n );\n return false;\n }\n isStartingRef.current = true;\n const mountEpoch = mountEpochRef.current;\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\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 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 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 mountEpochRef.current += 1;\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 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 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.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 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 // 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 // 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 setHasPermission(false);\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 (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. 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) 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 // 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 setHasPermission(false);\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 { 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 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. 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 [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 // 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, 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 } = 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 || 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 (!audioResumedRef.current) {\n await resumeGlobalAudioContext();\n audioResumedRef.current = 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 startRecRef.current();\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]);\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 // What the picker shows: the first device of the list until the app chooses\n // one, and again when the one it showed has left the list. This only names\n // a device. The hook opens a microphone when the app asks for one\n // (requestMicAccess, changeDevice) and never by itself (maintainer, #944):\n // a microphone that is unplugged ends its stream, useMicrophoneAccess\n // clears it, and the app asks again.\n useEffect(() => {\n if (!hasPermission || devices.length === 0) return;\n if (selectedDevice === null || !devices.some((d) => d.deviceId === selectedDevice)) {\n setSelectedDevice(devices[0].deviceId);\n }\n }, [hasPermission, devices, selectedDevice]);\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: the selection is reset with it, so the\n // picker does not keep naming an earlier choice that is not the open\n // microphone (after a hide, or a changeDevice that failed). The effect\n // above selects the first of the list again; a specific microphone is\n // chosen with changeDevice(), by exact id (maintainer, #944).\n setSelectedDevice(null);\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 setSelectedDevice(deviceId);\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 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;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,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,I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+D,CAAC;AACvF;AAAA,IACF;AACA,QAAI;AACF,mBAAa,IAAI;AAOjB,wBAAkB,IAAI;AACtB,YAAM,cAAc,QAAW,oBAAoB,OAAO;AAC1D,gBAAM,0CAAyB;AAC/B,sBAAgB,UAAU;AAAA,IAC5B,SAAS,KAAK;AACZ,mBAAa,eAAe,QAAQ,MAAM,IAAI,MAAM,OAAO,GAAG,CAAC,CAAC;AAAA,IAClE;AAAA,EACF,GAAG,CAAC,aAAa,CAAC;AAGlB,QAAM,mBAAe;AAAA,IACnB,OAAO,aAAqB;AAE1B,UAAI,eAAe,SAAS;AAC1B,qBAAa,IAAI,MAAM,uDAAuD,CAAC;AAC/E;AAAA,MACF;AACA,UAAI;AACF,qBAAa,IAAI;AACjB,0BAAkB,QAAQ;AAC1B,kBAAU;AACV,cAAM,cAAc,UAAU,oBAAoB,OAAO;AACzD,kBAAM,0CAAyB;AAC/B,wBAAgB,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;;;AEjbA,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 // 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 // Counts the effect's setups. 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.\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 if (isRecordingRef.current || isStartingRef.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 (stream.getAudioTracks()[0]?.readyState === 'ended') {\n setError(\n new Error(\n 'The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again.'\n )\n );\n return false;\n }\n isStartingRef.current = true;\n const mountEpoch = mountEpochRef.current;\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\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 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 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 mountEpochRef.current += 1;\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 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 [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, 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 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 // 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 // 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 setHasPermission(false);\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 (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. 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) 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 // 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 setHasPermission(false);\n }\n };\n }, [enumerateDevices]);\n\n return {\n stream,\n devices,\n hasLabels,\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, 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 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 hasPermission: 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 // 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 // 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 {\n stream,\n devices,\n hasLabels,\n hasPermission,\n requestAccess,\n error: micError,\n } = 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 || 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 (!audioResumedRef.current) {\n await resumeGlobalAudioContext();\n audioResumedRef.current = 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 startRecRef.current();\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]);\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 hasPermission,\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,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;A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cAAM,cAAc,UAAU,oBAAoB,OAAO;AACzD,kBAAM,0CAAyB;AAC/B,wBAAgB,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,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;;;AElcA,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"]}
package/dist/index.mjs CHANGED
@@ -378,6 +378,7 @@ import { enumerateMicrophones } from "@waveform-playlist/core";
378
378
  function useMicrophoneAccess() {
379
379
  const [stream, setStream] = useState2(null);
380
380
  const [devices, setDevices] = useState2([]);
381
+ const [hasLabels, setHasLabels] = useState2(false);
381
382
  const [hasPermission, setHasPermission] = useState2(false);
382
383
  const [isLoading, setIsLoading] = useState2(false);
383
384
  const [error, setError] = useState2(null);
@@ -386,8 +387,9 @@ function useMicrophoneAccess() {
386
387
  const isUnmountedRef = useRef2(false);
387
388
  const enumerateDevices = useCallback2(async () => {
388
389
  try {
389
- const { devices: audioInputs } = await enumerateMicrophones();
390
+ const { devices: audioInputs, hasLabels: labelled } = await enumerateMicrophones();
390
391
  setDevices(audioInputs);
392
+ setHasLabels(labelled);
391
393
  } catch (err) {
392
394
  console.warn("[waveform-playlist] Failed to enumerate devices:", String(err));
393
395
  setError(err instanceof Error ? err : new Error("Failed to enumerate devices"));
@@ -489,6 +491,7 @@ function useMicrophoneAccess() {
489
491
  return {
490
492
  stream,
491
493
  devices,
494
+ hasLabels,
492
495
  hasPermission,
493
496
  isLoading,
494
497
  requestAccess,
@@ -603,7 +606,7 @@ function useMicrophoneLevel(stream, options = {}) {
603
606
  }
604
607
 
605
608
  // src/hooks/useIntegratedRecording.ts
606
- import { useState as useState4, useCallback as useCallback4, useEffect as useEffect4, useRef as useRef4 } from "react";
609
+ import { useState as useState4, useCallback as useCallback4, useMemo, useRef as useRef4 } from "react";
607
610
 
608
611
  // src/hooks/takeTarget.ts
609
612
  import {
@@ -686,7 +689,6 @@ import {
686
689
  function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
687
690
  const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
688
691
  const audioResumedRef = useRef4(false);
689
- const [selectedDevice, setSelectedDevice] = useState4(null);
690
692
  const [hookError, setHookError] = useState4(null);
691
693
  const recordingStartTimeRef = useRef4(0);
692
694
  const recordingTrackIdRef = useRef4(null);
@@ -700,7 +702,15 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
700
702
  audioConstraintsRef.current = audioConstraints;
701
703
  const finishTakeRef = useRef4(() => {
702
704
  });
703
- const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();
705
+ const {
706
+ stream,
707
+ devices,
708
+ hasLabels,
709
+ hasPermission,
710
+ requestAccess,
711
+ error: micError
712
+ } = useMicrophoneAccess();
713
+ const selectedDevice = useMemo(() => openDeviceId(stream), [stream]);
704
714
  const {
705
715
  meter,
706
716
  resetPeak,
@@ -826,12 +836,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
826
836
  }
827
837
  finishTakeRef.current(buffer);
828
838
  }, [stopRec]);
829
- useEffect4(() => {
830
- if (!hasPermission || devices.length === 0) return;
831
- if (selectedDevice === null || !devices.some((d) => d.deviceId === selectedDevice)) {
832
- setSelectedDevice(devices[0].deviceId);
833
- }
834
- }, [hasPermission, devices, selectedDevice]);
835
839
  const isRecordingRef = useRef4(isRecording);
836
840
  isRecordingRef.current = isRecording;
837
841
  const requestMicAccess = useCallback4(async () => {
@@ -841,7 +845,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
841
845
  }
842
846
  try {
843
847
  setHookError(null);
844
- setSelectedDevice(null);
845
848
  await requestAccess(void 0, audioConstraintsRef.current);
846
849
  await resumeGlobalAudioContext();
847
850
  audioResumedRef.current = true;
@@ -857,7 +860,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
857
860
  }
858
861
  try {
859
862
  setHookError(null);
860
- setSelectedDevice(deviceId);
861
863
  resetPeak();
862
864
  await requestAccess(deviceId, audioConstraintsRef.current);
863
865
  await resumeGlobalAudioContext();
@@ -881,6 +883,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
881
883
  // Microphone state
882
884
  stream,
883
885
  devices,
886
+ hasLabels,
884
887
  hasPermission,
885
888
  selectedDevice,
886
889
  // Recording controls
@@ -892,6 +895,10 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
892
895
  changeDevice
893
896
  };
894
897
  }
898
+ function openDeviceId(stream) {
899
+ const track = stream?.getAudioTracks()[0];
900
+ return track?.getSettings?.().deviceId || null;
901
+ }
895
902
 
896
903
  // src/hooks/useRecordingProgress.ts
897
904
  import { useThrottledValue } from "@waveform-playlist/ui-components";
@@ -1 +1 @@
1
- {"version":3,"sources":["../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 * 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 // 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 // Counts the effect's setups. 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.\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 if (isRecordingRef.current || isStartingRef.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 (stream.getAudioTracks()[0]?.readyState === 'ended') {\n setError(\n new Error(\n 'The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again.'\n )\n );\n return false;\n }\n isStartingRef.current = true;\n const mountEpoch = mountEpochRef.current;\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\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 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 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 mountEpochRef.current += 1;\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 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 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.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 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 // 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 // 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 setHasPermission(false);\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 (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. 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) 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 // 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 setHasPermission(false);\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 { 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 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. 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 [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 // 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, 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 } = 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 || 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 (!audioResumedRef.current) {\n await resumeGlobalAudioContext();\n audioResumedRef.current = 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 startRecRef.current();\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]);\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 // What the picker shows: the first device of the list until the app chooses\n // one, and again when the one it showed has left the list. This only names\n // a device. The hook opens a microphone when the app asks for one\n // (requestMicAccess, changeDevice) and never by itself (maintainer, #944):\n // a microphone that is unplugged ends its stream, useMicrophoneAccess\n // clears it, and the app asks again.\n useEffect(() => {\n if (!hasPermission || devices.length === 0) return;\n if (selectedDevice === null || !devices.some((d) => d.deviceId === selectedDevice)) {\n setSelectedDevice(devices[0].deviceId);\n }\n }, [hasPermission, devices, selectedDevice]);\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: the selection is reset with it, so the\n // picker does not keep naming an earlier choice that is not the open\n // microphone (after a hide, or a changeDevice that failed). The effect\n // above selects the first of the list again; a specific microphone is\n // chosen with changeDevice(), by exact id (maintainer, #944).\n setSelectedDevice(null);\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 setSelectedDevice(deviceId);\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 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":";AAIA,SAAS,UAAU,QAAQ,aAAa,iBAAiB;AAEzD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;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,IAAI,SAAS,KAAK;AACpD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,KAAK;AAC9C,QAAM,CAAC,aAAa,cAAc,IAAI,SAA6B,IAAI;AACvE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAuB,IAAI;AAIrD,QAAM,CAAC,EAAE,QAAQ,UAAU,SAAS,qBAAqB,CAAC,IAAI;AAAA,IAAS,MACrE,kBAAqC,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IACA;AAAA,IACA;AAAA,IACA;AAAA,EACF;AACF;;;AEjbA,SAAS,yBAAwD;AAQ1D,SAAS,qBACd,UACA,UAAoC,CAAC,GAClB;AACnB,SAAO,kBAAkB,UAAU,OAAO;AAC5C;","names":["error","useState","useEffect","useCallback","useRef","useEffect","useState","useRef","useCallback","getGlobalContext","createValueSource","useState","useCallback","useEffect","useRef","getGlobalContext","useRef","useState","useCallback","useEffect"]}
1
+ {"version":3,"sources":["../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 * 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 // 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 // Counts the effect's setups. 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.\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 if (isRecordingRef.current || isStartingRef.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 (stream.getAudioTracks()[0]?.readyState === 'ended') {\n setError(\n new Error(\n 'The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again.'\n )\n );\n return false;\n }\n isStartingRef.current = true;\n const mountEpoch = mountEpochRef.current;\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\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 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 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 mountEpochRef.current += 1;\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 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 [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, 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 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 // 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 // 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 setHasPermission(false);\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 (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. 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) 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 // 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 setHasPermission(false);\n }\n };\n }, [enumerateDevices]);\n\n return {\n stream,\n devices,\n hasLabels,\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, 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 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 hasPermission: 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 // 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 // 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 {\n stream,\n devices,\n hasLabels,\n hasPermission,\n requestAccess,\n error: micError,\n } = 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 || 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 (!audioResumedRef.current) {\n await resumeGlobalAudioContext();\n audioResumedRef.current = 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 startRecRef.current();\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]);\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 hasPermission,\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":";AAIA,SAAS,UAAU,QAAQ,aAAa,iBAAiB;AAEzD;AAAA,EACE;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,OAEK;AACP,SAAS,wBAAwB;AACjC,SAAS,iCAAiC;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,IAAI,SAAS,KAAK;AACpD,QAAM,CAAC,UAAU,WAAW,IAAI,SAAS,KAAK;AAC9C,QAAM,CAAC,aAAa,cAAc,IAAI,SAA6B,IAAI;AACvE,QAAM,CAAC,OAAO,QAAQ,IAAI,SAAuB,IAAI;AAIrD,QAAM,CAAC,EAAE,QAAQ,UAAU,SAAS,qBAAqB,CAAC,IAAI;AAAA,IAAS,MACrE,kBAAqC,EAAE,UAAU,GAAG,OAAO,CAAC,WAAW,IAAI,CAAC,EAAE,CAAC;AAAA,EACjF;AAKA,QAAM,mBAAmB,OAAgB,KAAK;AAG9C,QAAM,iBAAiB,OAAgC,IAAI;AAC3D,QAAM,uBAAuB,OAA0C,IAAI;AAE3E,QAAM,oBAAoB,OAAyB,CAAC,CAAC;AACrD,QAAM,kBAAkB,OAAO,CAAC;AAChC,QAAM,oBAAoB,OAAsB,IAAI;AACpD,QAAM,eAAe,OAAe,CAAC;AACrC,QAAM,iBAAiB,OAAgB,KAAK;AAC5C,QAAM,cAAc,OAAgB,KAAK;AACzC,QAAM,gBAAgB,OAAgC,IAAI;AAC1D,QAAM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B,QAAM,eAAeA;AAAA,IACnB,OAAO,aAAqB;AAE1B,UAAI,eAAe,SAAS;AAC1B,qBAAa,IAAI,MAAM,uDAAuD,CAAC;AAC/E;AAAA,MACF;AACA,UAAI;AACF,qBAAa,IAAI;AACjB,kBAAU;AACV,cAAM,cAAc,UAAU,oBAAoB,OAAO;AACzD,cAAM,yBAAyB;AAC/B,wBAAgB,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,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;;;AElcA,SAAS,yBAAwD;AAQ1D,SAAS,qBACd,UACA,UAAoC,CAAC,GAClB;AACnB,SAAO,kBAAkB,UAAU,OAAO;AAC5C;","names":["error","useState","useEffect","useCallback","useRef","useEffect","useState","useRef","useCallback","getGlobalContext","createValueSource","useState","useCallback","useRef","getGlobalContext","useRef","useState","useCallback"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@waveform-playlist/recording",
3
- "version": "14.0.0-next.18",
3
+ "version": "14.0.0-next.19",
4
4
  "description": "Audio recording support for waveform-playlist using AudioWorklet",
5
5
  "main": "./dist/index.js",
6
6
  "module": "./dist/index.mjs",
@@ -50,10 +50,10 @@
50
50
  },
51
51
  "dependencies": {
52
52
  "@waveform-playlist/core": "13.0.0-next.9",
53
- "@waveform-playlist/playout": "13.0.0-next.9",
53
+ "@waveform-playlist/ui-components": "15.0.0-next.14",
54
54
  "@waveform-playlist/engine": "14.0.0-next.7",
55
- "@waveform-playlist/worklets": "13.0.1-next.0",
56
- "@waveform-playlist/ui-components": "15.0.0-next.14"
55
+ "@waveform-playlist/playout": "13.0.0-next.9",
56
+ "@waveform-playlist/worklets": "13.0.1-next.0"
57
57
  },
58
58
  "peerDependencies": {
59
59
  "react": "^19.0.0",