canvas-recorder-lib 0.6.0 → 0.7.1

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.
Files changed (62) hide show
  1. package/BREAKING-CHANGES.md +6 -0
  2. package/README.md +37 -23
  3. package/dev/audio-builder.ts +69 -163
  4. package/dev/canvas-recorder.ts +350 -169
  5. package/dev/player-body.ts +8 -0
  6. package/dev/sound-clips.ts +3 -2
  7. package/dev/soundtrack.ts +442 -0
  8. package/dev/transcripts.ts +55 -4
  9. package/dev/video-clip-panel.ts +1 -1
  10. package/dev/voice/chirp.ts +129 -0
  11. package/dev/voice/folder.ts +84 -0
  12. package/dev/voice/voice-panel.ts +523 -0
  13. package/dev/voice/voice-recorder.ts +603 -0
  14. package/dist/dev/audio-builder.d.ts +14 -31
  15. package/dist/dev/audio-builder.d.ts.map +1 -1
  16. package/dist/dev/audio-builder.js +62 -135
  17. package/dist/dev/audio-builder.js.map +1 -1
  18. package/dist/dev/canvas-recorder.js +336 -156
  19. package/dist/dev/canvas-recorder.js.map +1 -1
  20. package/dist/dev/player-body.d.ts +1 -1
  21. package/dist/dev/player-body.d.ts.map +1 -1
  22. package/dist/dev/player-body.js +8 -0
  23. package/dist/dev/player-body.js.map +1 -1
  24. package/dist/dev/sound-clips.d.ts +3 -2
  25. package/dist/dev/sound-clips.d.ts.map +1 -1
  26. package/dist/dev/sound-clips.js +3 -2
  27. package/dist/dev/sound-clips.js.map +1 -1
  28. package/dist/dev/soundtrack.d.ts +115 -0
  29. package/dist/dev/soundtrack.d.ts.map +1 -0
  30. package/dist/dev/soundtrack.js +376 -0
  31. package/dist/dev/soundtrack.js.map +1 -0
  32. package/dist/dev/transcripts.d.ts +5 -0
  33. package/dist/dev/transcripts.d.ts.map +1 -1
  34. package/dist/dev/transcripts.js +50 -4
  35. package/dist/dev/transcripts.js.map +1 -1
  36. package/dist/dev/video-clip-panel.js +1 -1
  37. package/dist/dev/video-clip-panel.js.map +1 -1
  38. package/dist/dev/voice/chirp.d.ts +27 -0
  39. package/dist/dev/voice/chirp.d.ts.map +1 -0
  40. package/dist/dev/voice/chirp.js +107 -0
  41. package/dist/dev/voice/chirp.js.map +1 -0
  42. package/dist/dev/voice/folder.d.ts +18 -0
  43. package/dist/dev/voice/folder.d.ts.map +1 -0
  44. package/dist/dev/voice/folder.js +68 -0
  45. package/dist/dev/voice/folder.js.map +1 -0
  46. package/dist/dev/voice/voice-panel.d.ts +44 -0
  47. package/dist/dev/voice/voice-panel.d.ts.map +1 -0
  48. package/dist/dev/voice/voice-panel.js +428 -0
  49. package/dist/dev/voice/voice-panel.js.map +1 -0
  50. package/dist/dev/voice/voice-recorder.d.ts +141 -0
  51. package/dist/dev/voice/voice-recorder.d.ts.map +1 -0
  52. package/dist/dev/voice/voice-recorder.js +506 -0
  53. package/dist/dev/voice/voice-recorder.js.map +1 -0
  54. package/dist/src/showable.d.ts +9 -0
  55. package/dist/src/showable.d.ts.map +1 -1
  56. package/dist/src/showable.js.map +1 -1
  57. package/dist/src/snapshot.d.ts.map +1 -1
  58. package/dist/src/snapshot.js +27 -11
  59. package/dist/src/snapshot.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/showable.ts +9 -0
  62. package/src/snapshot.ts +30 -15
@@ -62,7 +62,9 @@ import {
62
62
  } from "../src/snapshot.ts";
63
63
  import { downloadBlob, philDebug } from "../src/utility.ts";
64
64
  import { debugLog, getNewDebugLogEntries } from "../src/debug-log.ts";
65
- import { AudioBuilder } from "./audio-builder.ts";
65
+ import { SAMPLE_RATE, Soundtrack } from "./soundtrack.ts";
66
+ import { openVoicePanel, type VoicePanel } from "./voice/voice-panel.ts";
67
+ import type { RecordedClip, VoiceRecorder } from "./voice/voice-recorder.ts";
66
68
  import { openColorPickerDialog } from "./color-picker.ts";
67
69
  import { setSwatchColor } from "./color-utils.ts";
68
70
  import {
@@ -97,6 +99,7 @@ import {
97
99
  type TimelineWord,
98
100
  } from "./timeline-display.ts";
99
101
  import {
102
+ forgetTranscriptFailures,
100
103
  forgetTranscripts,
101
104
  makeTranscript,
102
105
  onTranscriptsChange,
@@ -472,8 +475,9 @@ onLocalFilesChange(updateLocalFilesButton);
472
475
  /** Ask about every file that needs it. Then the sounds can load. */
473
476
  async function allowLocalFiles() {
474
477
  await requestLocalFileAccess();
475
- // The images and video clips try again by themselves. The sounds are loaded all at once.
476
- void initAudio();
478
+ // The images and video clips try again by themselves.
479
+ soundtrack.forgetFailures();
480
+ forgetTranscriptFailures();
477
481
  }
478
482
  localFilesBtn.addEventListener("click", () => void allowLocalFiles());
479
483
 
@@ -652,17 +656,48 @@ function loadPlayPositionRange() {
652
656
  playPositionRange.valueAsNumber = playPositionSeconds.valueAsNumber * 1000;
653
657
  }
654
658
 
655
- const audioContext = new AudioContext();
659
+ // The same rate as the decoded files and the voice recorder, whatever the hardware uses.
660
+ const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
656
661
  console.log(audioContext);
657
662
  const gainNode = audioContext.createGain();
658
663
  gainNode.connect(audioContext.destination);
659
664
 
660
- /** Set to true once the AudioBuffer has been fully built and is safe to play. */
661
- let audioReady = false;
662
- let audioSourceNode: AudioBufferSourceNode | null = null;
663
- /** audioContext.currentTime at the moment startAudio() last started a source node. */
665
+ /**
666
+ * Every sound clip in the video, playing live. Ask it for a new soundtrack with
667
+ * `soundtrack.request()`, as often as you like: it does the rate limiting.
668
+ */
669
+ const soundtrack = new Soundtrack({
670
+ context: audioContext,
671
+ destination: gainNode,
672
+ root: () => toShow,
673
+ // Sound clips on the timeline can now show their waveforms, and the ones
674
+ // that play to the end of their file now know how long that is.
675
+ onDecoded: () => timelineDisplay.redraw(),
676
+ // The new file may be a local one that needs 🔓.
677
+ onNewSource: () => checkVideosLocalFiles(),
678
+ });
679
+ soundtrack.request();
680
+ // The images and videos may be local files too, even with no sound.
681
+ checkVideosLocalFiles();
682
+
683
+ /** True between startAudio() and stopAudio(), unless {@link rafFallbackMode}. */
684
+ let audioPlaying = false;
685
+ /**
686
+ * True from ● Record until the voice recording stops. The soundtrack is muted,
687
+ * and the controls that would spoil the recording are disabled.
688
+ * See {@link startVoiceRecording}.
689
+ */
690
+ let voiceRecording = false;
691
+ /**
692
+ * True while ● Record's chirp plays, before the video starts. Being paused
693
+ * then doesn't stop the recording.
694
+ */
695
+ let voiceChirping = false;
696
+ /** The voice recorder's controls, while 🎙 Record mode is showing them. */
697
+ let voicePanel: VoicePanel | undefined;
698
+ /** audioContext.currentTime at the moment startAudio() last anchored the clock. */
664
699
  let audioContextStartTime = 0;
665
- /** Media position (ms) at the moment startAudio() last started a source node. */
700
+ /** Media position (ms) at the moment startAudio() last anchored the clock. */
666
701
  let audioMediaStartMs = 0;
667
702
  let audioPlaybackRate = 1;
668
703
 
@@ -675,7 +710,7 @@ let audioPlaybackRate = 1;
675
710
  * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
676
711
  */
677
712
  let rafFallbackMode = false;
678
- /** True when fallback-mode "playback" is running (mirrors audioSourceNode !== null). */
713
+ /** True when fallback-mode "playback" is running (mirrors {@link audioPlaying}). */
679
714
  let rafFallbackPlaying = false;
680
715
  /** performance.now() at the moment fallback playback last started. */
681
716
  let rafFallbackStartPerf = 0;
@@ -719,7 +754,6 @@ function startAudio(fromMs: number): void {
719
754
  rafFallbackPlaying = true;
720
755
  return;
721
756
  }
722
- if (!audioReady) return;
723
757
  if (audioContext.state !== "running") {
724
758
  if (!navigator.userActivation.isActive) {
725
759
  // No user gesture available (e.g. restoring play state on page load).
@@ -727,30 +761,35 @@ function startAudio(fromMs: number): void {
727
761
  enterRafFallback(fromMs, false);
728
762
  return;
729
763
  }
730
- // Has a user gesture. resume() is async — the source node below plays
764
+ // Has a user gesture. resume() is async — the source nodes below play
731
765
  // once the context transitions to running. Do NOT check state synchronously
732
766
  // after this call; it will still read "suspended" before the promise resolves.
733
767
  audioContext.resume().catch(() => {});
734
768
  }
735
- const source = audioContext.createBufferSource();
736
- source.buffer = audioBuilder.getAudioBuffer();
737
- source.playbackRate.value = audioPlaybackRate;
738
- source.connect(gainNode);
739
769
  const contextNow = audioContext.currentTime;
740
- source.start(contextNow, fromMs / 1000);
741
- audioSourceNode = source;
742
770
  audioContextStartTime = contextNow;
743
771
  audioMediaStartMs = fromMs;
772
+ soundtrack.play({
773
+ contextTime: contextNow,
774
+ mediaMs: fromMs,
775
+ rate: audioPlaybackRate,
776
+ });
777
+ audioPlaying = true;
778
+ if (voiceRecording) beginVoiceClip(contextNow, fromMs);
744
779
  }
745
780
 
781
+ /**
782
+ * Stop the sound and the clock. Called for every seek too: the animation loop
783
+ * starts again from the play position on its next frame.
784
+ *
785
+ * While recording a voice, this ends the clip, and the next start begins a new one.
786
+ */
746
787
  function stopAudio(): void {
747
788
  rafFallbackPlaying = false;
748
- if (audioSourceNode) {
749
- try {
750
- audioSourceNode.stop();
751
- } catch (_) {}
752
- audioSourceNode.disconnect();
753
- audioSourceNode = null;
789
+ if (audioPlaying) {
790
+ soundtrack.stop();
791
+ audioPlaying = false;
792
+ if (voiceRecording) endVoiceClip();
754
793
  }
755
794
  }
756
795
 
@@ -763,17 +802,29 @@ function setPlaybackRate(rate: number): void {
763
802
  const currentMs = currentAudioTimeMs();
764
803
  rafFallbackStartMs = currentMs;
765
804
  rafFallbackStartPerf = performance.now();
766
- } else if (audioSourceNode) {
805
+ } else if (audioPlaying) {
767
806
  const currentMs = currentAudioTimeMs();
768
807
  audioContextStartTime = audioContext.currentTime;
769
808
  audioMediaStartMs = currentMs;
770
- audioSourceNode.playbackRate.value = rate;
809
+ soundtrack.changeRate({
810
+ contextTime: audioContextStartTime,
811
+ mediaMs: audioMediaStartMs,
812
+ rate,
813
+ });
771
814
  }
772
815
  audioPlaybackRate = rate;
773
816
  }
774
817
 
818
+ const volumeSlider = getById("volumeAudio", HTMLInputElement);
819
+ const speedSelect = getById("speedAudio", HTMLSelectElement);
820
+
821
+ /** The soundtrack's volume: the slider, unless it's muted, or a voice is being recorded. */
822
+ function updateGain(): void {
823
+ gainNode.gain.value =
824
+ muteCheckbox.checked || voiceRecording ? 0 : volumeSlider.valueAsNumber;
825
+ }
826
+
775
827
  {
776
- const volumeSlider = getById("volumeAudio", HTMLInputElement);
777
828
  muteCheckbox.addEventListener("input", () => {
778
829
  if (!muteCheckbox.checked && rafFallbackMode) {
779
830
  // Un-muting is a user gesture — try to exit fallback and resume real audio.
@@ -786,77 +837,14 @@ function setPlaybackRate(rate: number): void {
786
837
  startAudio(currentMs);
787
838
  }
788
839
  }
789
- gainNode.gain.value = muteCheckbox.checked ? 0 : volumeSlider.valueAsNumber;
790
- });
791
- volumeSlider.addEventListener("input", () => {
792
- if (!muteCheckbox.checked) {
793
- gainNode.gain.value = volumeSlider.valueAsNumber;
794
- }
840
+ updateGain();
795
841
  });
796
- getById("speedAudio", HTMLSelectElement).addEventListener("change", (e) => {
797
- setPlaybackRate(parseFloat((e.target as HTMLSelectElement).value));
842
+ volumeSlider.addEventListener("input", updateGain);
843
+ speedSelect.addEventListener("change", () => {
844
+ setPlaybackRate(parseFloat(speedSelect.value));
798
845
  });
799
846
  }
800
847
 
801
- let audioBuilder = new AudioBuilder(toShow.duration);
802
-
803
- let reloadGeneration = 0;
804
-
805
- async function initAudio(): Promise<void> {
806
- // The sound clips are being re-read, so this is a good time to look for files needing 🔓.
807
- checkVideosLocalFiles();
808
- const myGen = ++reloadGeneration;
809
- audioReady = false;
810
- stopAudio();
811
- const newBuilder = new AudioBuilder(toShow.duration);
812
-
813
- async function doIt(item: Showable, offset: number): Promise<boolean> {
814
- if (myGen !== reloadGeneration) return false;
815
- if (item.soundClips) {
816
- for (const clip of item.soundClips) {
817
- // A brand new clip has no source yet, and a URL being typed is wrong
818
- // until it's finished. Either way, skip that one clip, not all audio.
819
- if (clip.source === "") continue;
820
- try {
821
- await newBuilder.add(
822
- clip.source,
823
- offset + clip.startMsIntoScene,
824
- clip.startMsIntoClip,
825
- clip.lengthMs,
826
- );
827
- } catch (reason) {
828
- debugLog("audio", `Skipped "${clip.source}": ${reason}`);
829
- }
830
- if (myGen !== reloadGeneration) return false;
831
- }
832
- }
833
- if (item.children) {
834
- for (const { child, start } of item.children) {
835
- if (!(await doIt(child, offset + start))) return false;
836
- }
837
- }
838
- return true;
839
- }
840
-
841
- const time1 = performance.now();
842
- const completed = await doIt(toShow, 0);
843
- const time2 = performance.now();
844
- if (!completed) {
845
- console.log(
846
- `Audio init superseded after ${(time2 - time1).toFixed(0)} ms.`,
847
- );
848
- return;
849
- }
850
- audioBuilder = newBuilder;
851
- audioReady = true;
852
- console.log(`Audio ready in ${(time2 - time1).toFixed(0)} ms.`);
853
- // Sound clips on the timeline can now show their waveforms, and the ones
854
- // that play to the end of their file now know how long that is.
855
- timelineDisplay.redraw();
856
- }
857
-
858
- initAudio();
859
-
860
848
  /**
861
849
  * We disable {@link animationLoop} while rendering to a file.
862
850
  * We can reenable it when we are done rendering.
@@ -875,6 +863,8 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
875
863
  if (!playCheckBox.checked) {
876
864
  // Paused.
877
865
  stopAudio();
866
+ // Pausing is how a voice recording stops, once the video has started.
867
+ if (voiceRecording && !voiceChirping) stopVoiceRecording();
878
868
  playPositionSeconds.disabled = false;
879
869
  showFrame(playPositionSeconds.valueAsNumber * 1000, true);
880
870
  return;
@@ -883,8 +873,9 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
883
873
  // Playing.
884
874
  playPositionSeconds.disabled = true;
885
875
 
886
- if (!audioSourceNode && !rafFallbackPlaying) {
887
- // No source node running: first play, after pause/seek, or after repeat.
876
+ if (!audioPlaying && !rafFallbackPlaying) {
877
+ // Not running: first play, after pause/seek, or after repeat.
878
+ // Clips whose file isn't decoded yet join in when it is, so nothing waits for them.
888
879
  let startMs = playPositionSeconds.valueAsNumber * 1000;
889
880
  if (startMs >= sectionEndTime - 0.05) {
890
881
  // At the end — jump to the beginning.
@@ -893,16 +884,24 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
893
884
  loadPlayPositionRange();
894
885
  }
895
886
  startAudio(startMs);
896
- // If audio isn't built yet (and not in fallback mode), hold the current frame.
897
- if (!audioSourceNode && !rafFallbackPlaying) {
898
- showFrame(playPositionSeconds.valueAsNumber * 1000, true);
899
- return;
900
- }
901
887
  }
902
888
 
903
889
  const timeInMs = currentAudioTimeMs();
904
890
 
891
+ if (voiceRecording) {
892
+ voicePanel?.setPastEnd(
893
+ timeInMs > sectionEndTime ? timeInMs - sectionEndTime : undefined,
894
+ );
895
+ }
905
896
  if (timeInMs >= sectionEndTime - 0.05) {
897
+ if (voiceRecording) {
898
+ // Talking after the end: freeze on the last frame, and keep recording.
899
+ // The clock keeps going, so the clip does too.
900
+ loadPlayPositionSeconds(sectionEndTime);
901
+ loadPlayPositionRange();
902
+ showFrame(sectionEndTime, true);
903
+ return;
904
+ }
906
905
  // Repeating nothing would restart the audio on every frame.
907
906
  if (repeatRadioButton.checked && sectionEndTime > sectionStartTime) {
908
907
  // Loop: restart from the beginning of the section.
@@ -1085,6 +1084,158 @@ const cancelRecordingButton = getById("cancelRecording", HTMLButtonElement);
1085
1084
  */
1086
1085
  const liveControls = getById("liveControls", HTMLFieldSetElement);
1087
1086
 
1087
+ // MARK: Voice recording
1088
+ //
1089
+ // 🎙 Record mode shows the voice recorder's panel and turns on the mic. The
1090
+ // panel's ● Record plays a chirp, then starts the video, and records until the
1091
+ // video pauses. Every time the video starts moving, a new clip starts; every
1092
+ // time it stops or jumps, the clip ends. Each clip goes into the Visual
1093
+ // Editor's root as a sound clip. See development-plans/voice-recording.md.
1094
+
1095
+ const recordModeButton = getById("recordModeBtn", HTMLButtonElement);
1096
+ const voicePanelHolder = getById("voicePanelHolder", HTMLDivElement);
1097
+ const recordJustSoundButton = getById("recordJustSound", HTMLButtonElement);
1098
+ const sectionEndRadios = document.querySelectorAll<HTMLInputElement>(
1099
+ 'input[name="onSectionEnd"]',
1100
+ );
1101
+
1102
+ /** Where the clip being recorded will go. For its block on the timeline. */
1103
+ let liveVoiceClip: { readonly owner: Showable; readonly startInOwnerMs: number } | undefined;
1104
+
1105
+ recordModeButton.addEventListener("click", async () => {
1106
+ if (voicePanel) {
1107
+ await voicePanel.close();
1108
+ return;
1109
+ }
1110
+ recordModeButton.disabled = true;
1111
+ // A panel that couldn't open the mic stays up to say why. Replace it.
1112
+ voicePanelHolder.replaceChildren();
1113
+ try {
1114
+ voicePanel = await openVoicePanel({
1115
+ parent: voicePanelHolder,
1116
+ context: audioContext,
1117
+ onRecord: startVoiceRecording,
1118
+ onStop: () => {
1119
+ // Same as unchecking Play.
1120
+ playCheckBox.checked = false;
1121
+ stopAudio();
1122
+ stopVoiceRecording();
1123
+ },
1124
+ onClose: () => {
1125
+ stopVoiceRecording();
1126
+ voicePanel = undefined;
1127
+ },
1128
+ });
1129
+ philDebug.voicePanel = voicePanel;
1130
+ } catch (error) {
1131
+ console.error("Record mode", error);
1132
+ } finally {
1133
+ recordModeButton.disabled = false;
1134
+ }
1135
+ });
1136
+
1137
+ /**
1138
+ * ● Record: mute the soundtrack, lock the controls that would spoil the
1139
+ * recording, play the chirp, then play the video from where it is.
1140
+ */
1141
+ async function startVoiceRecording(
1142
+ recorder: VoiceRecorder,
1143
+ folder: FileSystemDirectoryHandle,
1144
+ ): Promise<void> {
1145
+ if (suspendLiveAnimationLoop) {
1146
+ throw new Error("Wait until the video has finished saving.");
1147
+ }
1148
+ if (rafFallbackMode) {
1149
+ // ● Record is a click, so the audio clock can run now. Recording needs it.
1150
+ stopAudio();
1151
+ rafFallbackMode = false;
1152
+ autoplayFallbackMsg.hidden = true;
1153
+ }
1154
+ voiceRecording = true;
1155
+ voiceChirping = true;
1156
+ lockControlsForVoice(true);
1157
+ voicePanel?.setRecording(true);
1158
+ try {
1159
+ // Each file is named after the video, like the properties files.
1160
+ await recorder.start(folder, toShowKey);
1161
+ } catch (error) {
1162
+ stopVoiceRecording();
1163
+ throw error;
1164
+ } finally {
1165
+ voiceChirping = false;
1166
+ }
1167
+ // × during the chirp.
1168
+ if (!voiceRecording) return;
1169
+ // Start the clock again from where the video is, so the first clip starts
1170
+ // with it, whether the video was playing or not.
1171
+ stopAudio();
1172
+ playCheckBox.checked = true;
1173
+ }
1174
+
1175
+ /** The recording stopped: by Pause, ■ Stop, or closing the panel. Safe to call more than once. */
1176
+ function stopVoiceRecording(): void {
1177
+ if (!voiceRecording) return;
1178
+ voiceRecording = false;
1179
+ voicePanel?.recorder.stop();
1180
+ liveVoiceClip = undefined;
1181
+ voicePanel?.setRecording(false);
1182
+ lockControlsForVoice(false);
1183
+ refreshTimeline();
1184
+ }
1185
+
1186
+ /**
1187
+ * While recording, the soundtrack is muted and plays at 1×, and these controls
1188
+ * are disabled. Each keeps its value, for afterward.
1189
+ */
1190
+ function lockControlsForVoice(locked: boolean): void {
1191
+ muteCheckbox.disabled = locked;
1192
+ speedSelect.disabled = locked;
1193
+ for (const radio of sectionEndRadios) radio.disabled = locked;
1194
+ startRecordingButton.disabled = locked;
1195
+ recordJustSoundButton.disabled = locked;
1196
+ updateGain();
1197
+ setPlaybackRate(locked ? 1 : parseFloat(speedSelect.value));
1198
+ }
1199
+
1200
+ /** The video started moving, while recording: start a clip. */
1201
+ function beginVoiceClip(contextTime: number, fromMs: number): void {
1202
+ const recorder = voicePanel?.recorder;
1203
+ const owner = currentRoot();
1204
+ if (!recorder?.recording || !owner) return;
1205
+ const live = { owner, startInOwnerMs: fromMs - rootStartMs };
1206
+ liveVoiceClip = live;
1207
+ recorder.beginClip(contextTime).then(
1208
+ (recorded) => addVoiceClip(live.owner, live.startInOwnerMs, recorded),
1209
+ (error) => voicePanel?.say(`Couldn't save a recording: ${error}`, true),
1210
+ );
1211
+ refreshTimeline();
1212
+ }
1213
+
1214
+ /** The video stopped or jumped, while recording: end the clip. */
1215
+ function endVoiceClip(): void {
1216
+ voicePanel?.recorder.endClip(audioContext.currentTime);
1217
+ if (liveVoiceClip) {
1218
+ liveVoiceClip = undefined;
1219
+ refreshTimeline();
1220
+ }
1221
+ }
1222
+
1223
+ /** A clip's file is finished. Put it on the timeline. */
1224
+ function addVoiceClip(owner: Showable, startInOwnerMs: number, recorded: RecordedClip): void {
1225
+ // The samples are in memory already. Don't read the file back.
1226
+ soundtrack.provide(recorded.url, recorded.buffer);
1227
+ (owner.soundClips ??= []).push({
1228
+ source: recorded.url,
1229
+ startMsIntoScene: tidyMs(startInOwnerMs),
1230
+ startMsIntoClip: tidyMs(recorded.trimMs),
1231
+ lengthMs: tidyMs(recorded.lengthMs),
1232
+ });
1233
+ markDirty();
1234
+ soundtrack.request();
1235
+ refreshTimeline();
1236
+ if ((selectedSlideChild ?? currentRoot()) === owner) updateScheduleEditor(owner);
1237
+ }
1238
+
1088
1239
  /**
1089
1240
  * Someone hit the stop button.
1090
1241
  */
@@ -1184,30 +1335,13 @@ async function startRecording(
1184
1335
  // The file starts where its first frame starts, so the sound starts there too.
1185
1336
  const audioStartMs = (firstFrame * 1000) / FPS;
1186
1337
 
1187
- const fullAudioBuffer = audioBuilder.getAudioBuffer();
1188
- let audioBuffer: AudioBuffer;
1189
- if (firstFrame === 0 && saveEndMs >= toShow.duration) {
1190
- audioBuffer = fullAudioBuffer;
1191
- } else {
1192
- const sr = fullAudioBuffer.sampleRate;
1193
- const s0 = Math.round((audioStartMs / 1000) * sr);
1194
- const s1 = Math.min(
1195
- Math.round((saveEndMs / 1000) * sr),
1196
- fullAudioBuffer.length,
1197
- );
1198
- const len = Math.max(0, s1 - s0);
1199
- audioBuffer = new AudioBuffer({
1200
- numberOfChannels: fullAudioBuffer.numberOfChannels,
1201
- length: len,
1202
- sampleRate: sr,
1203
- });
1204
- for (let ch = 0; ch < fullAudioBuffer.numberOfChannels; ch++) {
1205
- audioBuffer.copyToChannel(
1206
- fullAudioBuffer.getChannelData(ch).subarray(s0, s0 + len),
1207
- ch,
1208
- );
1209
- }
1210
- }
1338
+ // The newest soundtrack, with every file in it decoded. Right after a reload or an
1339
+ // edit, that can take a moment. (After the file picker, which needs the click.)
1340
+ infoDiv.innerHTML = "Waiting for the sound…";
1341
+ await soundtrack.ready();
1342
+ const audioBuffer = soundtrack
1343
+ .mix(audioStartMs, Math.min(saveEndMs, toShow.duration))
1344
+ .getAudioBuffer();
1211
1345
  const audioSource = new AudioBufferSource({
1212
1346
  codec: "aac",
1213
1347
  bitrate: QUALITY_HIGH,
@@ -1713,7 +1847,7 @@ const visualEditorAPI: VisualEditorAPI = {
1713
1847
  const selectable = currentRoot();
1714
1848
  if (!selectable) return;
1715
1849
  if (howMuch === "sound") {
1716
- void initAudio();
1850
+ soundtrack.request();
1717
1851
  } else if (howMuch === "properties") {
1718
1852
  updateScheduleEditor(selectedSlideChild ?? selectable);
1719
1853
  } else {
@@ -1733,13 +1867,16 @@ const visualEditorAPI: VisualEditorAPI = {
1733
1867
  return playheadInRootMs();
1734
1868
  },
1735
1869
  getDecodedBuffer(url: string): AudioBuffer | null {
1736
- return audioBuilder.getDecodedBuffer(url);
1870
+ return soundtrack.getDecodedBuffer(url);
1737
1871
  },
1738
1872
  };
1739
1873
 
1740
1874
  // MARK: Console API
1741
1875
  philDebug.chapterList = chapterList;
1742
- philDebug.refreshSounds = () => void initAudio();
1876
+ /** Read and decode every sound file again, e.g. one re-recorded under the same name. */
1877
+ philDebug.refreshSounds = () => soundtrack.forget();
1878
+ /** The live soundtrack. See dev/soundtrack.ts. */
1879
+ philDebug.soundtrack = soundtrack;
1743
1880
  /**
1744
1881
  * Transcribe one file from scratch, skipping the cache, and report how long
1745
1882
  * it took. `device` is "webgpu" or "wasm"; leave it out for the normal choice.
@@ -1954,22 +2091,19 @@ const schedulesShowingDurations = new WeakSet<ScheduleInfo>();
1954
2091
  /** The selectable whose `.parent` is currently set to {@link veRootParent}. */
1955
2092
  let _veRootSelectable: Showable | undefined;
1956
2093
 
1957
- let _durationAudioTimer: ReturnType<typeof setTimeout> | undefined;
1958
-
1959
2094
  /**
1960
2095
  * Synthetic {@link ShowableParent} that acts as the root of the editable tree.
1961
2096
  * When a selectable's `scheduleHasChanged()` chain reaches this object we:
1962
2097
  * - refresh all visible duration inputs,
1963
2098
  * - kick the auto-save / dirty-status machinery, and
1964
- * - debounce an audio reload.
2099
+ * - ask for a new soundtrack (which does nothing if no sound clip moved).
1965
2100
  */
1966
2101
  const veRootParent: ShowableParent = {
1967
2102
  scheduleHasChanged() {
1968
2103
  for (const cb of durationSyncCallbacks) cb();
1969
2104
  for (const cb of scheduleEditorRefreshers) cb();
1970
2105
  markDirty();
1971
- clearTimeout(_durationAudioTimer);
1972
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2106
+ soundtrack.request();
1973
2107
  // Redraw the timeline so block positions/sizes update during drags.
1974
2108
  refreshTimeline();
1975
2109
  scheduleChapterRefresh();
@@ -1991,8 +2125,7 @@ const toShowParent: ShowableParent = {
1991
2125
  for (const cb of durationSyncCallbacks) cb();
1992
2126
  for (const cb of scheduleEditorRefreshers) cb();
1993
2127
  markDirty();
1994
- clearTimeout(_durationAudioTimer);
1995
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2128
+ soundtrack.request();
1996
2129
  refreshTimeline();
1997
2130
  scheduleChapterRefresh();
1998
2131
  },
@@ -2207,8 +2340,7 @@ transcriptView = new TranscriptView({
2207
2340
  clips.splice(index, 1, ...pieces);
2208
2341
  selectedSoundClip = pieces[0];
2209
2342
  markDirty();
2210
- clearTimeout(_durationAudioTimer);
2211
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2343
+ soundtrack.request();
2212
2344
  // Show the owner's Sound Clips, with the remaining piece highlighted.
2213
2345
  selectInChapter(owner);
2214
2346
  refreshTimeline();
@@ -2281,12 +2413,11 @@ timelineDisplay.onBlockClick = (id) => {
2281
2413
 
2282
2414
  /**
2283
2415
  * A sound clip's numbers changed, from a field or a drag on the timeline.
2284
- * Save, rebuild the audio soon, and bring the fields and the timeline up to date.
2416
+ * Save, update the soundtrack, and bring the fields and the timeline up to date.
2285
2417
  */
2286
2418
  function _onClipValueChanged(): void {
2287
2419
  markDirty();
2288
- clearTimeout(_durationAudioTimer);
2289
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2420
+ soundtrack.request();
2290
2421
  for (const cb of soundClipSyncCallbacks) cb();
2291
2422
  timelineDisplay.redraw();
2292
2423
  }
@@ -2298,7 +2429,7 @@ const MIN_SOUND_CLIP_MS = 50;
2298
2429
 
2299
2430
  /** How long the file `clip` plays from is, once it has been decoded. */
2300
2431
  function soundFileMs(clip: SoundClip): number | undefined {
2301
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2432
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
2302
2433
  return buffer ? buffer.duration * 1000 : undefined;
2303
2434
  }
2304
2435
 
@@ -2400,7 +2531,7 @@ function soundClipBlock(clip: SoundClip, ownerStart: number): TimelineBlock {
2400
2531
  startMs: start,
2401
2532
  durationMs: () => soundClipLengthMs(clip) ?? 0,
2402
2533
  waveform: () => {
2403
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2534
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
2404
2535
  return buffer ? { buffer, fromMs: clip.startMsIntoClip ?? 0 } : undefined;
2405
2536
  },
2406
2537
  onDragBody: (newStartMs) => {
@@ -2556,6 +2687,24 @@ function _buildTimelineBlocks(selectable: Showable): TimelineBlock[] {
2556
2687
  }
2557
2688
  }
2558
2689
 
2690
+ // The voice clip being recorded, growing as you talk.
2691
+ const live = liveVoiceClip;
2692
+ const liveOwnerStart = live && startWithin(selectable, live.owner);
2693
+ if (live && liveOwnerStart !== undefined) {
2694
+ blocks.push({
2695
+ id: live,
2696
+ label: "● Recording",
2697
+ color: "#c62828",
2698
+ lane: "sound",
2699
+ startMs: () => liveOwnerStart + live.startInOwnerMs,
2700
+ durationMs: () => voicePanel?.recorder.liveClip()?.lengthMs ?? 0,
2701
+ waveform: () => {
2702
+ const clip = voicePanel?.recorder.liveClip();
2703
+ return clip && { buffer: clip.buffer, fromMs: clip.trimMs };
2704
+ },
2705
+ });
2706
+ }
2707
+
2559
2708
  return blocks;
2560
2709
  }
2561
2710
 
@@ -3622,6 +3771,18 @@ async function initFromDB(unloadBackup?: string | null): Promise<void> {
3622
3771
  updateComponentEditor(currentSel);
3623
3772
  updateScheduleEditor(currentSel);
3624
3773
  }
3774
+ afterStateApplied();
3775
+ }
3776
+
3777
+ /**
3778
+ * A saved state was just applied to the tree: restored at startup, opened,
3779
+ * or picked in the history. The sound clips in it are new objects, maybe in
3780
+ * new lists, so the timeline's blocks and the soundtrack are out of date.
3781
+ * The editors are rebuilt separately.
3782
+ */
3783
+ function afterStateApplied(): void {
3784
+ refreshTimeline();
3785
+ soundtrack.request();
3625
3786
  }
3626
3787
 
3627
3788
 
@@ -3721,7 +3882,6 @@ function currentSaveTarget(): Showable | null {
3721
3882
  }
3722
3883
 
3723
3884
  function saveOnUnload() {
3724
-
3725
3885
  // When the history dialog is open the live tree may hold a transient preview from
3726
3886
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
3727
3887
  // persisted as if the user had accepted it.
@@ -3815,6 +3975,7 @@ function _dialogSelectItem(index: number, target: Showable) {
3815
3975
  activeRootComponentEditor?.resetAll();
3816
3976
  updateComponentEditor(target);
3817
3977
  updateScheduleEditor(target);
3978
+ afterStateApplied();
3818
3979
 
3819
3980
  // The Abandon/Save buttons are no longer used; only Keep is shown.
3820
3981
  historyOkBtn.hidden = false;
@@ -4057,6 +4218,7 @@ async function _applyDialogSelection() {
4057
4218
  activeRootComponentEditor?.resetAll();
4058
4219
  updateComponentEditor(target);
4059
4220
  updateScheduleEditor(target);
4221
+ afterStateApplied();
4060
4222
  }
4061
4223
 
4062
4224
  historyOkBtn.addEventListener("click", () => {
@@ -4085,6 +4247,7 @@ historyCancelBtn.addEventListener("click", () => {
4085
4247
  activeRootComponentEditor?.resetAll();
4086
4248
  updateComponentEditor(target);
4087
4249
  updateScheduleEditor(target);
4250
+ afterStateApplied();
4088
4251
  }
4089
4252
  historyDialog.close();
4090
4253
  });
@@ -5463,30 +5626,34 @@ function updateComponentEditor(selectable: Showable) {
5463
5626
  }
5464
5627
 
5465
5628
  /**
5466
- * The Sound Clips section of the schedule editor, for a component whose
5467
- * `soundClips` is defined. One card per clip, plus Add and Paste.
5629
+ * The Sound Clips section of the schedule editor. One card per clip, plus Add and Paste.
5630
+ *
5631
+ * Every component gets one. A component with no `soundClips` list gets one
5632
+ * when its first clip is added.
5468
5633
  *
5469
5634
  * Each card's Owner menu moves the clip to another component without changing
5470
5635
  * when it plays. Registers per-field sync callbacks into
5471
5636
  * {@link soundClipSyncCallbacks}, so drags on the timeline show up here.
5472
5637
  */
5473
5638
  function buildSoundClipSection(selectable: Showable): HTMLElement {
5474
- const clips = selectable.soundClips!;
5639
+ const clips = selectable.soundClips ?? [];
5640
+ /** Call before adding a clip. Merely selecting a component doesn't give it a list. */
5641
+ const ensureList = () => (selectable.soundClips ??= clips);
5475
5642
 
5476
5643
  /** The clip list changed shape: save, rebuild the audio, redraw this section and the timeline. */
5477
5644
  function afterStructureChange(): void {
5478
5645
  markDirty();
5479
- clearTimeout(_durationAudioTimer);
5480
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
5646
+ soundtrack.request();
5481
5647
  updateScheduleEditor(selectable);
5482
5648
  refreshTimeline();
5483
5649
  }
5484
5650
 
5485
- /** Every place a sound can live in this video, and when each starts. */
5651
+ /** Every place a sound lives in this video, and when each starts. */
5486
5652
  const owners = soundOwners(toShow);
5653
+ /** Undefined until this component has a list. Then it has cards, with Owner menus that need it. */
5487
5654
  const self = owners.find(({ owner }) => owner === selectable);
5488
5655
  /** When this component starts, in video time. 0 if it can't be found, which shouldn't happen. */
5489
- const selfStartMs = self?.startMs ?? 0;
5656
+ const selfStartMs = startWithin(toShow, selectable) ?? 0;
5490
5657
 
5491
5658
  const section = document.createElement("fieldset");
5492
5659
  const legend = document.createElement("legend");
@@ -5506,6 +5673,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5506
5673
  addBtn.style.marginLeft = "auto";
5507
5674
  addBtn.addEventListener("click", () => {
5508
5675
  const clip: SoundClip = { source: "", startMsIntoScene: playheadInOwner() };
5676
+ ensureList();
5509
5677
  clips.push(clip);
5510
5678
  selectedSoundClip = clip;
5511
5679
  afterStructureChange();
@@ -5529,6 +5697,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5529
5697
  alert("No sound clips found on the clipboard. Each one needs at least a source.");
5530
5698
  return;
5531
5699
  }
5700
+ ensureList();
5532
5701
  clips.push(...pasted);
5533
5702
  selectedSoundClip = pasted[0];
5534
5703
  afterStructureChange();
@@ -5824,8 +5993,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5824
5993
  rehomeSoundClip(clip, self, to);
5825
5994
  selectedSoundClip = clip;
5826
5995
  markDirty();
5827
- clearTimeout(_durationAudioTimer);
5828
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
5996
+ soundtrack.request();
5829
5997
  const chapter = currentRoot();
5830
5998
  if (chapter && startWithin(chapter, to.owner) !== undefined) {
5831
5999
  // Follow the clip to its new owner.
@@ -5948,16 +6116,7 @@ function updateScheduleEditor(selectable: Showable) {
5948
6116
  const multiText =
5949
6117
  selectable instanceof MultiTextComponent ? selectable : null;
5950
6118
 
5951
- if (
5952
- !scalars?.length &&
5953
- !schedules?.length &&
5954
- !isTraditionalText &&
5955
- !slideComponent &&
5956
- selectable.soundClips === undefined
5957
- ) {
5958
- scheduleEditorFieldset.hidden = true;
5959
- return;
5960
- }
6119
+ // Every component has something to edit: at least its name and its sound clips.
5961
6120
  scheduleEditorFieldset.hidden = false;
5962
6121
  scheduleEditorFieldset.append(buildNameSection(selectable));
5963
6122
 
@@ -6126,9 +6285,7 @@ function updateScheduleEditor(selectable: Showable) {
6126
6285
  }
6127
6286
  scheduleEditorFieldset.append(section);
6128
6287
  }
6129
- if (selectable.soundClips !== undefined) {
6130
- scheduleEditorFieldset.append(buildSoundClipSection(selectable));
6131
- }
6288
+ scheduleEditorFieldset.append(buildSoundClipSection(selectable));
6132
6289
  }
6133
6290
 
6134
6291
  // MARK: Split
@@ -7530,15 +7687,20 @@ document.addEventListener("keyup", (e) => {
7530
7687
  getById("recordJustSound", HTMLButtonElement).addEventListener(
7531
7688
  "click",
7532
7689
  async () => {
7533
- const blob = await audioBuilder.toBlob();
7534
- downloadBlob("sound_file.wav", blob);
7690
+ // The newest soundtrack, with every file in it decoded.
7691
+ const before = infoDiv.innerHTML;
7692
+ infoDiv.innerHTML = "Waiting for the sound…";
7693
+ await soundtrack.ready();
7694
+ infoDiv.innerHTML = before;
7695
+ downloadBlob("sound_file.wav", soundtrack.mix(0, toShow.duration).toBlob());
7535
7696
  },
7536
7697
  );
7537
7698
 
7538
7699
  function reload(): void {
7539
7700
  initChapters();
7540
7701
  updateFromSelect();
7541
- initAudio();
7702
+ // Reload means everything, including sound files changed on disk.
7703
+ soundtrack.forget();
7542
7704
  }
7543
7705
 
7544
7706
  getById("reloadBtn", HTMLButtonElement).addEventListener("click", reload);
@@ -7709,6 +7871,7 @@ function refreshEditorsAfterLoad(): void {
7709
7871
  activeRootComponentEditor?.resetAll();
7710
7872
  updateComponentEditor(current);
7711
7873
  updateScheduleEditor(current);
7874
+ afterStateApplied();
7712
7875
  // The loaded state may use local files that need 🔓.
7713
7876
  checkVideosLocalFiles();
7714
7877
  }
@@ -7919,12 +8082,30 @@ if (import.meta.hot) {
7919
8082
  // Changing a typescript file invokes this.
7920
8083
  // Changing a css file would cause vite:beforeUpdate, instead.
7921
8084
  import.meta.hot.on("vite:beforeFullReload", (_data) => {
8085
+ finishVoiceOnUnload();
7922
8086
  saveState();
7923
8087
  saveOnUnload();
7924
8088
  });
7925
8089
  }
7926
8090
 
7927
- window.addEventListener("beforeunload", saveOnUnload);
8091
+ /**
8092
+ * Start closing any voice recording's files. They may not finish in time.
8093
+ *
8094
+ * Only when the page is really going away. Not on visibilitychange: a page is hidden by
8095
+ * another tab, another app or another desktop, often to read a script, and the recording
8096
+ * should keep going.
8097
+ *
8098
+ * TODO: test this, and add the clip being recorded before {@link saveOnUnload}'s backup.
8099
+ * See "Risks" in development-plans/voice-recording.md.
8100
+ */
8101
+ function finishVoiceOnUnload() {
8102
+ voicePanel?.recorder.flush();
8103
+ }
8104
+
8105
+ window.addEventListener("beforeunload", () => {
8106
+ finishVoiceOnUnload();
8107
+ saveOnUnload();
8108
+ });
7928
8109
  document.addEventListener("visibilitychange", () => {
7929
8110
  if (document.visibilityState === "hidden") saveOnUnload();
7930
8111
  });