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

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
@@ -42,14 +42,14 @@ import {
42
42
  } from '@waveform-playlist/recording';
43
43
 
44
44
  function RecordButton() {
45
- const { stream, hasPermission, requestAccess } = useMicrophoneAccess();
45
+ const { stream, requestAccess } = useMicrophoneAccess();
46
46
  const { isRecording, progress, startRecording, stopRecording } = useRecording(stream);
47
47
  // `progress` is a source ({ duration, peaks }), not state: useRecording does
48
48
  // not re-render as the take grows. This reads it 10 times a second.
49
49
  const { duration } = useRecordingProgress(progress);
50
50
 
51
51
  const handleRecord = async () => {
52
- if (!hasPermission) {
52
+ if (!stream) {
53
53
  await requestAccess();
54
54
  return;
55
55
  }
@@ -164,10 +164,9 @@ Stopping adds a new `AudioClip` to the track that was selected when the take STA
164
164
  Manages microphone permission, device enumeration, and hot-plug detection.
165
165
 
166
166
  **Returns (`UseMicrophoneAccessReturn`):**
167
- - `stream: MediaStream | null`
167
+ - `stream: MediaStream | null` — the open microphone, `null` while none is open (before a grant, while a request opens one, after `stopStream()`, a failed request, an unplug or a hide); `stream !== null` says a microphone is open
168
168
  - `devices: MicrophoneDevice[]` — `{ deviceId, label, groupId }`
169
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
170
- - `hasPermission: boolean`
171
170
  - `isLoading: boolean`
172
171
  - `requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>`
173
172
  - `stopStream: () => void`
@@ -227,7 +226,7 @@ Batteries-included hook: wires `useMicrophoneAccess` + `useMicrophoneLevel` + `u
227
226
  - `samplesPerPixel?: number` (default: `1024`)
228
227
  - `latencyOffset?: number` — seconds; overrides the auto-computed `outputLatency + lookAhead` compensation applied to the clip's start. `0` disables compensation; omit to auto-compute
229
228
 
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`.
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`, `null` while no microphone is open, `devices`, `hasLabels`, 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`.
231
230
 
232
231
  **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.
233
232
 
package/dist/index.d.mts CHANGED
@@ -56,6 +56,13 @@ interface UseRecordingReturn {
56
56
  error: Error | null;
57
57
  }
58
58
  interface UseMicrophoneAccessReturn {
59
+ /**
60
+ * The open microphone, `null` while none is open: before the first grant,
61
+ * while a request is opening one (it stops the previous stream first),
62
+ * after `stopStream()`, a failed request, an unplug, or a hide. Test
63
+ * `stream !== null` to know whether a microphone is open (#947 removed
64
+ * `hasPermission`, a second copy of that).
65
+ */
59
66
  stream: MediaStream | null;
60
67
  devices: MicrophoneDevice[];
61
68
  /**
@@ -69,7 +76,6 @@ interface UseMicrophoneAccessReturn {
69
76
  * `devicechange`, a grant), and not when an enumeration fails.
70
77
  */
71
78
  hasLabels: boolean;
72
- hasPermission: boolean;
73
79
  isLoading: boolean;
74
80
  requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
75
81
  stopStream: () => void;
@@ -209,13 +215,14 @@ interface UseIntegratedRecordingReturn {
209
215
  */
210
216
  progress: RecordingProgressSource;
211
217
  error: Error | null;
218
+ /** `useMicrophoneAccess`'s `stream`: the open microphone, `null` while none
219
+ * is open. A microphone is open when `stream !== null`. */
212
220
  stream: MediaStream | null;
213
221
  devices: MicrophoneDevice[];
214
222
  /** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
215
223
  * microphones, so a picker can offer them before one is open and open only
216
224
  * the one chosen, with `changeDevice(id)`. */
217
225
  hasLabels: boolean;
218
- hasPermission: boolean;
219
226
  /**
220
227
  * The id of the microphone that is open: the device the stream's track
221
228
  * reports (`getSettings().deviceId`), `null` while no stream is open (also
package/dist/index.d.ts CHANGED
@@ -56,6 +56,13 @@ interface UseRecordingReturn {
56
56
  error: Error | null;
57
57
  }
58
58
  interface UseMicrophoneAccessReturn {
59
+ /**
60
+ * The open microphone, `null` while none is open: before the first grant,
61
+ * while a request is opening one (it stops the previous stream first),
62
+ * after `stopStream()`, a failed request, an unplug, or a hide. Test
63
+ * `stream !== null` to know whether a microphone is open (#947 removed
64
+ * `hasPermission`, a second copy of that).
65
+ */
59
66
  stream: MediaStream | null;
60
67
  devices: MicrophoneDevice[];
61
68
  /**
@@ -69,7 +76,6 @@ interface UseMicrophoneAccessReturn {
69
76
  * `devicechange`, a grant), and not when an enumeration fails.
70
77
  */
71
78
  hasLabels: boolean;
72
- hasPermission: boolean;
73
79
  isLoading: boolean;
74
80
  requestAccess: (deviceId?: string, audioConstraints?: MediaTrackConstraints) => Promise<void>;
75
81
  stopStream: () => void;
@@ -209,13 +215,14 @@ interface UseIntegratedRecordingReturn {
209
215
  */
210
216
  progress: RecordingProgressSource;
211
217
  error: Error | null;
218
+ /** `useMicrophoneAccess`'s `stream`: the open microphone, `null` while none
219
+ * is open. A microphone is open when `stream !== null`. */
212
220
  stream: MediaStream | null;
213
221
  devices: MicrophoneDevice[];
214
222
  /** `useMicrophoneAccess`'s `hasLabels`: `devices` names the real
215
223
  * microphones, so a picker can offer them before one is open and open only
216
224
  * the one chosen, with `changeDevice(id)`. */
217
225
  hasLabels: boolean;
218
- hasPermission: boolean;
219
226
  /**
220
227
  * The id of the microphone that is open: the device the stream's track
221
228
  * reports (`getSettings().deviceId`), `null` while no stream is open (also
package/dist/index.js CHANGED
@@ -64,7 +64,7 @@ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
64
64
  const isStoppingRef = (0, import_react.useRef)(false);
65
65
  const stopPromiseRef = (0, import_react.useRef)(null);
66
66
  const finishStopRecordingRef = (0, import_react.useRef)(null);
67
- const isStartingRef = (0, import_react.useRef)(false);
67
+ const startingEpochRef = (0, import_react.useRef)(null);
68
68
  const isUnmountedRef = (0, import_react.useRef)(false);
69
69
  const mountEpochRef = (0, import_react.useRef)(0);
70
70
  const durationRef = (0, import_react.useRef)(0);
@@ -102,21 +102,22 @@ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
102
102
  }
103
103
  }, []);
104
104
  const startRecording = (0, import_react.useCallback)(async () => {
105
- if (isRecordingRef.current || isStartingRef.current) return false;
105
+ const refuseEndedStream = (message) => {
106
+ if (stream?.getAudioTracks()[0]?.readyState !== "ended") return false;
107
+ setError(new Error(message));
108
+ return true;
109
+ };
110
+ if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;
106
111
  if (!stream) {
107
112
  setError(new Error("No microphone stream available"));
108
113
  return false;
109
114
  }
110
- if (stream.getAudioTracks()[0]?.readyState === "ended") {
111
- setError(
112
- new Error(
113
- "The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again."
114
- )
115
- );
115
+ if (refuseEndedStream(
116
+ "The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again."
117
+ ))
116
118
  return false;
117
- }
118
- isStartingRef.current = true;
119
119
  const mountEpoch = mountEpochRef.current;
120
+ startingEpochRef.current = mountEpoch;
120
121
  try {
121
122
  setError(null);
122
123
  const context = (0, import_playout.getGlobalContext)();
@@ -125,6 +126,10 @@ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
125
126
  }
126
127
  await loadWorklet();
127
128
  if (isUnmountedRef.current || mountEpoch !== mountEpochRef.current) return false;
129
+ if (refuseEndedStream(
130
+ "The microphone changed or was disconnected while recording was starting. Start recording again."
131
+ ))
132
+ return false;
128
133
  const source = context.createMediaStreamSource(stream);
129
134
  mediaStreamSourceRef.current = source;
130
135
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;
@@ -208,7 +213,7 @@ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
208
213
  setError(err instanceof Error ? err : new Error("Failed to start recording"));
209
214
  return false;
210
215
  } finally {
211
- isStartingRef.current = false;
216
+ if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;
212
217
  }
213
218
  }, [
214
219
  stream,
@@ -335,9 +340,10 @@ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
335
340
  }, [startDurationLoop]);
336
341
  (0, import_react.useEffect)(() => {
337
342
  isUnmountedRef.current = false;
338
- mountEpochRef.current += 1;
343
+ const epoch = mountEpochRef.current;
339
344
  return () => {
340
345
  isUnmountedRef.current = true;
346
+ mountEpochRef.current = epoch + 1;
341
347
  if (audioTrackRef.current && onTrackEndedRef.current) {
342
348
  audioTrackRef.current.removeEventListener("ended", onTrackEndedRef.current);
343
349
  }
@@ -404,12 +410,12 @@ function useMicrophoneAccess() {
404
410
  const [stream, setStream] = (0, import_react2.useState)(null);
405
411
  const [devices, setDevices] = (0, import_react2.useState)([]);
406
412
  const [hasLabels, setHasLabels] = (0, import_react2.useState)(false);
407
- const [hasPermission, setHasPermission] = (0, import_react2.useState)(false);
408
413
  const [isLoading, setIsLoading] = (0, import_react2.useState)(false);
409
414
  const [error, setError] = (0, import_react2.useState)(null);
410
415
  const streamRef = (0, import_react2.useRef)(null);
411
416
  const requestGenerationRef = (0, import_react2.useRef)(0);
412
417
  const isUnmountedRef = (0, import_react2.useRef)(false);
418
+ const mountEpochRef = (0, import_react2.useRef)(0);
413
419
  const enumerateDevices = (0, import_react2.useCallback)(async () => {
414
420
  try {
415
421
  const { devices: audioInputs, hasLabels: labelled } = await (0, import_core2.enumerateMicrophones)();
@@ -423,6 +429,8 @@ function useMicrophoneAccess() {
423
429
  const requestAccess = (0, import_react2.useCallback)(
424
430
  async (deviceId, audioConstraints) => {
425
431
  const generation = ++requestGenerationRef.current;
432
+ const mountEpoch = mountEpochRef.current;
433
+ const isStale = () => generation !== requestGenerationRef.current || mountEpoch !== mountEpochRef.current || isUnmountedRef.current;
426
434
  setIsLoading(true);
427
435
  setError(null);
428
436
  try {
@@ -454,18 +462,16 @@ function useMicrophoneAccess() {
454
462
  );
455
463
  }
456
464
  const newStream = await mediaDevices.getUserMedia(constraints);
457
- if (generation !== requestGenerationRef.current || isUnmountedRef.current) {
465
+ if (isStale()) {
458
466
  newStream.getTracks().forEach((track) => track.stop());
459
467
  return;
460
468
  }
461
469
  streamRef.current = newStream;
462
470
  setStream(newStream);
463
- setHasPermission(true);
464
471
  const onEnded = () => {
465
472
  if (streamRef.current !== newStream) return;
466
473
  streamRef.current = null;
467
474
  setStream(null);
468
- setHasPermission(false);
469
475
  setError(
470
476
  new Error(
471
477
  "The microphone was disconnected or its permission was revoked. Request microphone access again."
@@ -476,9 +482,8 @@ function useMicrophoneAccess() {
476
482
  await enumerateDevices();
477
483
  } catch (err) {
478
484
  console.warn("[waveform-playlist] Failed to access microphone:", String(err));
479
- if (generation === requestGenerationRef.current) {
485
+ if (!isStale()) {
480
486
  setError(err instanceof Error ? err : new Error("Failed to access microphone"));
481
- setHasPermission(false);
482
487
  }
483
488
  } finally {
484
489
  if (generation === requestGenerationRef.current) {
@@ -490,26 +495,28 @@ function useMicrophoneAccess() {
490
495
  );
491
496
  const stopStream = (0, import_react2.useCallback)(() => {
492
497
  requestGenerationRef.current++;
498
+ setIsLoading(false);
493
499
  if (streamRef.current) {
494
500
  streamRef.current.getTracks().forEach((track) => track.stop());
495
501
  streamRef.current = null;
496
502
  setStream(null);
497
- setHasPermission(false);
498
503
  }
499
504
  }, []);
500
505
  (0, import_react2.useEffect)(() => {
501
506
  isUnmountedRef.current = false;
507
+ const epoch = mountEpochRef.current;
502
508
  enumerateDevices();
503
509
  const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
504
510
  mediaDevices?.addEventListener("devicechange", enumerateDevices);
505
511
  return () => {
506
512
  mediaDevices?.removeEventListener("devicechange", enumerateDevices);
507
513
  isUnmountedRef.current = true;
514
+ mountEpochRef.current = epoch + 1;
515
+ setIsLoading(false);
508
516
  if (streamRef.current) {
509
517
  streamRef.current.getTracks().forEach((track) => track.stop());
510
518
  streamRef.current = null;
511
519
  setStream(null);
512
- setHasPermission(false);
513
520
  }
514
521
  };
515
522
  }, [enumerateDevices]);
@@ -517,7 +524,6 @@ function useMicrophoneAccess() {
517
524
  stream,
518
525
  devices,
519
526
  hasLabels,
520
- hasPermission,
521
527
  isLoading,
522
528
  requestAccess,
523
529
  stopStream,
@@ -704,7 +710,14 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
704
710
  const recordingStartTimeRef = (0, import_react4.useRef)(0);
705
711
  const recordingTrackIdRef = (0, import_react4.useRef)(null);
706
712
  const [recordingTrackId, setRecordingTrackId] = (0, import_react4.useState)(null);
707
- const isStartingRef = (0, import_react4.useRef)(false);
713
+ const startingEpochRef = (0, import_react4.useRef)(null);
714
+ const mountEpochRef = (0, import_react4.useRef)(0);
715
+ (0, import_react4.useEffect)(() => {
716
+ const epoch = mountEpochRef.current;
717
+ return () => {
718
+ mountEpochRef.current = epoch + 1;
719
+ };
720
+ }, []);
708
721
  const selectedTrackIdRef = (0, import_react4.useRef)(selectedTrackId);
709
722
  selectedTrackIdRef.current = selectedTrackId;
710
723
  const currentTimeRef = (0, import_react4.useRef)(currentTime);
@@ -713,14 +726,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
713
726
  audioConstraintsRef.current = audioConstraints;
714
727
  const finishTakeRef = (0, import_react4.useRef)(() => {
715
728
  });
716
- const {
717
- stream,
718
- devices,
719
- hasLabels,
720
- hasPermission,
721
- requestAccess,
722
- error: micError
723
- } = useMicrophoneAccess();
729
+ const { stream, devices, hasLabels, requestAccess, error: micError } = useMicrophoneAccess();
724
730
  const selectedDevice = (0, import_react4.useMemo)(() => openDeviceId(stream), [stream]);
725
731
  const {
726
732
  meter,
@@ -749,7 +755,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
749
755
  const startRecRef = (0, import_react4.useRef)(startRec);
750
756
  startRecRef.current = startRec;
751
757
  const startRecording = (0, import_react4.useCallback)(async () => {
752
- if (isRecordingRef.current || isStartingRef.current) return false;
758
+ if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;
753
759
  if (!selectedTrackIdRef.current) {
754
760
  setHookError(
755
761
  new Error("Cannot start recording: no track selected. Select or create a track first.")
@@ -761,25 +767,30 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
761
767
  setHookError(refusal);
762
768
  return false;
763
769
  }
764
- isStartingRef.current = true;
770
+ const mountEpoch = mountEpochRef.current;
771
+ startingEpochRef.current = mountEpoch;
772
+ const isStale = () => mountEpoch !== mountEpochRef.current;
765
773
  try {
766
774
  setHookError(null);
767
775
  if (!audioResumedRef.current) {
768
776
  await (0, import_playout3.resumeGlobalAudioContext)();
769
777
  audioResumedRef.current = true;
770
778
  }
779
+ if (isStale()) return false;
771
780
  recordingStartTimeRef.current = currentTimeRef.current;
772
781
  recordingTrackIdRef.current = selectedTrackIdRef.current;
773
782
  setRecordingTrackId(selectedTrackIdRef.current);
774
783
  const started = await startRecRef.current();
775
- if (!started) setRecordingTrackId(null);
784
+ if (!started && !isStale()) setRecordingTrackId(null);
776
785
  return started;
777
786
  } catch (err) {
778
- setRecordingTrackId(null);
779
- setHookError(err instanceof Error ? err : new Error(String(err)));
787
+ if (!isStale()) {
788
+ setRecordingTrackId(null);
789
+ setHookError(err instanceof Error ? err : new Error(String(err)));
790
+ }
780
791
  return false;
781
792
  } finally {
782
- isStartingRef.current = false;
793
+ if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;
783
794
  }
784
795
  }, [arrangement]);
785
796
  const finishTake = (0, import_react4.useCallback)(
@@ -895,7 +906,6 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
895
906
  stream,
896
907
  devices,
897
908
  hasLabels,
898
- hasPermission,
899
909
  selectedDevice,
900
910
  // Recording controls
901
911
  startRecording,