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