@waveform-playlist/recording 14.0.0-next.2 → 14.0.0-next.21

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.mjs CHANGED
@@ -12,6 +12,9 @@ function emptyPeaks(bits) {
12
12
  return bits === 8 ? new Int8Array(0) : new Int16Array(0);
13
13
  }
14
14
  function useRecording(stream, options = {}) {
15
+ return useRecordingWithTakeEnded(stream, options);
16
+ }
17
+ function useRecordingWithTakeEnded(stream, options = {}, onTakeEnded) {
15
18
  const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;
16
19
  const [isRecording, setIsRecording] = useState(false);
17
20
  const [isPaused, setIsPaused] = useState(false);
@@ -36,9 +39,12 @@ function useRecording(stream, options = {}) {
36
39
  const isStoppingRef = useRef(false);
37
40
  const stopPromiseRef = useRef(null);
38
41
  const finishStopRecordingRef = useRef(null);
39
- const isStartingRef = useRef(false);
42
+ const startingEpochRef = useRef(null);
40
43
  const isUnmountedRef = useRef(false);
44
+ const mountEpochRef = useRef(0);
41
45
  const durationRef = useRef(0);
46
+ const onTakeEndedRef = useRef(onTakeEnded);
47
+ onTakeEndedRef.current = onTakeEnded;
42
48
  const peaksRef = useRef(progress.getSnapshot().peaks);
43
49
  const publishProgress = useCallback(() => {
44
50
  const current = progress.getSnapshot();
@@ -71,12 +77,22 @@ function useRecording(stream, options = {}) {
71
77
  }
72
78
  }, []);
73
79
  const startRecording = useCallback(async () => {
74
- if (isRecordingRef.current || isStartingRef.current) return false;
80
+ const refuseEndedStream = (message) => {
81
+ if (stream?.getAudioTracks()[0]?.readyState !== "ended") return false;
82
+ setError(new Error(message));
83
+ return true;
84
+ };
85
+ if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;
75
86
  if (!stream) {
76
87
  setError(new Error("No microphone stream available"));
77
88
  return false;
78
89
  }
79
- isStartingRef.current = true;
90
+ if (refuseEndedStream(
91
+ "The microphone stream has ended (the device was disconnected or its permission revoked). Request microphone access again."
92
+ ))
93
+ return false;
94
+ const mountEpoch = mountEpochRef.current;
95
+ startingEpochRef.current = mountEpoch;
80
96
  try {
81
97
  setError(null);
82
98
  const context = getGlobalContext();
@@ -84,7 +100,11 @@ function useRecording(stream, options = {}) {
84
100
  await context.resume();
85
101
  }
86
102
  await loadWorklet();
87
- if (isUnmountedRef.current) return false;
103
+ if (isUnmountedRef.current || mountEpoch !== mountEpochRef.current) return false;
104
+ if (refuseEndedStream(
105
+ "The microphone changed or was disconnected while recording was starting. Start recording again."
106
+ ))
107
+ return false;
88
108
  const source = context.createMediaStreamSource(stream);
89
109
  mediaStreamSourceRef.current = source;
90
110
  const detectedChannelCount = stream.getAudioTracks()[0]?.getSettings().channelCount;
@@ -149,8 +169,9 @@ function useRecording(stream, options = {}) {
149
169
  if (audioTrack) {
150
170
  const onEnded = () => {
151
171
  console.warn("[waveform-playlist] Audio track ended (mic unplugged or revoked)");
152
- stopRecordingRef.current?.();
172
+ const stopped = stopRecordingRef.current?.();
153
173
  setError(new Error("Microphone disconnected during recording"));
174
+ stopped?.then((buffer) => onTakeEndedRef.current?.(buffer));
154
175
  };
155
176
  onTrackEndedRef.current = onEnded;
156
177
  audioTrack.addEventListener("ended", onEnded);
@@ -167,7 +188,7 @@ function useRecording(stream, options = {}) {
167
188
  setError(err instanceof Error ? err : new Error("Failed to start recording"));
168
189
  return false;
169
190
  } finally {
170
- isStartingRef.current = false;
191
+ if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;
171
192
  }
172
193
  }, [
173
194
  stream,
@@ -190,6 +211,18 @@ function useRecording(stream, options = {}) {
190
211
  stopPromiseRef.current = stopPromise;
191
212
  return stopPromise;
192
213
  }, []);
214
+ const buildTakeBuffer = useCallback(() => {
215
+ const context = getGlobalContext();
216
+ const rawContext = context.rawContext;
217
+ const numChannels = recordedChunksRef.current.length || channelCount;
218
+ const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));
219
+ const totalSamples = channelData[0]?.length ?? 0;
220
+ if (totalSamples === 0) {
221
+ console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
222
+ return null;
223
+ }
224
+ return createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);
225
+ }, [channelCount]);
193
226
  const finishStopRecording = useCallback(async () => {
194
227
  try {
195
228
  if (animationFrameRef.current !== null) {
@@ -237,16 +270,8 @@ function useRecording(stream, options = {}) {
237
270
  workletNodeRef.current = null;
238
271
  mediaStreamSourceRef.current = null;
239
272
  }
240
- const context = getGlobalContext();
241
- const rawContext = context.rawContext;
242
- const numChannels = recordedChunksRef.current.length || channelCount;
243
- const channelData = recordedChunksRef.current.map((chunks) => concatenateAudioData(chunks));
244
- const totalSamples = channelData[0]?.length ?? 0;
245
- if (totalSamples === 0) {
246
- console.warn("[waveform-playlist] Recording stopped with 0 samples captured \u2014 discarding");
247
- return null;
248
- }
249
- const buffer = createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);
273
+ const buffer = buildTakeBuffer();
274
+ if (!buffer) return null;
250
275
  setAudioBuffer(buffer);
251
276
  durationRef.current = buffer.duration;
252
277
  publishProgress();
@@ -262,9 +287,11 @@ function useRecording(stream, options = {}) {
262
287
  setIsRecording(false);
263
288
  setIsPaused(false);
264
289
  }
265
- }, [channelCount, publishProgress]);
290
+ }, [buildTakeBuffer, publishProgress]);
266
291
  stopRecordingRef.current = stopRecording;
267
292
  finishStopRecordingRef.current = finishStopRecording;
293
+ const buildTakeBufferRef = useRef(buildTakeBuffer);
294
+ buildTakeBufferRef.current = buildTakeBuffer;
268
295
  const pauseRecording = useCallback(() => {
269
296
  if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {
270
297
  workletNodeRef.current?.port.postMessage({ command: "pause" });
@@ -288,8 +315,10 @@ function useRecording(stream, options = {}) {
288
315
  }, [startDurationLoop]);
289
316
  useEffect(() => {
290
317
  isUnmountedRef.current = false;
318
+ const epoch = mountEpochRef.current;
291
319
  return () => {
292
320
  isUnmountedRef.current = true;
321
+ mountEpochRef.current = epoch + 1;
293
322
  if (audioTrackRef.current && onTrackEndedRef.current) {
294
323
  audioTrackRef.current.removeEventListener("ended", onTrackEndedRef.current);
295
324
  }
@@ -311,6 +340,28 @@ function useRecording(stream, options = {}) {
311
340
  }
312
341
  if (animationFrameRef.current !== null) {
313
342
  cancelAnimationFrame(animationFrameRef.current);
343
+ animationFrameRef.current = null;
344
+ }
345
+ if (!isRecordingRef.current || isStoppingRef.current) return;
346
+ isRecordingRef.current = false;
347
+ isPausedRef.current = false;
348
+ workletNodeRef.current = null;
349
+ mediaStreamSourceRef.current = null;
350
+ audioTrackRef.current = null;
351
+ onTrackEndedRef.current = null;
352
+ let buffer = null;
353
+ try {
354
+ buffer = buildTakeBufferRef.current();
355
+ } catch (err) {
356
+ console.warn("[waveform-playlist] Failed to keep the interrupted take:", String(err));
357
+ }
358
+ setIsRecording(false);
359
+ setIsPaused(false);
360
+ if (buffer) setAudioBuffer(buffer);
361
+ try {
362
+ onTakeEndedRef.current?.(buffer);
363
+ } catch (err) {
364
+ console.warn("[waveform-playlist] Failed to hand over the interrupted take:", String(err));
314
365
  }
315
366
  };
316
367
  }, []);
@@ -333,24 +384,28 @@ import { enumerateMicrophones } from "@waveform-playlist/core";
333
384
  function useMicrophoneAccess() {
334
385
  const [stream, setStream] = useState2(null);
335
386
  const [devices, setDevices] = useState2([]);
336
- const [hasPermission, setHasPermission] = useState2(false);
387
+ const [hasLabels, setHasLabels] = useState2(false);
337
388
  const [isLoading, setIsLoading] = useState2(false);
338
389
  const [error, setError] = useState2(null);
339
390
  const streamRef = useRef2(null);
340
391
  const requestGenerationRef = useRef2(0);
341
392
  const isUnmountedRef = useRef2(false);
393
+ const mountEpochRef = useRef2(0);
342
394
  const enumerateDevices = useCallback2(async () => {
343
395
  try {
344
- const { devices: audioInputs } = await enumerateMicrophones();
396
+ const { devices: audioInputs, hasLabels: labelled } = await enumerateMicrophones();
345
397
  setDevices(audioInputs);
398
+ setHasLabels(labelled);
346
399
  } catch (err) {
347
- console.error("Failed to enumerate devices:", err);
400
+ console.warn("[waveform-playlist] Failed to enumerate devices:", String(err));
348
401
  setError(err instanceof Error ? err : new Error("Failed to enumerate devices"));
349
402
  }
350
403
  }, []);
351
404
  const requestAccess = useCallback2(
352
405
  async (deviceId, audioConstraints) => {
353
406
  const generation = ++requestGenerationRef.current;
407
+ const mountEpoch = mountEpochRef.current;
408
+ const isStale = () => generation !== requestGenerationRef.current || mountEpoch !== mountEpochRef.current || isUnmountedRef.current;
354
409
  setIsLoading(true);
355
410
  setError(null);
356
411
  try {
@@ -375,20 +430,35 @@ function useMicrophoneAccess() {
375
430
  audio,
376
431
  video: false
377
432
  };
378
- const newStream = await navigator.mediaDevices.getUserMedia(constraints);
379
- if (generation !== requestGenerationRef.current || isUnmountedRef.current) {
433
+ const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
434
+ if (!mediaDevices || typeof mediaDevices.getUserMedia !== "function") {
435
+ throw new Error(
436
+ "Microphone access is not available: navigator.mediaDevices is undefined. It needs a secure context (https or localhost)."
437
+ );
438
+ }
439
+ const newStream = await mediaDevices.getUserMedia(constraints);
440
+ if (isStale()) {
380
441
  newStream.getTracks().forEach((track) => track.stop());
381
442
  return;
382
443
  }
383
444
  streamRef.current = newStream;
384
445
  setStream(newStream);
385
- setHasPermission(true);
446
+ const onEnded = () => {
447
+ if (streamRef.current !== newStream) return;
448
+ streamRef.current = null;
449
+ setStream(null);
450
+ setError(
451
+ new Error(
452
+ "The microphone was disconnected or its permission was revoked. Request microphone access again."
453
+ )
454
+ );
455
+ };
456
+ newStream.getTracks().forEach((track) => track.addEventListener("ended", onEnded, { once: true }));
386
457
  await enumerateDevices();
387
458
  } catch (err) {
388
- console.error("Failed to access microphone:", err);
389
- if (generation === requestGenerationRef.current) {
459
+ console.warn("[waveform-playlist] Failed to access microphone:", String(err));
460
+ if (!isStale()) {
390
461
  setError(err instanceof Error ? err : new Error("Failed to access microphone"));
391
- setHasPermission(false);
392
462
  }
393
463
  } finally {
394
464
  if (generation === requestGenerationRef.current) {
@@ -400,30 +470,35 @@ function useMicrophoneAccess() {
400
470
  );
401
471
  const stopStream = useCallback2(() => {
402
472
  requestGenerationRef.current++;
473
+ setIsLoading(false);
403
474
  if (streamRef.current) {
404
475
  streamRef.current.getTracks().forEach((track) => track.stop());
405
476
  streamRef.current = null;
406
477
  setStream(null);
407
- setHasPermission(false);
408
478
  }
409
479
  }, []);
410
480
  useEffect2(() => {
411
481
  isUnmountedRef.current = false;
482
+ const epoch = mountEpochRef.current;
412
483
  enumerateDevices();
413
- navigator.mediaDevices.addEventListener("devicechange", enumerateDevices);
484
+ const mediaDevices = typeof navigator !== "undefined" ? navigator.mediaDevices : void 0;
485
+ mediaDevices?.addEventListener("devicechange", enumerateDevices);
414
486
  return () => {
415
- navigator.mediaDevices.removeEventListener("devicechange", enumerateDevices);
487
+ mediaDevices?.removeEventListener("devicechange", enumerateDevices);
416
488
  isUnmountedRef.current = true;
489
+ mountEpochRef.current = epoch + 1;
490
+ setIsLoading(false);
417
491
  if (streamRef.current) {
418
492
  streamRef.current.getTracks().forEach((track) => track.stop());
419
493
  streamRef.current = null;
494
+ setStream(null);
420
495
  }
421
496
  };
422
497
  }, [enumerateDevices]);
423
498
  return {
424
499
  stream,
425
500
  devices,
426
- hasPermission,
501
+ hasLabels,
427
502
  isLoading,
428
503
  requestAccess,
429
504
  stopStream,
@@ -537,7 +612,7 @@ function useMicrophoneLevel(stream, options = {}) {
537
612
  }
538
613
 
539
614
  // src/hooks/useIntegratedRecording.ts
540
- import { useState as useState4, useCallback as useCallback4, useEffect as useEffect4, useRef as useRef4 } from "react";
615
+ import { useState as useState4, useCallback as useCallback4, useEffect as useEffect4, useMemo, useRef as useRef4 } from "react";
541
616
 
542
617
  // src/hooks/takeTarget.ts
543
618
  import {
@@ -619,18 +694,29 @@ import {
619
694
  } from "@waveform-playlist/playout";
620
695
  function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
621
696
  const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
622
- const [isMonitoring, setIsMonitoring] = useState4(false);
623
- const [selectedDevice, setSelectedDevice] = useState4(null);
697
+ const audioResumedRef = useRef4(false);
624
698
  const [hookError, setHookError] = useState4(null);
625
699
  const recordingStartTimeRef = useRef4(0);
626
700
  const recordingTrackIdRef = useRef4(null);
627
701
  const [recordingTrackId, setRecordingTrackId] = useState4(null);
628
- const isStartingRef = useRef4(false);
702
+ const startingEpochRef = useRef4(null);
703
+ const mountEpochRef = useRef4(0);
704
+ useEffect4(() => {
705
+ const epoch = mountEpochRef.current;
706
+ return () => {
707
+ mountEpochRef.current = epoch + 1;
708
+ };
709
+ }, []);
629
710
  const selectedTrackIdRef = useRef4(selectedTrackId);
630
711
  selectedTrackIdRef.current = selectedTrackId;
631
712
  const currentTimeRef = useRef4(currentTime);
632
713
  currentTimeRef.current = currentTime;
633
- const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();
714
+ const audioConstraintsRef = useRef4(audioConstraints);
715
+ audioConstraintsRef.current = audioConstraints;
716
+ const finishTakeRef = useRef4(() => {
717
+ });
718
+ const { stream, devices, hasLabels, requestAccess, error: micError } = useMicrophoneAccess();
719
+ const selectedDevice = useMemo(() => openDeviceId(stream), [stream]);
634
720
  const {
635
721
  meter,
636
722
  resetPeak,
@@ -647,9 +733,18 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
647
733
  pauseRecording,
648
734
  resumeRecording,
649
735
  error: recError
650
- } = useRecording(stream, recordingOptions);
736
+ } = useRecordingWithTakeEnded(
737
+ stream,
738
+ recordingOptions,
739
+ (buffer) => (
740
+ // The take ended without our stopRecording(): keep it (#822).
741
+ finishTakeRef.current(buffer)
742
+ )
743
+ );
744
+ const startRecRef = useRef4(startRec);
745
+ startRecRef.current = startRec;
651
746
  const startRecording = useCallback4(async () => {
652
- if (isRecordingRef.current || isStartingRef.current) return false;
747
+ if (isRecordingRef.current || startingEpochRef.current === mountEpochRef.current) return false;
653
748
  if (!selectedTrackIdRef.current) {
654
749
  setHookError(
655
750
  new Error("Cannot start recording: no track selected. Select or create a track first.")
@@ -661,39 +756,39 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
661
756
  setHookError(refusal);
662
757
  return false;
663
758
  }
664
- isStartingRef.current = true;
759
+ const mountEpoch = mountEpochRef.current;
760
+ startingEpochRef.current = mountEpoch;
761
+ const isStale = () => mountEpoch !== mountEpochRef.current;
665
762
  try {
666
763
  setHookError(null);
667
- if (!isMonitoring) {
764
+ if (!audioResumedRef.current) {
668
765
  await resumeGlobalAudioContext();
669
- setIsMonitoring(true);
766
+ audioResumedRef.current = true;
670
767
  }
768
+ if (isStale()) return false;
671
769
  recordingStartTimeRef.current = currentTimeRef.current;
672
770
  recordingTrackIdRef.current = selectedTrackIdRef.current;
673
771
  setRecordingTrackId(selectedTrackIdRef.current);
674
- const started = await startRec();
675
- if (!started) setRecordingTrackId(null);
772
+ const started = await startRecRef.current();
773
+ if (!started && !isStale()) setRecordingTrackId(null);
676
774
  return started;
677
775
  } catch (err) {
678
- setRecordingTrackId(null);
679
- setHookError(err instanceof Error ? err : new Error(String(err)));
776
+ if (!isStale()) {
777
+ setRecordingTrackId(null);
778
+ setHookError(err instanceof Error ? err : new Error(String(err)));
779
+ }
680
780
  return false;
681
781
  } finally {
682
- isStartingRef.current = false;
782
+ if (startingEpochRef.current === mountEpoch) startingEpochRef.current = null;
683
783
  }
684
- }, [arrangement, isMonitoring, startRec]);
685
- const stopRecording = useCallback4(async () => {
686
- let buffer;
687
- try {
688
- buffer = await stopRec();
689
- } catch (err) {
690
- setHookError(err instanceof Error ? err : new Error(String(err)));
691
- return;
692
- } finally {
784
+ }, [arrangement]);
785
+ const finishTake = useCallback4(
786
+ (buffer) => {
787
+ if (!buffer) return;
788
+ const trackId = recordingTrackIdRef.current;
789
+ recordingTrackIdRef.current = null;
693
790
  setRecordingTrackId(null);
694
- }
695
- const trackId = recordingTrackIdRef.current;
696
- if (buffer && trackId) {
791
+ if (!trackId) return;
697
792
  if (!arrangement.getTracks().some((t) => t.id === trackId)) {
698
793
  const err = new Error(
699
794
  `Recording completed but track "${trackId}" no longer exists. The recorded audio could not be saved.`
@@ -739,19 +834,19 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
739
834
  console.warn(`[waveform-playlist] ${notSaved.message}`);
740
835
  setHookError(notSaved);
741
836
  }
837
+ },
838
+ [arrangement, latencyOffset]
839
+ );
840
+ finishTakeRef.current = finishTake;
841
+ const stopRecording = useCallback4(async () => {
842
+ let buffer = null;
843
+ try {
844
+ buffer = await stopRec();
845
+ } catch (err) {
846
+ setHookError(err instanceof Error ? err : new Error(String(err)));
742
847
  }
743
- }, [arrangement, stopRec, latencyOffset]);
744
- useEffect4(() => {
745
- if (!hasPermission || devices.length === 0) return;
746
- if (selectedDevice === null) {
747
- setSelectedDevice(devices[0].deviceId);
748
- } else if (!devices.some((d) => d.deviceId === selectedDevice)) {
749
- const fallbackId = devices[0].deviceId;
750
- setSelectedDevice(fallbackId);
751
- resetPeak();
752
- requestAccess(fallbackId, audioConstraints);
753
- }
754
- }, [hasPermission, devices, selectedDevice, resetPeak, requestAccess, audioConstraints]);
848
+ finishTakeRef.current(buffer);
849
+ }, [stopRec]);
755
850
  const isRecordingRef = useRef4(isRecording);
756
851
  isRecordingRef.current = isRecording;
757
852
  const requestMicAccess = useCallback4(async () => {
@@ -761,13 +856,13 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
761
856
  }
762
857
  try {
763
858
  setHookError(null);
764
- await requestAccess(void 0, audioConstraints);
859
+ await requestAccess(void 0, audioConstraintsRef.current);
765
860
  await resumeGlobalAudioContext();
766
- setIsMonitoring(true);
861
+ audioResumedRef.current = true;
767
862
  } catch (err) {
768
863
  setHookError(err instanceof Error ? err : new Error(String(err)));
769
864
  }
770
- }, [requestAccess, audioConstraints]);
865
+ }, [requestAccess]);
771
866
  const changeDevice = useCallback4(
772
867
  async (deviceId) => {
773
868
  if (isRecordingRef.current) {
@@ -776,16 +871,15 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
776
871
  }
777
872
  try {
778
873
  setHookError(null);
779
- setSelectedDevice(deviceId);
780
874
  resetPeak();
781
- await requestAccess(deviceId, audioConstraints);
875
+ await requestAccess(deviceId, audioConstraintsRef.current);
782
876
  await resumeGlobalAudioContext();
783
- setIsMonitoring(true);
877
+ audioResumedRef.current = true;
784
878
  } catch (err) {
785
879
  setHookError(err instanceof Error ? err : new Error(String(err)));
786
880
  }
787
881
  },
788
- [requestAccess, audioConstraints, resetPeak]
882
+ [requestAccess, resetPeak]
789
883
  );
790
884
  return {
791
885
  // Recording state
@@ -800,7 +894,7 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
800
894
  // Microphone state
801
895
  stream,
802
896
  devices,
803
- hasPermission,
897
+ hasLabels,
804
898
  selectedDevice,
805
899
  // Recording controls
806
900
  startRecording,
@@ -811,6 +905,10 @@ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
811
905
  changeDevice
812
906
  };
813
907
  }
908
+ function openDeviceId(stream) {
909
+ const track = stream?.getAudioTracks()[0];
910
+ return track?.getSettings?.().deviceId || null;
911
+ }
814
912
 
815
913
  // src/hooks/useRecordingProgress.ts
816
914
  import { useThrottledValue } from "@waveform-playlist/ui-components";