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