@waveform-playlist/recording 13.0.6 → 14.0.0-next.0

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
@@ -1,6 +1,11 @@
1
1
  // src/hooks/useRecording.ts
2
2
  import { useState, useRef, useCallback, useEffect } from "react";
3
- import { concatenateAudioData, createAudioBuffer, appendPeaks } from "@waveform-playlist/core";
3
+ import {
4
+ concatenateAudioData,
5
+ createAudioBuffer,
6
+ appendPeaks,
7
+ createValueSource
8
+ } from "@waveform-playlist/core";
4
9
  import { getGlobalContext } from "@waveform-playlist/playout";
5
10
  import { addRecordingWorkletModule } from "@waveform-playlist/worklets";
6
11
  function emptyPeaks(bits) {
@@ -10,12 +15,11 @@ function useRecording(stream, options = {}) {
10
15
  const { channelCount = 1, samplesPerPixel = 1024, bits = 16 } = options;
11
16
  const [isRecording, setIsRecording] = useState(false);
12
17
  const [isPaused, setIsPaused] = useState(false);
13
- const [duration, setDuration] = useState(0);
14
- const [peaks, setPeaks] = useState([emptyPeaks(bits)]);
15
18
  const [audioBuffer, setAudioBuffer] = useState(null);
16
19
  const [error, setError] = useState(null);
17
- const [level, setLevel] = useState(0);
18
- const [peakLevel, setPeakLevel] = useState(0);
20
+ const [{ source: progress, publish: publishProgressValue }] = useState(
21
+ () => createValueSource({ duration: 0, peaks: [emptyPeaks(bits)] })
22
+ );
19
23
  const workletLoadedRef = useRef(false);
20
24
  const workletNodeRef = useRef(null);
21
25
  const mediaStreamSourceRef = useRef(null);
@@ -35,17 +39,22 @@ function useRecording(stream, options = {}) {
35
39
  const isStartingRef = useRef(false);
36
40
  const isUnmountedRef = useRef(false);
37
41
  const durationRef = useRef(0);
42
+ const peaksRef = useRef(progress.getSnapshot().peaks);
43
+ const publishProgress = useCallback(() => {
44
+ const current = progress.getSnapshot();
45
+ if (current.duration === durationRef.current && current.peaks === peaksRef.current) return;
46
+ publishProgressValue({ duration: durationRef.current, peaks: peaksRef.current });
47
+ }, [progress, publishProgressValue]);
38
48
  const startDurationLoop = useCallback(() => {
39
49
  const tick = () => {
40
50
  if (isRecordingRef.current && !isPausedRef.current && !isStoppingRef.current) {
41
- const elapsed = (performance.now() - startTimeRef.current) / 1e3;
42
- durationRef.current = elapsed;
43
- setDuration(elapsed);
51
+ durationRef.current = (performance.now() - startTimeRef.current) / 1e3;
52
+ publishProgress();
44
53
  animationFrameRef.current = requestAnimationFrame(tick);
45
54
  }
46
55
  };
47
56
  tick();
48
- }, []);
57
+ }, [publishProgress]);
49
58
  const loadWorklet = useCallback(async () => {
50
59
  if (workletLoadedRef.current) {
51
60
  return;
@@ -96,10 +105,10 @@ function useRecording(stream, options = {}) {
96
105
  };
97
106
  recordedChunksRef.current = Array.from({ length: streamChannelCount }, () => []);
98
107
  totalSamplesRef.current = 0;
99
- setPeaks(Array.from({ length: streamChannelCount }, () => emptyPeaks(bits)));
108
+ durationRef.current = 0;
109
+ peaksRef.current = Array.from({ length: streamChannelCount }, () => emptyPeaks(bits));
110
+ publishProgress();
100
111
  setAudioBuffer(null);
101
- setLevel(0);
102
- setPeakLevel(0);
103
112
  workletNode.port.onmessage = (event) => {
104
113
  const { channels, done } = event.data;
105
114
  if (channels && channels.length > 0 && channels[0] && channels[0].length > 0) {
@@ -115,16 +124,17 @@ function useRecording(stream, options = {}) {
115
124
  const samplesProcessedBefore = totalSamplesRef.current;
116
125
  totalSamplesRef.current += channels[0].length;
117
126
  if (stopAckResolveRef.current === null) {
118
- setPeaks((prevPeaks) => {
119
- const updated = [];
120
- for (let ch = 0; ch < channels.length; ch++) {
121
- const prev = prevPeaks[ch] ?? emptyPeaks(bits);
122
- updated.push(
123
- appendPeaks(prev, channels[ch], samplesPerPixel, samplesProcessedBefore, bits)
124
- );
125
- }
126
- return updated;
127
- });
127
+ const previous = peaksRef.current;
128
+ peaksRef.current = channels.map(
129
+ (channel, ch) => appendPeaks(
130
+ previous[ch] ?? emptyPeaks(bits),
131
+ channel,
132
+ samplesPerPixel,
133
+ samplesProcessedBefore,
134
+ bits
135
+ )
136
+ );
137
+ if (isPausedRef.current) publishProgress();
128
138
  }
129
139
  }
130
140
  if (done) {
@@ -159,7 +169,15 @@ function useRecording(stream, options = {}) {
159
169
  } finally {
160
170
  isStartingRef.current = false;
161
171
  }
162
- }, [stream, channelCount, samplesPerPixel, bits, loadWorklet, startDurationLoop]);
172
+ }, [
173
+ stream,
174
+ channelCount,
175
+ samplesPerPixel,
176
+ bits,
177
+ loadWorklet,
178
+ startDurationLoop,
179
+ publishProgress
180
+ ]);
163
181
  const stopRecording = useCallback(async () => {
164
182
  if (!isRecordingRef.current) {
165
183
  return null;
@@ -231,7 +249,7 @@ function useRecording(stream, options = {}) {
231
249
  const buffer = createAudioBuffer(rawContext, channelData, rawContext.sampleRate, numChannels);
232
250
  setAudioBuffer(buffer);
233
251
  durationRef.current = buffer.duration;
234
- setDuration(buffer.duration);
252
+ publishProgress();
235
253
  return buffer;
236
254
  } catch (err) {
237
255
  console.warn("[waveform-playlist] Failed to stop recording:", String(err));
@@ -243,9 +261,8 @@ function useRecording(stream, options = {}) {
243
261
  isStoppingRef.current = false;
244
262
  setIsRecording(false);
245
263
  setIsPaused(false);
246
- setLevel(0);
247
264
  }
248
- }, [channelCount]);
265
+ }, [channelCount, publishProgress]);
249
266
  stopRecordingRef.current = stopRecording;
250
267
  finishStopRecordingRef.current = finishStopRecording;
251
268
  const pauseRecording = useCallback(() => {
@@ -256,9 +273,10 @@ function useRecording(stream, options = {}) {
256
273
  animationFrameRef.current = null;
257
274
  }
258
275
  isPausedRef.current = true;
276
+ publishProgress();
259
277
  setIsPaused(true);
260
278
  }
261
- }, []);
279
+ }, [publishProgress]);
262
280
  const resumeRecording = useCallback(() => {
263
281
  if (isRecordingRef.current && isPausedRef.current && !isStoppingRef.current) {
264
282
  workletNodeRef.current?.port.postMessage({ command: "resume" });
@@ -277,6 +295,7 @@ function useRecording(stream, options = {}) {
277
295
  }
278
296
  if (workletNodeRef.current) {
279
297
  workletNodeRef.current.port.postMessage({ command: "stop" });
298
+ workletNodeRef.current.port.onmessage = null;
280
299
  if (mediaStreamSourceRef.current) {
281
300
  try {
282
301
  mediaStreamSourceRef.current.disconnect(workletNodeRef.current);
@@ -298,11 +317,8 @@ function useRecording(stream, options = {}) {
298
317
  return {
299
318
  isRecording,
300
319
  isPaused,
301
- duration,
302
- peaks,
320
+ progress,
303
321
  audioBuffer,
304
- level,
305
- peakLevel,
306
322
  startRecording,
307
323
  stopRecording,
308
324
  pauseRecording,
@@ -418,28 +434,29 @@ function useMicrophoneAccess() {
418
434
  // src/hooks/useMicrophoneLevel.ts
419
435
  import { useEffect as useEffect3, useState as useState3, useRef as useRef3, useCallback as useCallback3 } from "react";
420
436
  import { getGlobalContext as getGlobalContext2 } from "@waveform-playlist/playout";
421
- import { gainToNormalized } from "@waveform-playlist/core";
437
+ import {
438
+ createValueSource as createValueSource2,
439
+ readMeterMessage,
440
+ silentMeterLevels
441
+ } from "@waveform-playlist/core";
422
442
  import { addMeterWorkletModule } from "@waveform-playlist/worklets";
423
- var PEAK_DECAY = 0.98;
424
443
  function useMicrophoneLevel(stream, options = {}) {
425
444
  const { updateRate = 60, channelCount = 1 } = options;
426
- const [levels, setLevels] = useState3(() => new Array(channelCount).fill(0));
427
- const [peakLevels, setPeakLevels] = useState3(() => new Array(channelCount).fill(0));
428
- const [rmsLevels, setRmsLevels] = useState3(() => new Array(channelCount).fill(0));
445
+ const [{ source: meter, publish }] = useState3(
446
+ () => createValueSource2(silentMeterLevels(channelCount))
447
+ );
429
448
  const [meterError, setMeterError] = useState3(null);
430
449
  const workletNodeRef = useRef3(null);
431
450
  const sourceRef = useRef3(null);
432
- const smoothedPeakRef = useRef3(new Array(channelCount).fill(0));
433
- const resetPeak = useCallback3(
434
- () => setPeakLevels(new Array(channelCount).fill(0)),
435
- [channelCount]
436
- );
451
+ const smoothedPeakRef = useRef3([]);
452
+ const resetPeak = useCallback3(() => {
453
+ const current = meter.getSnapshot();
454
+ publish({ ...current, peakLevels: current.peakLevels.map(() => 0) });
455
+ }, [meter, publish]);
437
456
  useEffect3(() => {
438
457
  if (!stream) {
439
- setLevels(new Array(channelCount).fill(0));
440
- setPeakLevels(new Array(channelCount).fill(0));
441
- setRmsLevels(new Array(channelCount).fill(0));
442
- smoothedPeakRef.current = new Array(channelCount).fill(0);
458
+ smoothedPeakRef.current = [];
459
+ publish(silentMeterLevels(channelCount));
443
460
  return;
444
461
  }
445
462
  let isMounted = true;
@@ -470,24 +487,18 @@ function useMicrophoneLevel(stream, options = {}) {
470
487
  const source = context.createMediaStreamSource(stream);
471
488
  sourceRef.current = source;
472
489
  source.connect(workletNode);
473
- smoothedPeakRef.current = new Array(actualChannels).fill(0);
490
+ smoothedPeakRef.current = [];
474
491
  workletNode.port.onmessage = (event) => {
475
492
  if (!isMounted) return;
476
- const data = event.data;
477
- const workletChannels = data.length / 2;
478
- const smoothed = smoothedPeakRef.current;
479
- const peakValues = [];
480
- const rmsValues = [];
481
- for (let ch = 0; ch < workletChannels; ch++) {
482
- smoothed[ch] = Math.max(data[ch], (smoothed[ch] ?? 0) * PEAK_DECAY);
483
- peakValues.push(gainToNormalized(smoothed[ch]));
484
- rmsValues.push(gainToNormalized(data[workletChannels + ch]));
485
- }
486
- const mirroredPeaks = workletChannels < channelCount ? new Array(channelCount).fill(peakValues[0]) : peakValues;
487
- const mirroredRms = workletChannels < channelCount ? new Array(channelCount).fill(rmsValues[0]) : rmsValues;
488
- setLevels(mirroredPeaks);
489
- setRmsLevels(mirroredRms);
490
- setPeakLevels((prev) => mirroredPeaks.map((val, i) => Math.max(prev[i] ?? 0, val)));
493
+ const reading = readMeterMessage({
494
+ data: event.data,
495
+ previousSmoothedPeaks: smoothedPeakRef.current,
496
+ heldPeakLevels: meter.getSnapshot().peakLevels,
497
+ // Mirror mono to fill the requested channelCount
498
+ minChannels: channelCount
499
+ });
500
+ smoothedPeakRef.current = reading.smoothedPeaks;
501
+ publish(reading.levels);
491
502
  };
492
503
  setMeterError(null);
493
504
  };
@@ -517,24 +528,88 @@ function useMicrophoneLevel(stream, options = {}) {
517
528
  workletNodeRef.current = null;
518
529
  }
519
530
  };
520
- }, [stream, updateRate, channelCount]);
521
- const level = channelCount === 1 ? levels[0] ?? 0 : Math.max(...levels);
522
- const peakLevel = channelCount === 1 ? peakLevels[0] ?? 0 : Math.max(...peakLevels);
531
+ }, [stream, updateRate, channelCount, meter, publish]);
523
532
  return {
524
- level,
525
- peakLevel,
533
+ meter,
526
534
  resetPeak,
527
- levels,
528
- peakLevels,
529
- rmsLevels,
530
535
  error: meterError
531
536
  };
532
537
  }
533
538
 
534
539
  // src/hooks/useIntegratedRecording.ts
535
540
  import { useState as useState4, useCallback as useCallback4, useEffect as useEffect4, useRef as useRef4 } from "react";
541
+
542
+ // src/hooks/takeTarget.ts
536
543
  import {
537
544
  carveClipRange,
545
+ isLoadingClip,
546
+ trackKind
547
+ } from "@waveform-playlist/core";
548
+ var PREFIX = "Cannot start recording: ";
549
+ function label(track) {
550
+ return '"' + (track.name || track.id) + '"';
551
+ }
552
+ function isUnusableClipFailure(arrangement, clip, state) {
553
+ const message = state.error?.message ?? "";
554
+ return arrangement.getTracks().some(
555
+ (t) => t.clips.some(
556
+ (c) => isLoadingClip(c) && c.src === clip.src && message.startsWith(`clip "${c.id}": `)
557
+ )
558
+ );
559
+ }
560
+ function loadingClipRefusal(arrangement, track, clip) {
561
+ const state = arrangement.sources.getSnapshot().sources.get(clip.src);
562
+ if (state?.status !== "failed") {
563
+ return new Error(
564
+ `${PREFIX}${label(track)} holds a clip whose audio is still loading ("${clip.id}"). Start the take once it has loaded.`
565
+ );
566
+ }
567
+ const reason = state.error?.message ?? "unknown error";
568
+ if (isUnusableClipFailure(arrangement, clip, state)) {
569
+ return new Error(
570
+ `${PREFIX}a clip on ${label(track)} cannot be made from its audio (${reason}). Correct or remove the clip.`
571
+ );
572
+ }
573
+ return new Error(
574
+ `${PREFIX}the audio of clip "${clip.id}" on ${label(track)} could not be loaded (${reason}). Retry it with arrangement.retry(), or remove the clip.`
575
+ );
576
+ }
577
+ function takeRefusal(arrangement, trackId) {
578
+ const target = arrangement.getTracks().find((t) => t.id === trackId);
579
+ if (!target) {
580
+ return new Error(
581
+ `${PREFIX}the selected track "${trackId}" is not in the arrangement. Add it with arrangement.addTrack() first.`
582
+ );
583
+ }
584
+ if (trackKind(target) === "midi") {
585
+ return new Error(
586
+ `${PREFIX}${label(target)} is a MIDI track. Select or create an audio track first.`
587
+ );
588
+ }
589
+ const loading = target.clips.find(isLoadingClip);
590
+ return loading ? loadingClipRefusal(arrangement, target, loading) : null;
591
+ }
592
+ function takeNotSaved(trackId, refusal) {
593
+ const cause = refusal instanceof Error ? refusal : new Error(String(refusal));
594
+ return Object.assign(
595
+ new Error(
596
+ `Recording completed but the take could not be saved on track "${trackId}": ` + cause.message
597
+ ),
598
+ { cause }
599
+ );
600
+ }
601
+ function withTake(track, take) {
602
+ const loaded = track.clips.filter((c) => !isLoadingClip(c));
603
+ const loading = track.clips.filter(isLoadingClip);
604
+ const end = take.startSample + take.durationSamples;
605
+ return {
606
+ ...track,
607
+ clips: [...carveClipRange(loaded, take.startSample, end), ...loading, take]
608
+ };
609
+ }
610
+
611
+ // src/hooks/useIntegratedRecording.ts
612
+ import {
538
613
  resolveRecordingOffsetSamples
539
614
  } from "@waveform-playlist/core";
540
615
  import {
@@ -542,25 +617,22 @@ import {
542
617
  getGlobalAudioContext,
543
618
  getGlobalContext as getGlobalContext3
544
619
  } from "@waveform-playlist/playout";
545
- function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}) {
620
+ function useIntegratedRecording(arrangement, selectedTrackId, options = {}) {
546
621
  const { currentTime = 0, audioConstraints, latencyOffset, ...recordingOptions } = options;
547
622
  const [isMonitoring, setIsMonitoring] = useState4(false);
548
623
  const [selectedDevice, setSelectedDevice] = useState4(null);
549
624
  const [hookError, setHookError] = useState4(null);
550
625
  const recordingStartTimeRef = useRef4(0);
626
+ const recordingTrackIdRef = useRef4(null);
627
+ const [recordingTrackId, setRecordingTrackId] = useState4(null);
628
+ const isStartingRef = useRef4(false);
551
629
  const selectedTrackIdRef = useRef4(selectedTrackId);
552
630
  selectedTrackIdRef.current = selectedTrackId;
553
631
  const currentTimeRef = useRef4(currentTime);
554
632
  currentTimeRef.current = currentTime;
555
- const tracksRef = useRef4(tracks);
556
- tracksRef.current = tracks;
557
633
  const { stream, devices, hasPermission, requestAccess, error: micError } = useMicrophoneAccess();
558
634
  const {
559
- level,
560
- peakLevel,
561
- levels,
562
- peakLevels,
563
- rmsLevels,
635
+ meter,
564
636
  resetPeak,
565
637
  error: meterError
566
638
  } = useMicrophoneLevel(stream, {
@@ -569,9 +641,7 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
569
641
  const {
570
642
  isRecording,
571
643
  isPaused,
572
- duration,
573
- peaks,
574
- audioBuffer: _recordedAudioBuffer,
644
+ progress,
575
645
  startRecording: startRec,
576
646
  stopRecording: stopRec,
577
647
  pauseRecording,
@@ -579,12 +649,19 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
579
649
  error: recError
580
650
  } = useRecording(stream, recordingOptions);
581
651
  const startRecording = useCallback4(async () => {
652
+ if (isRecordingRef.current || isStartingRef.current) return false;
582
653
  if (!selectedTrackIdRef.current) {
583
654
  setHookError(
584
655
  new Error("Cannot start recording: no track selected. Select or create a track first.")
585
656
  );
586
657
  return false;
587
658
  }
659
+ const refusal = takeRefusal(arrangement, selectedTrackIdRef.current);
660
+ if (refusal) {
661
+ setHookError(refusal);
662
+ return false;
663
+ }
664
+ isStartingRef.current = true;
588
665
  try {
589
666
  setHookError(null);
590
667
  if (!isMonitoring) {
@@ -592,12 +669,19 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
592
669
  setIsMonitoring(true);
593
670
  }
594
671
  recordingStartTimeRef.current = currentTimeRef.current;
595
- return await startRec();
672
+ recordingTrackIdRef.current = selectedTrackIdRef.current;
673
+ setRecordingTrackId(selectedTrackIdRef.current);
674
+ const started = await startRec();
675
+ if (!started) setRecordingTrackId(null);
676
+ return started;
596
677
  } catch (err) {
678
+ setRecordingTrackId(null);
597
679
  setHookError(err instanceof Error ? err : new Error(String(err)));
598
680
  return false;
681
+ } finally {
682
+ isStartingRef.current = false;
599
683
  }
600
- }, [isMonitoring, startRec]);
684
+ }, [arrangement, isMonitoring, startRec]);
601
685
  const stopRecording = useCallback4(async () => {
602
686
  let buffer;
603
687
  try {
@@ -605,12 +689,12 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
605
689
  } catch (err) {
606
690
  setHookError(err instanceof Error ? err : new Error(String(err)));
607
691
  return;
692
+ } finally {
693
+ setRecordingTrackId(null);
608
694
  }
609
- const trackId = selectedTrackIdRef.current;
610
- const currentTracks = tracksRef.current;
695
+ const trackId = recordingTrackIdRef.current;
611
696
  if (buffer && trackId) {
612
- const selectedTrackIndex = currentTracks.findIndex((t) => t.id === trackId);
613
- if (selectedTrackIndex === -1) {
697
+ if (!arrangement.getTracks().some((t) => t.id === trackId)) {
614
698
  const err = new Error(
615
699
  `Recording completed but track "${trackId}" no longer exists. The recorded audio could not be saved.`
616
700
  );
@@ -648,21 +732,15 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
648
732
  gain: 1,
649
733
  name: `Recording ${(/* @__PURE__ */ new Date()).toLocaleTimeString()}`
650
734
  };
651
- const newTracks = currentTracks.map((track, index) => {
652
- if (index === selectedTrackIndex) {
653
- return {
654
- ...track,
655
- clips: [
656
- ...carveClipRange(track.clips, startSample, startSample + effectiveDuration),
657
- newClip
658
- ]
659
- };
660
- }
661
- return track;
662
- });
663
- setTracks(newTracks);
735
+ try {
736
+ arrangement.updateTrack(trackId, (track) => withTake(track, newClip));
737
+ } catch (err) {
738
+ const notSaved = takeNotSaved(trackId, err);
739
+ console.warn(`[waveform-playlist] ${notSaved.message}`);
740
+ setHookError(notSaved);
741
+ }
664
742
  }
665
- }, [setTracks, stopRec, latencyOffset]);
743
+ }, [arrangement, stopRec, latencyOffset]);
666
744
  useEffect4(() => {
667
745
  if (!hasPermission || devices.length === 0) return;
668
746
  if (selectedDevice === null) {
@@ -713,12 +791,11 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
713
791
  // Recording state
714
792
  isRecording,
715
793
  isPaused,
716
- duration,
717
- level,
718
- peakLevel,
719
- levels,
720
- peakLevels,
721
- rmsLevels,
794
+ // Only while a take is running: a take can also end without our
795
+ // stopRecording (the microphone is unplugged and useRecording stops itself).
796
+ recordingTrackId: isRecording ? recordingTrackId : null,
797
+ meter,
798
+ progress,
722
799
  error: hookError || micError || meterError || recError,
723
800
  // Microphone state
724
801
  stream,
@@ -731,15 +808,20 @@ function useIntegratedRecording(tracks, setTracks, selectedTrackId, options = {}
731
808
  pauseRecording,
732
809
  resumeRecording,
733
810
  requestMicAccess,
734
- changeDevice,
735
- // Track state
736
- recordingPeaks: peaks
811
+ changeDevice
737
812
  };
738
813
  }
814
+
815
+ // src/hooks/useRecordingProgress.ts
816
+ import { useThrottledValue } from "@waveform-playlist/ui-components";
817
+ function useRecordingProgress(progress, options = {}) {
818
+ return useThrottledValue(progress, options);
819
+ }
739
820
  export {
740
821
  useIntegratedRecording,
741
822
  useMicrophoneAccess,
742
823
  useMicrophoneLevel,
743
- useRecording
824
+ useRecording,
825
+ useRecordingProgress
744
826
  };
745
827
  //# sourceMappingURL=index.mjs.map