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
@@ -7,8 +7,9 @@ import { Lattice } from "../src/lattice.js";
7
7
  import { interpolateArrow } from "../src/schedule-helper.js";
8
8
  import { applyJsonEntry, applyTree, counterparts, fillTreeDefaults, findSerializedNode, isVideoSnapshot, omitComponentDefaults, registryDefault, omitTreeDefaults, serializeComponents, serializeScalars, serializeSchedules, serializeTree, SNAPSHOT_FORMAT_VERSION, } from "../src/snapshot.js";
9
9
  import { downloadBlob, philDebug } from "../src/utility.js";
10
- import { debugLog, getNewDebugLogEntries } from "../src/debug-log.js";
11
- import { AudioBuilder } from "./audio-builder.js";
10
+ import { getNewDebugLogEntries } from "../src/debug-log.js";
11
+ import { SAMPLE_RATE, Soundtrack } from "./soundtrack.js";
12
+ import { openVoicePanel } from "./voice/voice-panel.js";
12
13
  import { openColorPickerDialog } from "./color-picker.js";
13
14
  import { setSwatchColor } from "./color-utils.js";
14
15
  import { addName, buildEaseSelect, buildNumericInput, buildScalarSection, parseScheduleFromClipboard, scheduleToTypeScript, } from "./schedule-helpers.js";
@@ -21,7 +22,7 @@ import { ownerOf, parseSoundClips, rehomeSoundClip, soundOwners, startWithin, ti
21
22
  import { askHowToSplit, askHowToSplitSound } from "./split-dialog.js";
22
23
  import { SyncedFile } from "./synced-file.js";
23
24
  import { TimelineDisplay, } from "./timeline-display.js";
24
- import { forgetTranscripts, makeTranscript, onTranscriptsChange, readyTranscript, setTranscriptsEnabled, statusText, transcriptsEnabled, transcriptStatus, transcriptsSummary, } from "./transcripts.js";
25
+ import { forgetTranscriptFailures, forgetTranscripts, makeTranscript, onTranscriptsChange, readyTranscript, setTranscriptsEnabled, statusText, transcriptsEnabled, transcriptStatus, transcriptsSummary, } from "./transcripts.js";
25
26
  import { transcriptFileName, transcriptJson } from "./transcript-export.js";
26
27
  import { wordFlag } from "./transcript-align.js";
27
28
  import { canvasRecorder } from "../lib/main-control.js";
@@ -333,8 +334,9 @@ onLocalFilesChange(updateLocalFilesButton);
333
334
  /** Ask about every file that needs it. Then the sounds can load. */
334
335
  async function allowLocalFiles() {
335
336
  await requestLocalFileAccess();
336
- // The images and video clips try again by themselves. The sounds are loaded all at once.
337
- void initAudio();
337
+ // The images and video clips try again by themselves.
338
+ soundtrack.forgetFailures();
339
+ forgetTranscriptFailures();
338
340
  }
339
341
  localFilesBtn.addEventListener("click", () => void allowLocalFiles());
340
342
  /**
@@ -493,16 +495,46 @@ function loadPlayPositionSeconds(timeInMs) {
493
495
  function loadPlayPositionRange() {
494
496
  playPositionRange.valueAsNumber = playPositionSeconds.valueAsNumber * 1000;
495
497
  }
496
- const audioContext = new AudioContext();
498
+ // The same rate as the decoded files and the voice recorder, whatever the hardware uses.
499
+ const audioContext = new AudioContext({ sampleRate: SAMPLE_RATE });
497
500
  console.log(audioContext);
498
501
  const gainNode = audioContext.createGain();
499
502
  gainNode.connect(audioContext.destination);
500
- /** Set to true once the AudioBuffer has been fully built and is safe to play. */
501
- let audioReady = false;
502
- let audioSourceNode = null;
503
- /** audioContext.currentTime at the moment startAudio() last started a source node. */
503
+ /**
504
+ * Every sound clip in the video, playing live. Ask it for a new soundtrack with
505
+ * `soundtrack.request()`, as often as you like: it does the rate limiting.
506
+ */
507
+ const soundtrack = new Soundtrack({
508
+ context: audioContext,
509
+ destination: gainNode,
510
+ root: () => toShow,
511
+ // Sound clips on the timeline can now show their waveforms, and the ones
512
+ // that play to the end of their file now know how long that is.
513
+ onDecoded: () => timelineDisplay.redraw(),
514
+ // The new file may be a local one that needs 🔓.
515
+ onNewSource: () => checkVideosLocalFiles(),
516
+ });
517
+ soundtrack.request();
518
+ // The images and videos may be local files too, even with no sound.
519
+ checkVideosLocalFiles();
520
+ /** True between startAudio() and stopAudio(), unless {@link rafFallbackMode}. */
521
+ let audioPlaying = false;
522
+ /**
523
+ * True from ● Record until the voice recording stops. The soundtrack is muted,
524
+ * and the controls that would spoil the recording are disabled.
525
+ * See {@link startVoiceRecording}.
526
+ */
527
+ let voiceRecording = false;
528
+ /**
529
+ * True while ● Record's chirp plays, before the video starts. Being paused
530
+ * then doesn't stop the recording.
531
+ */
532
+ let voiceChirping = false;
533
+ /** The voice recorder's controls, while 🎙 Record mode is showing them. */
534
+ let voicePanel;
535
+ /** audioContext.currentTime at the moment startAudio() last anchored the clock. */
504
536
  let audioContextStartTime = 0;
505
- /** Media position (ms) at the moment startAudio() last started a source node. */
537
+ /** Media position (ms) at the moment startAudio() last anchored the clock. */
506
538
  let audioMediaStartMs = 0;
507
539
  let audioPlaybackRate = 1;
508
540
  /**
@@ -514,7 +546,7 @@ let audioPlaybackRate = 1;
514
546
  * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
515
547
  */
516
548
  let rafFallbackMode = false;
517
- /** True when fallback-mode "playback" is running (mirrors audioSourceNode !== null). */
549
+ /** True when fallback-mode "playback" is running (mirrors {@link audioPlaying}). */
518
550
  let rafFallbackPlaying = false;
519
551
  /** performance.now() at the moment fallback playback last started. */
520
552
  let rafFallbackStartPerf = 0;
@@ -550,8 +582,6 @@ function startAudio(fromMs) {
550
582
  rafFallbackPlaying = true;
551
583
  return;
552
584
  }
553
- if (!audioReady)
554
- return;
555
585
  if (audioContext.state !== "running") {
556
586
  if (!navigator.userActivation.isActive) {
557
587
  // No user gesture available (e.g. restoring play state on page load).
@@ -559,30 +589,36 @@ function startAudio(fromMs) {
559
589
  enterRafFallback(fromMs, false);
560
590
  return;
561
591
  }
562
- // Has a user gesture. resume() is async — the source node below plays
592
+ // Has a user gesture. resume() is async — the source nodes below play
563
593
  // once the context transitions to running. Do NOT check state synchronously
564
594
  // after this call; it will still read "suspended" before the promise resolves.
565
595
  audioContext.resume().catch(() => { });
566
596
  }
567
- const source = audioContext.createBufferSource();
568
- source.buffer = audioBuilder.getAudioBuffer();
569
- source.playbackRate.value = audioPlaybackRate;
570
- source.connect(gainNode);
571
597
  const contextNow = audioContext.currentTime;
572
- source.start(contextNow, fromMs / 1000);
573
- audioSourceNode = source;
574
598
  audioContextStartTime = contextNow;
575
599
  audioMediaStartMs = fromMs;
600
+ soundtrack.play({
601
+ contextTime: contextNow,
602
+ mediaMs: fromMs,
603
+ rate: audioPlaybackRate,
604
+ });
605
+ audioPlaying = true;
606
+ if (voiceRecording)
607
+ beginVoiceClip(contextNow, fromMs);
576
608
  }
609
+ /**
610
+ * Stop the sound and the clock. Called for every seek too: the animation loop
611
+ * starts again from the play position on its next frame.
612
+ *
613
+ * While recording a voice, this ends the clip, and the next start begins a new one.
614
+ */
577
615
  function stopAudio() {
578
616
  rafFallbackPlaying = false;
579
- if (audioSourceNode) {
580
- try {
581
- audioSourceNode.stop();
582
- }
583
- catch (_) { }
584
- audioSourceNode.disconnect();
585
- audioSourceNode = null;
617
+ if (audioPlaying) {
618
+ soundtrack.stop();
619
+ audioPlaying = false;
620
+ if (voiceRecording)
621
+ endVoiceClip();
586
622
  }
587
623
  }
588
624
  /**
@@ -595,16 +631,26 @@ function setPlaybackRate(rate) {
595
631
  rafFallbackStartMs = currentMs;
596
632
  rafFallbackStartPerf = performance.now();
597
633
  }
598
- else if (audioSourceNode) {
634
+ else if (audioPlaying) {
599
635
  const currentMs = currentAudioTimeMs();
600
636
  audioContextStartTime = audioContext.currentTime;
601
637
  audioMediaStartMs = currentMs;
602
- audioSourceNode.playbackRate.value = rate;
638
+ soundtrack.changeRate({
639
+ contextTime: audioContextStartTime,
640
+ mediaMs: audioMediaStartMs,
641
+ rate,
642
+ });
603
643
  }
604
644
  audioPlaybackRate = rate;
605
645
  }
646
+ const volumeSlider = getById("volumeAudio", HTMLInputElement);
647
+ const speedSelect = getById("speedAudio", HTMLSelectElement);
648
+ /** The soundtrack's volume: the slider, unless it's muted, or a voice is being recorded. */
649
+ function updateGain() {
650
+ gainNode.gain.value =
651
+ muteCheckbox.checked || voiceRecording ? 0 : volumeSlider.valueAsNumber;
652
+ }
606
653
  {
607
- const volumeSlider = getById("volumeAudio", HTMLInputElement);
608
654
  muteCheckbox.addEventListener("input", () => {
609
655
  if (!muteCheckbox.checked && rafFallbackMode) {
610
656
  // Un-muting is a user gesture — try to exit fallback and resume real audio.
@@ -617,68 +663,13 @@ function setPlaybackRate(rate) {
617
663
  startAudio(currentMs);
618
664
  }
619
665
  }
620
- gainNode.gain.value = muteCheckbox.checked ? 0 : volumeSlider.valueAsNumber;
666
+ updateGain();
621
667
  });
622
- volumeSlider.addEventListener("input", () => {
623
- if (!muteCheckbox.checked) {
624
- gainNode.gain.value = volumeSlider.valueAsNumber;
625
- }
626
- });
627
- getById("speedAudio", HTMLSelectElement).addEventListener("change", (e) => {
628
- setPlaybackRate(parseFloat(e.target.value));
668
+ volumeSlider.addEventListener("input", updateGain);
669
+ speedSelect.addEventListener("change", () => {
670
+ setPlaybackRate(parseFloat(speedSelect.value));
629
671
  });
630
672
  }
631
- let audioBuilder = new AudioBuilder(toShow.duration);
632
- let reloadGeneration = 0;
633
- async function initAudio() {
634
- // The sound clips are being re-read, so this is a good time to look for files needing 🔓.
635
- checkVideosLocalFiles();
636
- const myGen = ++reloadGeneration;
637
- audioReady = false;
638
- stopAudio();
639
- const newBuilder = new AudioBuilder(toShow.duration);
640
- async function doIt(item, offset) {
641
- if (myGen !== reloadGeneration)
642
- return false;
643
- if (item.soundClips) {
644
- for (const clip of item.soundClips) {
645
- // A brand new clip has no source yet, and a URL being typed is wrong
646
- // until it's finished. Either way, skip that one clip, not all audio.
647
- if (clip.source === "")
648
- continue;
649
- try {
650
- await newBuilder.add(clip.source, offset + clip.startMsIntoScene, clip.startMsIntoClip, clip.lengthMs);
651
- }
652
- catch (reason) {
653
- debugLog("audio", `Skipped "${clip.source}": ${reason}`);
654
- }
655
- if (myGen !== reloadGeneration)
656
- return false;
657
- }
658
- }
659
- if (item.children) {
660
- for (const { child, start } of item.children) {
661
- if (!(await doIt(child, offset + start)))
662
- return false;
663
- }
664
- }
665
- return true;
666
- }
667
- const time1 = performance.now();
668
- const completed = await doIt(toShow, 0);
669
- const time2 = performance.now();
670
- if (!completed) {
671
- console.log(`Audio init superseded after ${(time2 - time1).toFixed(0)} ms.`);
672
- return;
673
- }
674
- audioBuilder = newBuilder;
675
- audioReady = true;
676
- console.log(`Audio ready in ${(time2 - time1).toFixed(0)} ms.`);
677
- // Sound clips on the timeline can now show their waveforms, and the ones
678
- // that play to the end of their file now know how long that is.
679
- timelineDisplay.redraw();
680
- }
681
- initAudio();
682
673
  /**
683
674
  * We disable {@link animationLoop} while rendering to a file.
684
675
  * We can reenable it when we are done rendering.
@@ -696,14 +687,18 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs) => {
696
687
  if (!playCheckBox.checked) {
697
688
  // Paused.
698
689
  stopAudio();
690
+ // Pausing is how a voice recording stops, once the video has started.
691
+ if (voiceRecording && !voiceChirping)
692
+ stopVoiceRecording();
699
693
  playPositionSeconds.disabled = false;
700
694
  showFrame(playPositionSeconds.valueAsNumber * 1000, true);
701
695
  return;
702
696
  }
703
697
  // Playing.
704
698
  playPositionSeconds.disabled = true;
705
- if (!audioSourceNode && !rafFallbackPlaying) {
706
- // No source node running: first play, after pause/seek, or after repeat.
699
+ if (!audioPlaying && !rafFallbackPlaying) {
700
+ // Not running: first play, after pause/seek, or after repeat.
701
+ // Clips whose file isn't decoded yet join in when it is, so nothing waits for them.
707
702
  let startMs = playPositionSeconds.valueAsNumber * 1000;
708
703
  if (startMs >= sectionEndTime - 0.05) {
709
704
  // At the end — jump to the beginning.
@@ -712,14 +707,20 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs) => {
712
707
  loadPlayPositionRange();
713
708
  }
714
709
  startAudio(startMs);
715
- // If audio isn't built yet (and not in fallback mode), hold the current frame.
716
- if (!audioSourceNode && !rafFallbackPlaying) {
717
- showFrame(playPositionSeconds.valueAsNumber * 1000, true);
718
- return;
719
- }
720
710
  }
721
711
  const timeInMs = currentAudioTimeMs();
712
+ if (voiceRecording) {
713
+ voicePanel?.setPastEnd(timeInMs > sectionEndTime ? timeInMs - sectionEndTime : undefined);
714
+ }
722
715
  if (timeInMs >= sectionEndTime - 0.05) {
716
+ if (voiceRecording) {
717
+ // Talking after the end: freeze on the last frame, and keep recording.
718
+ // The clock keeps going, so the clip does too.
719
+ loadPlayPositionSeconds(sectionEndTime);
720
+ loadPlayPositionRange();
721
+ showFrame(sectionEndTime, true);
722
+ return;
723
+ }
723
724
  // Repeating nothing would restart the audio on every frame.
724
725
  if (repeatRadioButton.checked && sectionEndTime > sectionStartTime) {
725
726
  // Loop: restart from the beginning of the section.
@@ -886,6 +887,149 @@ const cancelRecordingButton = getById("cancelRecording", HTMLButtonElement);
886
887
  * Some of these display the right data, but you can't change them.
887
888
  */
888
889
  const liveControls = getById("liveControls", HTMLFieldSetElement);
890
+ // MARK: Voice recording
891
+ //
892
+ // 🎙 Record mode shows the voice recorder's panel and turns on the mic. The
893
+ // panel's ● Record plays a chirp, then starts the video, and records until the
894
+ // video pauses. Every time the video starts moving, a new clip starts; every
895
+ // time it stops or jumps, the clip ends. Each clip goes into the Visual
896
+ // Editor's root as a sound clip. See development-plans/voice-recording.md.
897
+ const recordModeButton = getById("recordModeBtn", HTMLButtonElement);
898
+ const voicePanelHolder = getById("voicePanelHolder", HTMLDivElement);
899
+ const recordJustSoundButton = getById("recordJustSound", HTMLButtonElement);
900
+ const sectionEndRadios = document.querySelectorAll('input[name="onSectionEnd"]');
901
+ /** Where the clip being recorded will go. For its block on the timeline. */
902
+ let liveVoiceClip;
903
+ recordModeButton.addEventListener("click", async () => {
904
+ if (voicePanel) {
905
+ await voicePanel.close();
906
+ return;
907
+ }
908
+ recordModeButton.disabled = true;
909
+ // A panel that couldn't open the mic stays up to say why. Replace it.
910
+ voicePanelHolder.replaceChildren();
911
+ try {
912
+ voicePanel = await openVoicePanel({
913
+ parent: voicePanelHolder,
914
+ context: audioContext,
915
+ onRecord: startVoiceRecording,
916
+ onStop: () => {
917
+ // Same as unchecking Play.
918
+ playCheckBox.checked = false;
919
+ stopAudio();
920
+ stopVoiceRecording();
921
+ },
922
+ onClose: () => {
923
+ stopVoiceRecording();
924
+ voicePanel = undefined;
925
+ },
926
+ });
927
+ philDebug.voicePanel = voicePanel;
928
+ }
929
+ catch (error) {
930
+ console.error("Record mode", error);
931
+ }
932
+ finally {
933
+ recordModeButton.disabled = false;
934
+ }
935
+ });
936
+ /**
937
+ * ● Record: mute the soundtrack, lock the controls that would spoil the
938
+ * recording, play the chirp, then play the video from where it is.
939
+ */
940
+ async function startVoiceRecording(recorder, folder) {
941
+ if (suspendLiveAnimationLoop) {
942
+ throw new Error("Wait until the video has finished saving.");
943
+ }
944
+ if (rafFallbackMode) {
945
+ // ● Record is a click, so the audio clock can run now. Recording needs it.
946
+ stopAudio();
947
+ rafFallbackMode = false;
948
+ autoplayFallbackMsg.hidden = true;
949
+ }
950
+ voiceRecording = true;
951
+ voiceChirping = true;
952
+ lockControlsForVoice(true);
953
+ voicePanel?.setRecording(true);
954
+ try {
955
+ // Each file is named after the video, like the properties files.
956
+ await recorder.start(folder, toShowKey);
957
+ }
958
+ catch (error) {
959
+ stopVoiceRecording();
960
+ throw error;
961
+ }
962
+ finally {
963
+ voiceChirping = false;
964
+ }
965
+ // × during the chirp.
966
+ if (!voiceRecording)
967
+ return;
968
+ // Start the clock again from where the video is, so the first clip starts
969
+ // with it, whether the video was playing or not.
970
+ stopAudio();
971
+ playCheckBox.checked = true;
972
+ }
973
+ /** The recording stopped: by Pause, ■ Stop, or closing the panel. Safe to call more than once. */
974
+ function stopVoiceRecording() {
975
+ if (!voiceRecording)
976
+ return;
977
+ voiceRecording = false;
978
+ voicePanel?.recorder.stop();
979
+ liveVoiceClip = undefined;
980
+ voicePanel?.setRecording(false);
981
+ lockControlsForVoice(false);
982
+ refreshTimeline();
983
+ }
984
+ /**
985
+ * While recording, the soundtrack is muted and plays at 1×, and these controls
986
+ * are disabled. Each keeps its value, for afterward.
987
+ */
988
+ function lockControlsForVoice(locked) {
989
+ muteCheckbox.disabled = locked;
990
+ speedSelect.disabled = locked;
991
+ for (const radio of sectionEndRadios)
992
+ radio.disabled = locked;
993
+ startRecordingButton.disabled = locked;
994
+ recordJustSoundButton.disabled = locked;
995
+ updateGain();
996
+ setPlaybackRate(locked ? 1 : parseFloat(speedSelect.value));
997
+ }
998
+ /** The video started moving, while recording: start a clip. */
999
+ function beginVoiceClip(contextTime, fromMs) {
1000
+ const recorder = voicePanel?.recorder;
1001
+ const owner = currentRoot();
1002
+ if (!recorder?.recording || !owner)
1003
+ return;
1004
+ const live = { owner, startInOwnerMs: fromMs - rootStartMs };
1005
+ liveVoiceClip = live;
1006
+ recorder.beginClip(contextTime).then((recorded) => addVoiceClip(live.owner, live.startInOwnerMs, recorded), (error) => voicePanel?.say(`Couldn't save a recording: ${error}`, true));
1007
+ refreshTimeline();
1008
+ }
1009
+ /** The video stopped or jumped, while recording: end the clip. */
1010
+ function endVoiceClip() {
1011
+ voicePanel?.recorder.endClip(audioContext.currentTime);
1012
+ if (liveVoiceClip) {
1013
+ liveVoiceClip = undefined;
1014
+ refreshTimeline();
1015
+ }
1016
+ }
1017
+ /** A clip's file is finished. Put it on the timeline. */
1018
+ function addVoiceClip(owner, startInOwnerMs, recorded) {
1019
+ // The samples are in memory already. Don't read the file back.
1020
+ soundtrack.provide(recorded.url, recorded.buffer);
1021
+ (owner.soundClips ??= []).push({
1022
+ source: recorded.url,
1023
+ startMsIntoScene: tidyMs(startInOwnerMs),
1024
+ startMsIntoClip: tidyMs(recorded.trimMs),
1025
+ lengthMs: tidyMs(recorded.lengthMs),
1026
+ });
1027
+ markDirty();
1028
+ soundtrack.request();
1029
+ refreshTimeline();
1030
+ if ((selectedSlideChild ?? currentRoot()) === owner)
1031
+ updateScheduleEditor(owner);
1032
+ }
889
1033
  /**
890
1034
  * Someone hit the stop button.
891
1035
  */
@@ -968,25 +1112,13 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration, pixe
968
1112
  const firstFrame = firstFrameAtOrAfter(saveStartMs);
969
1113
  // The file starts where its first frame starts, so the sound starts there too.
970
1114
  const audioStartMs = (firstFrame * 1000) / FPS;
971
- const fullAudioBuffer = audioBuilder.getAudioBuffer();
972
- let audioBuffer;
973
- if (firstFrame === 0 && saveEndMs >= toShow.duration) {
974
- audioBuffer = fullAudioBuffer;
975
- }
976
- else {
977
- const sr = fullAudioBuffer.sampleRate;
978
- const s0 = Math.round((audioStartMs / 1000) * sr);
979
- const s1 = Math.min(Math.round((saveEndMs / 1000) * sr), fullAudioBuffer.length);
980
- const len = Math.max(0, s1 - s0);
981
- audioBuffer = new AudioBuffer({
982
- numberOfChannels: fullAudioBuffer.numberOfChannels,
983
- length: len,
984
- sampleRate: sr,
985
- });
986
- for (let ch = 0; ch < fullAudioBuffer.numberOfChannels; ch++) {
987
- audioBuffer.copyToChannel(fullAudioBuffer.getChannelData(ch).subarray(s0, s0 + len), ch);
988
- }
989
- }
1115
+ // The newest soundtrack, with every file in it decoded. Right after a reload or an
1116
+ // edit, that can take a moment. (After the file picker, which needs the click.)
1117
+ infoDiv.innerHTML = "Waiting for the sound…";
1118
+ await soundtrack.ready();
1119
+ const audioBuffer = soundtrack
1120
+ .mix(audioStartMs, Math.min(saveEndMs, toShow.duration))
1121
+ .getAudioBuffer();
990
1122
  const audioSource = new AudioBufferSource({
991
1123
  codec: "aac",
992
1124
  bitrate: QUALITY_HIGH,
@@ -1416,7 +1548,7 @@ const visualEditorAPI = {
1416
1548
  if (!selectable)
1417
1549
  return;
1418
1550
  if (howMuch === "sound") {
1419
- void initAudio();
1551
+ soundtrack.request();
1420
1552
  }
1421
1553
  else if (howMuch === "properties") {
1422
1554
  updateScheduleEditor(selectedSlideChild ?? selectable);
@@ -1438,12 +1570,15 @@ const visualEditorAPI = {
1438
1570
  return playheadInRootMs();
1439
1571
  },
1440
1572
  getDecodedBuffer(url) {
1441
- return audioBuilder.getDecodedBuffer(url);
1573
+ return soundtrack.getDecodedBuffer(url);
1442
1574
  },
1443
1575
  };
1444
1576
  // MARK: Console API
1445
1577
  philDebug.chapterList = chapterList;
1446
- philDebug.refreshSounds = () => void initAudio();
1578
+ /** Read and decode every sound file again, e.g. one re-recorded under the same name. */
1579
+ philDebug.refreshSounds = () => soundtrack.forget();
1580
+ /** The live soundtrack. See dev/soundtrack.ts. */
1581
+ philDebug.soundtrack = soundtrack;
1447
1582
  /**
1448
1583
  * Transcribe one file from scratch, skipping the cache, and report how long
1449
1584
  * it took. `device` is "webgpu" or "wasm"; leave it out for the normal choice.
@@ -1584,13 +1719,12 @@ const scheduleEditorRefreshers = [];
1584
1719
  const schedulesShowingDurations = new WeakSet();
1585
1720
  /** The selectable whose `.parent` is currently set to {@link veRootParent}. */
1586
1721
  let _veRootSelectable;
1587
- let _durationAudioTimer;
1588
1722
  /**
1589
1723
  * Synthetic {@link ShowableParent} that acts as the root of the editable tree.
1590
1724
  * When a selectable's `scheduleHasChanged()` chain reaches this object we:
1591
1725
  * - refresh all visible duration inputs,
1592
1726
  * - kick the auto-save / dirty-status machinery, and
1593
- * - debounce an audio reload.
1727
+ * - ask for a new soundtrack (which does nothing if no sound clip moved).
1594
1728
  */
1595
1729
  const veRootParent = {
1596
1730
  scheduleHasChanged() {
@@ -1599,8 +1733,7 @@ const veRootParent = {
1599
1733
  for (const cb of scheduleEditorRefreshers)
1600
1734
  cb();
1601
1735
  markDirty();
1602
- clearTimeout(_durationAudioTimer);
1603
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
1736
+ soundtrack.request();
1604
1737
  // Redraw the timeline so block positions/sizes update during drags.
1605
1738
  refreshTimeline();
1606
1739
  scheduleChapterRefresh();
@@ -1623,8 +1756,7 @@ const toShowParent = {
1623
1756
  for (const cb of scheduleEditorRefreshers)
1624
1757
  cb();
1625
1758
  markDirty();
1626
- clearTimeout(_durationAudioTimer);
1627
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
1759
+ soundtrack.request();
1628
1760
  refreshTimeline();
1629
1761
  scheduleChapterRefresh();
1630
1762
  },
@@ -1832,8 +1964,7 @@ transcriptView = new TranscriptView({
1832
1964
  clips.splice(index, 1, ...pieces);
1833
1965
  selectedSoundClip = pieces[0];
1834
1966
  markDirty();
1835
- clearTimeout(_durationAudioTimer);
1836
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
1967
+ soundtrack.request();
1837
1968
  // Show the owner's Sound Clips, with the remaining piece highlighted.
1838
1969
  selectInChapter(owner);
1839
1970
  refreshTimeline();
@@ -1904,12 +2035,11 @@ timelineDisplay.onBlockClick = (id) => {
1904
2035
  // MARK: Timeline blocks
1905
2036
  /**
1906
2037
  * A sound clip's numbers changed, from a field or a drag on the timeline.
1907
- * Save, rebuild the audio soon, and bring the fields and the timeline up to date.
2038
+ * Save, update the soundtrack, and bring the fields and the timeline up to date.
1908
2039
  */
1909
2040
  function _onClipValueChanged() {
1910
2041
  markDirty();
1911
- clearTimeout(_durationAudioTimer);
1912
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2042
+ soundtrack.request();
1913
2043
  for (const cb of soundClipSyncCallbacks)
1914
2044
  cb();
1915
2045
  timelineDisplay.redraw();
@@ -1919,7 +2049,7 @@ function _onClipValueChanged() {
1919
2049
  const MIN_SOUND_CLIP_MS = 50;
1920
2050
  /** How long the file `clip` plays from is, once it has been decoded. */
1921
2051
  function soundFileMs(clip) {
1922
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2052
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
1923
2053
  return buffer ? buffer.duration * 1000 : undefined;
1924
2054
  }
1925
2055
  /**
@@ -2017,7 +2147,7 @@ function soundClipBlock(clip, ownerStart) {
2017
2147
  startMs: start,
2018
2148
  durationMs: () => soundClipLengthMs(clip) ?? 0,
2019
2149
  waveform: () => {
2020
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2150
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
2021
2151
  return buffer ? { buffer, fromMs: clip.startMsIntoClip ?? 0 } : undefined;
2022
2152
  },
2023
2153
  onDragBody: (newStartMs) => {
@@ -2157,6 +2287,23 @@ function _buildTimelineBlocks(selectable) {
2157
2287
  blocks.push(soundClipBlock(clip, startMs));
2158
2288
  }
2159
2289
  }
2290
+ // The voice clip being recorded, growing as you talk.
2291
+ const live = liveVoiceClip;
2292
+ const liveOwnerStart = live && startWithin(selectable, live.owner);
2293
+ if (live && liveOwnerStart !== undefined) {
2294
+ blocks.push({
2295
+ id: live,
2296
+ label: "● Recording",
2297
+ color: "#c62828",
2298
+ lane: "sound",
2299
+ startMs: () => liveOwnerStart + live.startInOwnerMs,
2300
+ durationMs: () => voicePanel?.recorder.liveClip()?.lengthMs ?? 0,
2301
+ waveform: () => {
2302
+ const clip = voicePanel?.recorder.liveClip();
2303
+ return clip && { buffer: clip.buffer, fromMs: clip.trimMs };
2304
+ },
2305
+ });
2306
+ }
2160
2307
  return blocks;
2161
2308
  }
2162
2309
  /**
@@ -2984,6 +3131,17 @@ async function initFromDB(unloadBackup) {
2984
3131
  updateComponentEditor(currentSel);
2985
3132
  updateScheduleEditor(currentSel);
2986
3133
  }
3134
+ afterStateApplied();
3135
+ }
3136
+ /**
3137
+ * A saved state was just applied to the tree: restored at startup, opened,
3138
+ * or picked in the history. The sound clips in it are new objects, maybe in
3139
+ * new lists, so the timeline's blocks and the soundtrack are out of date.
3140
+ * The editors are rebuilt separately.
3141
+ */
3142
+ function afterStateApplied() {
3143
+ refreshTimeline();
3144
+ soundtrack.request();
2987
3145
  }
2988
3146
  /** Saves current schedule state to IndexedDB as a full data entry.
2989
3147
  * Pass force=true (💾 Save button) to bypass the ts-defaults-no-auto-save guard. */
@@ -3145,6 +3303,7 @@ function _dialogSelectItem(index, target) {
3145
3303
  activeRootComponentEditor?.resetAll();
3146
3304
  updateComponentEditor(target);
3147
3305
  updateScheduleEditor(target);
3306
+ afterStateApplied();
3148
3307
  // The Abandon/Save buttons are no longer used; only Keep is shown.
3149
3308
  historyOkBtn.hidden = false;
3150
3309
  historyAbandonBtn.hidden = true;
@@ -3372,6 +3531,7 @@ async function _applyDialogSelection() {
3372
3531
  activeRootComponentEditor?.resetAll();
3373
3532
  updateComponentEditor(target);
3374
3533
  updateScheduleEditor(target);
3534
+ afterStateApplied();
3375
3535
  }
3376
3536
  historyOkBtn.addEventListener("click", () => {
3377
3537
  void _applyDialogSelection();
@@ -3396,6 +3556,7 @@ historyCancelBtn.addEventListener("click", () => {
3396
3556
  activeRootComponentEditor?.resetAll();
3397
3557
  updateComponentEditor(target);
3398
3558
  updateScheduleEditor(target);
3559
+ afterStateApplied();
3399
3560
  }
3400
3561
  historyDialog.close();
3401
3562
  });
@@ -4672,28 +4833,32 @@ function updateComponentEditor(selectable) {
4672
4833
  list.scrollTop = wasAtBottom ? list.scrollHeight : savedScrollTop;
4673
4834
  }
4674
4835
  /**
4675
- * The Sound Clips section of the schedule editor, for a component whose
4676
- * `soundClips` is defined. One card per clip, plus Add and Paste.
4836
+ * The Sound Clips section of the schedule editor. One card per clip, plus Add and Paste.
4837
+ *
4838
+ * Every component gets one. A component with no `soundClips` list gets one
4839
+ * when its first clip is added.
4677
4840
  *
4678
4841
  * Each card's Owner menu moves the clip to another component without changing
4679
4842
  * when it plays. Registers per-field sync callbacks into
4680
4843
  * {@link soundClipSyncCallbacks}, so drags on the timeline show up here.
4681
4844
  */
4682
4845
  function buildSoundClipSection(selectable) {
4683
- const clips = selectable.soundClips;
4846
+ const clips = selectable.soundClips ?? [];
4847
+ /** Call before adding a clip. Merely selecting a component doesn't give it a list. */
4848
+ const ensureList = () => (selectable.soundClips ??= clips);
4684
4849
  /** The clip list changed shape: save, rebuild the audio, redraw this section and the timeline. */
4685
4850
  function afterStructureChange() {
4686
4851
  markDirty();
4687
- clearTimeout(_durationAudioTimer);
4688
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
4852
+ soundtrack.request();
4689
4853
  updateScheduleEditor(selectable);
4690
4854
  refreshTimeline();
4691
4855
  }
4692
- /** Every place a sound can live in this video, and when each starts. */
4856
+ /** Every place a sound lives in this video, and when each starts. */
4693
4857
  const owners = soundOwners(toShow);
4858
+ /** Undefined until this component has a list. Then it has cards, with Owner menus that need it. */
4694
4859
  const self = owners.find(({ owner }) => owner === selectable);
4695
4860
  /** When this component starts, in video time. 0 if it can't be found, which shouldn't happen. */
4696
- const selfStartMs = self?.startMs ?? 0;
4861
+ const selfStartMs = startWithin(toShow, selectable) ?? 0;
4697
4862
  const section = document.createElement("fieldset");
4698
4863
  const legend = document.createElement("legend");
4699
4864
  legend.textContent = `Sound Clips (${clips.length})`;
@@ -4710,6 +4875,7 @@ function buildSoundClipSection(selectable) {
4710
4875
  addBtn.style.marginLeft = "auto";
4711
4876
  addBtn.addEventListener("click", () => {
4712
4877
  const clip = { source: "", startMsIntoScene: playheadInOwner() };
4878
+ ensureList();
4713
4879
  clips.push(clip);
4714
4880
  selectedSoundClip = clip;
4715
4881
  afterStructureChange();
@@ -4734,6 +4900,7 @@ function buildSoundClipSection(selectable) {
4734
4900
  alert("No sound clips found on the clipboard. Each one needs at least a source.");
4735
4901
  return;
4736
4902
  }
4903
+ ensureList();
4737
4904
  clips.push(...pasted);
4738
4905
  selectedSoundClip = pasted[0];
4739
4906
  afterStructureChange();
@@ -4971,8 +5138,7 @@ function buildSoundClipSection(selectable) {
4971
5138
  rehomeSoundClip(clip, self, to);
4972
5139
  selectedSoundClip = clip;
4973
5140
  markDirty();
4974
- clearTimeout(_durationAudioTimer);
4975
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
5141
+ soundtrack.request();
4976
5142
  const chapter = currentRoot();
4977
5143
  if (chapter && startWithin(chapter, to.owner) !== undefined) {
4978
5144
  // Follow the clip to its new owner.
@@ -5082,14 +5248,7 @@ function updateScheduleEditor(selectable) {
5082
5248
  const slideComponent = selectable instanceof SlideComponent ? selectable : null;
5083
5249
  const videoClip = selectable instanceof VideoClipComponent ? selectable : null;
5084
5250
  const multiText = selectable instanceof MultiTextComponent ? selectable : null;
5085
- if (!scalars?.length &&
5086
- !schedules?.length &&
5087
- !isTraditionalText &&
5088
- !slideComponent &&
5089
- selectable.soundClips === undefined) {
5090
- scheduleEditorFieldset.hidden = true;
5091
- return;
5092
- }
5251
+ // Every component has something to edit: at least its name and its sound clips.
5093
5252
  scheduleEditorFieldset.hidden = false;
5094
5253
  scheduleEditorFieldset.append(buildNameSection(selectable));
5095
5254
  let customPanel = null;
@@ -5237,9 +5396,7 @@ function updateScheduleEditor(selectable) {
5237
5396
  }
5238
5397
  scheduleEditorFieldset.append(section);
5239
5398
  }
5240
- if (selectable.soundClips !== undefined) {
5241
- scheduleEditorFieldset.append(buildSoundClipSection(selectable));
5242
- }
5399
+ scheduleEditorFieldset.append(buildSoundClipSection(selectable));
5243
5400
  }
5244
5401
  // MARK: Split
5245
5402
  /**
@@ -6508,13 +6665,18 @@ document.addEventListener("keyup", (e) => {
6508
6665
  }
6509
6666
  });
6510
6667
  getById("recordJustSound", HTMLButtonElement).addEventListener("click", async () => {
6511
- const blob = await audioBuilder.toBlob();
6512
- downloadBlob("sound_file.wav", blob);
6668
+ // The newest soundtrack, with every file in it decoded.
6669
+ const before = infoDiv.innerHTML;
6670
+ infoDiv.innerHTML = "Waiting for the sound…";
6671
+ await soundtrack.ready();
6672
+ infoDiv.innerHTML = before;
6673
+ downloadBlob("sound_file.wav", soundtrack.mix(0, toShow.duration).toBlob());
6513
6674
  });
6514
6675
  function reload() {
6515
6676
  initChapters();
6516
6677
  updateFromSelect();
6517
- initAudio();
6678
+ // Reload means everything, including sound files changed on disk.
6679
+ soundtrack.forget();
6518
6680
  }
6519
6681
  getById("reloadBtn", HTMLButtonElement).addEventListener("click", reload);
6520
6682
  // MARK: Debug Log
@@ -6659,6 +6821,7 @@ function refreshEditorsAfterLoad() {
6659
6821
  activeRootComponentEditor?.resetAll();
6660
6822
  updateComponentEditor(current);
6661
6823
  updateScheduleEditor(current);
6824
+ afterStateApplied();
6662
6825
  // The loaded state may use local files that need 🔓.
6663
6826
  checkVideosLocalFiles();
6664
6827
  }
@@ -6824,11 +6987,28 @@ if (import.meta.hot) {
6824
6987
  // Changing a typescript file invokes this.
6825
6988
  // Changing a css file would cause vite:beforeUpdate, instead.
6826
6989
  import.meta.hot.on("vite:beforeFullReload", (_data) => {
6990
+ finishVoiceOnUnload();
6827
6991
  saveState();
6828
6992
  saveOnUnload();
6829
6993
  });
6830
6994
  }
6831
- window.addEventListener("beforeunload", saveOnUnload);
6995
+ /**
6996
+ * Start closing any voice recording's files. They may not finish in time.
6997
+ *
6998
+ * Only when the page is really going away. Not on visibilitychange: a page is hidden by
6999
+ * another tab, another app or another desktop, often to read a script, and the recording
7000
+ * should keep going.
7001
+ *
7002
+ * TODO: test this, and add the clip being recorded before {@link saveOnUnload}'s backup.
7003
+ * See "Risks" in development-plans/voice-recording.md.
7004
+ */
7005
+ function finishVoiceOnUnload() {
7006
+ voicePanel?.recorder.flush();
7007
+ }
7008
+ window.addEventListener("beforeunload", () => {
7009
+ finishVoiceOnUnload();
7010
+ saveOnUnload();
7011
+ });
6832
7012
  document.addEventListener("visibilitychange", () => {
6833
7013
  if (document.visibilityState === "hidden")
6834
7014
  saveOnUnload();