canvas-recorder-lib 0.5.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 (347) hide show
  1. package/BREAKING-CHANGES.md +24 -0
  2. package/README.md +131 -25
  3. package/dev/audio-builder.ts +69 -161
  4. package/dev/canvas-recorder.css +59 -0
  5. package/dev/canvas-recorder.ts +1006 -212
  6. package/dev/delay-files.ts +1 -1
  7. package/dev/font-utils.ts +8 -1
  8. package/dev/format-editor.ts +734 -0
  9. package/dev/format-string.ts +110 -0
  10. package/dev/local-file-row.ts +107 -0
  11. package/dev/multi-text-dialog.ts +360 -0
  12. package/dev/multi-text-panel.ts +11 -0
  13. package/dev/player-body.ts +94 -6
  14. package/dev/rect-snap.ts +9 -9
  15. package/dev/slide-panel.ts +1 -1
  16. package/dev/sound-clips.ts +3 -2
  17. package/dev/soundtrack.ts +434 -0
  18. package/dev/split-dialog.ts +13 -2
  19. package/dev/static-image-panel.ts +35 -5
  20. package/dev/timeline-display.ts +50 -5
  21. package/dev/transcripts.ts +5 -3
  22. package/dev/video-clip-panel.ts +202 -16
  23. package/dev/voice/chirp.ts +129 -0
  24. package/dev/voice/folder.ts +84 -0
  25. package/dev/voice/voice-panel.ts +513 -0
  26. package/dev/voice/voice-recorder.ts +603 -0
  27. package/dist/dev/audio-builder.d.ts +14 -31
  28. package/dist/dev/audio-builder.d.ts.map +1 -1
  29. package/dist/dev/audio-builder.js +62 -134
  30. package/dist/dev/audio-builder.js.map +1 -1
  31. package/dist/dev/canvas-recorder.css +59 -0
  32. package/dist/dev/canvas-recorder.js +926 -198
  33. package/dist/dev/canvas-recorder.js.map +1 -1
  34. package/dist/dev/delay-files.js +1 -1
  35. package/dist/dev/delay-files.js.map +1 -1
  36. package/dist/dev/font-utils.d.ts.map +1 -1
  37. package/dist/dev/font-utils.js +9 -1
  38. package/dist/dev/font-utils.js.map +1 -1
  39. package/dist/dev/format-editor.d.ts +75 -0
  40. package/dist/dev/format-editor.d.ts.map +1 -0
  41. package/dist/dev/format-editor.js +642 -0
  42. package/dist/dev/format-editor.js.map +1 -0
  43. package/dist/dev/format-string.d.ts +62 -0
  44. package/dist/dev/format-string.d.ts.map +1 -0
  45. package/dist/dev/format-string.js +86 -0
  46. package/dist/dev/format-string.js.map +1 -0
  47. package/dist/dev/local-file-row.d.ts +22 -0
  48. package/dist/dev/local-file-row.d.ts.map +1 -0
  49. package/dist/dev/local-file-row.js +84 -0
  50. package/dist/dev/local-file-row.js.map +1 -0
  51. package/dist/dev/multi-text-dialog.d.ts +30 -0
  52. package/dist/dev/multi-text-dialog.d.ts.map +1 -0
  53. package/dist/dev/multi-text-dialog.js +297 -0
  54. package/dist/dev/multi-text-dialog.js.map +1 -0
  55. package/dist/dev/multi-text-panel.d.ts +2 -0
  56. package/dist/dev/multi-text-panel.d.ts.map +1 -1
  57. package/dist/dev/multi-text-panel.js +4 -0
  58. package/dist/dev/multi-text-panel.js.map +1 -1
  59. package/dist/dev/player-body.d.ts +1 -1
  60. package/dist/dev/player-body.d.ts.map +1 -1
  61. package/dist/dev/player-body.js +94 -6
  62. package/dist/dev/player-body.js.map +1 -1
  63. package/dist/dev/rect-snap.d.ts +1 -1
  64. package/dist/dev/rect-snap.js +7 -7
  65. package/dist/dev/rect-snap.js.map +1 -1
  66. package/dist/dev/slide-panel.d.ts +1 -1
  67. package/dist/dev/slide-panel.d.ts.map +1 -1
  68. package/dist/dev/slide-panel.js +1 -1
  69. package/dist/dev/slide-panel.js.map +1 -1
  70. package/dist/dev/sound-clips.d.ts +3 -2
  71. package/dist/dev/sound-clips.d.ts.map +1 -1
  72. package/dist/dev/sound-clips.js +3 -2
  73. package/dist/dev/sound-clips.js.map +1 -1
  74. package/dist/dev/soundtrack.d.ts +115 -0
  75. package/dist/dev/soundtrack.d.ts.map +1 -0
  76. package/dist/dev/soundtrack.js +369 -0
  77. package/dist/dev/soundtrack.js.map +1 -0
  78. package/dist/dev/split-dialog.d.ts.map +1 -1
  79. package/dist/dev/split-dialog.js +14 -2
  80. package/dist/dev/split-dialog.js.map +1 -1
  81. package/dist/dev/static-image-panel.d.ts +2 -0
  82. package/dist/dev/static-image-panel.d.ts.map +1 -1
  83. package/dist/dev/static-image-panel.js +29 -5
  84. package/dist/dev/static-image-panel.js.map +1 -1
  85. package/dist/dev/timeline-display.d.ts +23 -2
  86. package/dist/dev/timeline-display.d.ts.map +1 -1
  87. package/dist/dev/timeline-display.js +47 -5
  88. package/dist/dev/timeline-display.js.map +1 -1
  89. package/dist/dev/transcripts.d.ts.map +1 -1
  90. package/dist/dev/transcripts.js +5 -3
  91. package/dist/dev/transcripts.js.map +1 -1
  92. package/dist/dev/video-clip-panel.d.ts +8 -0
  93. package/dist/dev/video-clip-panel.d.ts.map +1 -1
  94. package/dist/dev/video-clip-panel.js +176 -10
  95. package/dist/dev/video-clip-panel.js.map +1 -1
  96. package/dist/dev/voice/chirp.d.ts +27 -0
  97. package/dist/dev/voice/chirp.d.ts.map +1 -0
  98. package/dist/dev/voice/chirp.js +107 -0
  99. package/dist/dev/voice/chirp.js.map +1 -0
  100. package/dist/dev/voice/folder.d.ts +18 -0
  101. package/dist/dev/voice/folder.d.ts.map +1 -0
  102. package/dist/dev/voice/folder.js +68 -0
  103. package/dist/dev/voice/folder.js.map +1 -0
  104. package/dist/dev/voice/voice-panel.d.ts +44 -0
  105. package/dist/dev/voice/voice-panel.d.ts.map +1 -0
  106. package/dist/dev/voice/voice-panel.js +418 -0
  107. package/dist/dev/voice/voice-panel.js.map +1 -0
  108. package/dist/dev/voice/voice-recorder.d.ts +141 -0
  109. package/dist/dev/voice/voice-recorder.d.ts.map +1 -0
  110. package/dist/dev/voice/voice-recorder.js +506 -0
  111. package/dist/dev/voice/voice-recorder.js.map +1 -0
  112. package/dist/lib/index.d.ts +3 -0
  113. package/dist/lib/index.d.ts.map +1 -1
  114. package/dist/lib/index.js +3 -0
  115. package/dist/lib/index.js.map +1 -1
  116. package/dist/lib/main-control.d.ts +50 -4
  117. package/dist/lib/main-control.d.ts.map +1 -1
  118. package/dist/lib/main-control.js +94 -12
  119. package/dist/lib/main-control.js.map +1 -1
  120. package/dist/src/binary-search.js +1 -1
  121. package/dist/src/binary-search.js.map +1 -1
  122. package/dist/src/corner-rounder.d.ts +17 -0
  123. package/dist/src/corner-rounder.d.ts.map +1 -0
  124. package/dist/src/corner-rounder.js +89 -0
  125. package/dist/src/corner-rounder.js.map +1 -0
  126. package/dist/src/cross-fade.d.ts +1 -1
  127. package/dist/src/cross-fade.d.ts.map +1 -1
  128. package/dist/src/cross-fade.js +3 -3
  129. package/dist/src/cross-fade.js.map +1 -1
  130. package/dist/src/fancy-text.d.ts +116 -0
  131. package/dist/src/fancy-text.d.ts.map +1 -0
  132. package/dist/src/fancy-text.js +211 -0
  133. package/dist/src/fancy-text.js.map +1 -0
  134. package/dist/src/glib/letters-base.d.ts +1 -1
  135. package/dist/src/glib/letters-base.d.ts.map +1 -1
  136. package/dist/src/glib/letters-base.js +4 -3
  137. package/dist/src/glib/letters-base.js.map +1 -1
  138. package/dist/src/glib/line-font.d.ts +2 -2
  139. package/dist/src/glib/line-font.d.ts.map +1 -1
  140. package/dist/src/glib/line-font.js +2 -2
  141. package/dist/src/glib/line-font.js.map +1 -1
  142. package/dist/src/glib/paragraph-layout.d.ts +2 -2
  143. package/dist/src/glib/paragraph-layout.d.ts.map +1 -1
  144. package/dist/src/glib/paragraph-layout.js +1 -1
  145. package/dist/src/glib/paragraph-layout.js.map +1 -1
  146. package/dist/src/glib/path-shape-splitter.d.ts +1 -1
  147. package/dist/src/glib/path-shape-splitter.d.ts.map +1 -1
  148. package/dist/src/glib/path-shape-splitter.js +1 -1
  149. package/dist/src/glib/path-shape-splitter.js.map +1 -1
  150. package/dist/src/glib/path-shape.js +2 -2
  151. package/dist/src/glib/path-shape.js.map +1 -1
  152. package/dist/src/interpolate.d.ts +2 -2
  153. package/dist/src/interpolate.d.ts.map +1 -1
  154. package/dist/src/interpolate.js +1 -1
  155. package/dist/src/interpolate.js.map +1 -1
  156. package/dist/src/lattice.d.ts +1 -1
  157. package/dist/src/lattice.d.ts.map +1 -1
  158. package/dist/src/local-files.d.ts +129 -0
  159. package/dist/src/local-files.d.ts.map +1 -0
  160. package/dist/src/local-files.js +327 -0
  161. package/dist/src/local-files.js.map +1 -0
  162. package/dist/src/morph-animation.d.ts +1 -1
  163. package/dist/src/morph-animation.d.ts.map +1 -1
  164. package/dist/src/morph-animation.js +2 -2
  165. package/dist/src/morph-animation.js.map +1 -1
  166. package/dist/src/peano-fourier/fourier-shared.d.ts +1 -1
  167. package/dist/src/peano-fourier/fourier-shared.d.ts.map +1 -1
  168. package/dist/src/peano-fourier/fourier-shared.js +17 -4
  169. package/dist/src/peano-fourier/fourier-shared.js.map +1 -1
  170. package/dist/src/schedule-helper.d.ts +4 -4
  171. package/dist/src/schedule-helper.d.ts.map +1 -1
  172. package/dist/src/schedule-helper.js +2 -2
  173. package/dist/src/schedule-helper.js.map +1 -1
  174. package/dist/src/showable.d.ts +45 -4
  175. package/dist/src/showable.d.ts.map +1 -1
  176. package/dist/src/showable.js +37 -1
  177. package/dist/src/showable.js.map +1 -1
  178. package/dist/src/slide-components/arrow.d.ts +4 -4
  179. package/dist/src/slide-components/arrow.d.ts.map +1 -1
  180. package/dist/src/slide-components/arrow.js +2 -2
  181. package/dist/src/slide-components/arrow.js.map +1 -1
  182. package/dist/src/slide-components/cross-fade-transition.d.ts +3 -3
  183. package/dist/src/slide-components/cross-fade-transition.d.ts.map +1 -1
  184. package/dist/src/slide-components/cross-fade-transition.js +3 -3
  185. package/dist/src/slide-components/cross-fade-transition.js.map +1 -1
  186. package/dist/src/slide-components/duration-agnostic.d.ts +3 -3
  187. package/dist/src/slide-components/duration-agnostic.d.ts.map +1 -1
  188. package/dist/src/slide-components/duration-agnostic.js +1 -1
  189. package/dist/src/slide-components/duration-agnostic.js.map +1 -1
  190. package/dist/src/slide-components/fixed-duration.d.ts +1 -1
  191. package/dist/src/slide-components/fixed-duration.d.ts.map +1 -1
  192. package/dist/src/slide-components/fixed-duration.js +1 -1
  193. package/dist/src/slide-components/fixed-duration.js.map +1 -1
  194. package/dist/src/slide-components/fourier.d.ts +6 -6
  195. package/dist/src/slide-components/fourier.d.ts.map +1 -1
  196. package/dist/src/slide-components/fourier.js +6 -6
  197. package/dist/src/slide-components/fourier.js.map +1 -1
  198. package/dist/src/slide-components/frame-counter.d.ts +2 -2
  199. package/dist/src/slide-components/frame-counter.d.ts.map +1 -1
  200. package/dist/src/slide-components/frame-counter.js +1 -1
  201. package/dist/src/slide-components/frame-counter.js.map +1 -1
  202. package/dist/src/slide-components/function-graph.d.ts +2 -2
  203. package/dist/src/slide-components/function-graph.d.ts.map +1 -1
  204. package/dist/src/slide-components/function-graph.js +3 -3
  205. package/dist/src/slide-components/function-graph.js.map +1 -1
  206. package/dist/src/slide-components/halftone-shadow.d.ts +4 -4
  207. package/dist/src/slide-components/halftone-shadow.d.ts.map +1 -1
  208. package/dist/src/slide-components/halftone-shadow.js +2 -2
  209. package/dist/src/slide-components/halftone-shadow.js.map +1 -1
  210. package/dist/src/slide-components/handwriting-effect.d.ts +5 -5
  211. package/dist/src/slide-components/handwriting-effect.d.ts.map +1 -1
  212. package/dist/src/slide-components/handwriting-effect.js +5 -5
  213. package/dist/src/slide-components/handwriting-effect.js.map +1 -1
  214. package/dist/src/slide-components/hold.d.ts +3 -3
  215. package/dist/src/slide-components/hold.d.ts.map +1 -1
  216. package/dist/src/slide-components/hold.js +3 -3
  217. package/dist/src/slide-components/hold.js.map +1 -1
  218. package/dist/src/slide-components/image.d.ts +3 -3
  219. package/dist/src/slide-components/image.d.ts.map +1 -1
  220. package/dist/src/slide-components/image.js +3 -3
  221. package/dist/src/slide-components/image.js.map +1 -1
  222. package/dist/src/slide-components/in-parallel.d.ts +3 -3
  223. package/dist/src/slide-components/in-parallel.d.ts.map +1 -1
  224. package/dist/src/slide-components/in-parallel.js +2 -2
  225. package/dist/src/slide-components/in-parallel.js.map +1 -1
  226. package/dist/src/slide-components/in-series.d.ts +4 -4
  227. package/dist/src/slide-components/in-series.d.ts.map +1 -1
  228. package/dist/src/slide-components/in-series.js +5 -1
  229. package/dist/src/slide-components/in-series.js.map +1 -1
  230. package/dist/src/slide-components/live-duration.d.ts +1 -1
  231. package/dist/src/slide-components/live-duration.d.ts.map +1 -1
  232. package/dist/src/slide-components/live-duration.js +1 -1
  233. package/dist/src/slide-components/live-duration.js.map +1 -1
  234. package/dist/src/slide-components/multi-text.d.ts +76 -15
  235. package/dist/src/slide-components/multi-text.d.ts.map +1 -1
  236. package/dist/src/slide-components/multi-text.js +170 -25
  237. package/dist/src/slide-components/multi-text.js.map +1 -1
  238. package/dist/src/slide-components/rectangle.d.ts +3 -3
  239. package/dist/src/slide-components/rectangle.d.ts.map +1 -1
  240. package/dist/src/slide-components/rectangle.js +1 -1
  241. package/dist/src/slide-components/rectangle.js.map +1 -1
  242. package/dist/src/slide-components/registry.d.ts +1 -1
  243. package/dist/src/slide-components/registry.d.ts.map +1 -1
  244. package/dist/src/slide-components/registry.js +18 -18
  245. package/dist/src/slide-components/registry.js.map +1 -1
  246. package/dist/src/slide-components/serialize.d.ts +1 -1
  247. package/dist/src/slide-components/serialize.d.ts.map +1 -1
  248. package/dist/src/slide-components/serialize.js +2 -2
  249. package/dist/src/slide-components/serialize.js.map +1 -1
  250. package/dist/src/slide-components/show-error.js +2 -2
  251. package/dist/src/slide-components/show-error.js.map +1 -1
  252. package/dist/src/slide-components/simple-text.d.ts +4 -4
  253. package/dist/src/slide-components/simple-text.d.ts.map +1 -1
  254. package/dist/src/slide-components/simple-text.js +4 -4
  255. package/dist/src/slide-components/simple-text.js.map +1 -1
  256. package/dist/src/slide-components/slide-component.d.ts +5 -5
  257. package/dist/src/slide-components/slide-component.d.ts.map +1 -1
  258. package/dist/src/slide-components/slide-component.js +4 -4
  259. package/dist/src/slide-components/slide-component.js.map +1 -1
  260. package/dist/src/slide-components/slide-left.d.ts +3 -3
  261. package/dist/src/slide-components/slide-left.d.ts.map +1 -1
  262. package/dist/src/slide-components/slide-left.js +3 -3
  263. package/dist/src/slide-components/slide-left.js.map +1 -1
  264. package/dist/src/slide-components/split-video-clip.d.ts +2 -2
  265. package/dist/src/slide-components/split-video-clip.d.ts.map +1 -1
  266. package/dist/src/slide-components/split-video-clip.js +3 -3
  267. package/dist/src/slide-components/split-video-clip.js.map +1 -1
  268. package/dist/src/slide-components/text-effect.d.ts +2 -2
  269. package/dist/src/slide-components/text-effect.d.ts.map +1 -1
  270. package/dist/src/slide-components/traditional-text.d.ts +4 -4
  271. package/dist/src/slide-components/traditional-text.d.ts.map +1 -1
  272. package/dist/src/slide-components/traditional-text.js +3 -3
  273. package/dist/src/slide-components/traditional-text.js.map +1 -1
  274. package/dist/src/slide-components/video-clip.d.ts +17 -5
  275. package/dist/src/slide-components/video-clip.d.ts.map +1 -1
  276. package/dist/src/slide-components/video-clip.js +52 -11
  277. package/dist/src/slide-components/video-clip.js.map +1 -1
  278. package/dist/src/slide-components/video-info.d.ts +11 -11
  279. package/dist/src/slide-components/video-info.d.ts.map +1 -1
  280. package/dist/src/slide-components/video-info.js +32 -21
  281. package/dist/src/slide-components/video-info.js.map +1 -1
  282. package/dist/src/slow-image-sources.d.ts +7 -1
  283. package/dist/src/slow-image-sources.d.ts.map +1 -1
  284. package/dist/src/slow-image-sources.js +36 -5
  285. package/dist/src/slow-image-sources.js.map +1 -1
  286. package/dist/src/snapshot.d.ts +2 -2
  287. package/dist/src/snapshot.d.ts.map +1 -1
  288. package/dist/src/snapshot.js +31 -15
  289. package/dist/src/snapshot.js.map +1 -1
  290. package/dist/src/stroke-colors.d.ts +1 -1
  291. package/dist/src/stroke-colors.d.ts.map +1 -1
  292. package/dist/src/stroke-colors.js +4 -4
  293. package/dist/src/stroke-colors.js.map +1 -1
  294. package/dist/src/utility.d.ts +3 -4
  295. package/dist/src/utility.d.ts.map +1 -1
  296. package/dist/src/utility.js +4 -4
  297. package/dist/src/utility.js.map +1 -1
  298. package/lib/index.ts +3 -0
  299. package/lib/main-control.ts +119 -12
  300. package/package.json +7 -5
  301. package/src/binary-search.ts +2 -2
  302. package/src/corner-rounder.ts +128 -0
  303. package/src/cross-fade.ts +3 -3
  304. package/src/fancy-text.ts +255 -0
  305. package/src/glib/letters-base.ts +4 -3
  306. package/src/glib/line-font.ts +2 -2
  307. package/src/glib/paragraph-layout.ts +2 -2
  308. package/src/glib/path-shape-splitter.ts +1 -1
  309. package/src/glib/path-shape.ts +2 -2
  310. package/src/interpolate.ts +3 -3
  311. package/src/lattice.ts +1 -1
  312. package/src/local-files.ts +389 -0
  313. package/src/morph-animation.ts +2 -2
  314. package/src/peano-fourier/fourier-shared.ts +17 -4
  315. package/src/schedule-helper.ts +4 -4
  316. package/src/showable.ts +63 -4
  317. package/src/slide-components/arrow.ts +4 -4
  318. package/src/slide-components/cross-fade-transition.ts +4 -4
  319. package/src/slide-components/duration-agnostic.ts +3 -3
  320. package/src/slide-components/fixed-duration.ts +1 -1
  321. package/src/slide-components/fourier.ts +9 -9
  322. package/src/slide-components/frame-counter.ts +2 -2
  323. package/src/slide-components/function-graph.ts +4 -4
  324. package/src/slide-components/halftone-shadow.ts +4 -4
  325. package/src/slide-components/handwriting-effect.ts +7 -7
  326. package/src/slide-components/hold.ts +4 -4
  327. package/src/slide-components/image.ts +5 -5
  328. package/src/slide-components/in-parallel.ts +4 -4
  329. package/src/slide-components/in-series.ts +7 -4
  330. package/src/slide-components/live-duration.ts +1 -1
  331. package/src/slide-components/multi-text.ts +195 -30
  332. package/src/slide-components/rectangle.ts +3 -3
  333. package/src/slide-components/registry.ts +19 -19
  334. package/src/slide-components/serialize.ts +2 -2
  335. package/src/slide-components/show-error.ts +2 -2
  336. package/src/slide-components/simple-text.ts +7 -7
  337. package/src/slide-components/slide-component.ts +7 -7
  338. package/src/slide-components/slide-left.ts +4 -4
  339. package/src/slide-components/split-video-clip.ts +4 -4
  340. package/src/slide-components/text-effect.ts +2 -2
  341. package/src/slide-components/traditional-text.ts +5 -5
  342. package/src/slide-components/video-clip.ts +64 -13
  343. package/src/slide-components/video-info.ts +33 -21
  344. package/src/slow-image-sources.ts +38 -6
  345. package/src/snapshot.ts +34 -19
  346. package/src/stroke-colors.ts +4 -4
  347. package/src/utility.ts +5 -5
@@ -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 {
@@ -80,6 +82,7 @@ import {
80
82
  import { buildSlideComponentPanel } from "./slide-panel.ts";
81
83
  import { buildVideoClipPanel } from "./video-clip-panel.ts";
82
84
  import { buildTextFramePanel, CanvasState } from "./multi-text-panel.ts";
85
+ import { openMultiTextDialog } from "./multi-text-dialog.ts";
83
86
  import {
84
87
  ownerOf,
85
88
  parseSoundClips,
@@ -110,8 +113,15 @@ import {
110
113
  import { transcriptFileName, transcriptJson } from "./transcript-export.ts";
111
114
  import { wordFlag } from "./transcript-align.ts";
112
115
  import type { Device } from "./transcribe-core.ts";
113
- import { canvasRecorder } from "../lib/main-control.ts";
116
+ import { canvasRecorder, type VideoSize } from "../lib/main-control.ts";
114
117
  import { watchServiceWorkerReady } from "./delay-files.ts";
118
+ import {
119
+ checkLocalFiles,
120
+ localFilesNeedingPermission,
121
+ localFileUrlsIn,
122
+ onLocalFilesChange,
123
+ requestLocalFileAccess,
124
+ } from "../src/local-files.ts";
115
125
  import { DurationAgnosticComponent } from "../src/slide-components/duration-agnostic.ts";
116
126
  import {
117
127
  componentChoices,
@@ -317,6 +327,166 @@ viewport.addEventListener(
317
327
  { passive: false },
318
328
  );
319
329
 
330
+ // MARK: Video size
331
+
332
+ /**
333
+ * The four size fields: the saved file's pixels, and the drawing units.
334
+ * See development-plans/configurable-video-size.md.
335
+ */
336
+ const videoSizeInputs = {
337
+ pixelWidth: getById("videoPixelWidth", HTMLInputElement),
338
+ pixelHeight: getById("videoPixelHeight", HTMLInputElement),
339
+ width: getById("videoUnitWidth", HTMLInputElement),
340
+ height: getById("videoUnitHeight", HTMLInputElement),
341
+ } satisfies Record<keyof VideoSize, HTMLInputElement>;
342
+ const videoSizeWarning = getById("videoSizeWarning", HTMLSpanElement);
343
+
344
+ /**
345
+ * Where the user's size is remembered. One entry per video, shared by every window
346
+ * and session on this origin. localStorage, not IndexedDB: it's synchronous, so a
347
+ * saved size is in place before the first frame, and its `storage` event tells the
348
+ * other windows about a change for free.
349
+ */
350
+ const videoSizeStorageKey = `canvas-recorder-size|${startRequest.name}`;
351
+
352
+ /** The size this video's user saved, if any. */
353
+ function readSavedVideoSize(): VideoSize | undefined {
354
+ try {
355
+ const parsed: unknown = JSON.parse(
356
+ localStorage.getItem(videoSizeStorageKey) ?? "null",
357
+ );
358
+ if (typeof parsed !== "object" || parsed === null) return undefined;
359
+ const record = parsed as Record<string, unknown>;
360
+ const size = {
361
+ pixelWidth: record.pixelWidth,
362
+ pixelHeight: record.pixelHeight,
363
+ width: record.width,
364
+ height: record.height,
365
+ };
366
+ const valid = Object.values(size).every(
367
+ (value) => typeof value === "number" && Number.isFinite(value) && value > 0,
368
+ );
369
+ return valid ? (size as VideoSize) : undefined;
370
+ } catch {
371
+ return undefined;
372
+ }
373
+ }
374
+
375
+ /** Use the saved size, unless the program locked it. A bad saved size is ignored. */
376
+ function applySavedVideoSize() {
377
+ if (canvasRecorder.sizeLocked) return;
378
+ const saved = readSavedVideoSize();
379
+ if (!saved) return;
380
+ try {
381
+ canvasRecorder.size = saved;
382
+ } catch (error) {
383
+ console.warn("Ignoring the saved video size.", saved, error);
384
+ }
385
+ }
386
+ applySavedVideoSize();
387
+
388
+ /** Copy the size into the fields, except one the user is typing in. */
389
+ function showVideoSize(size: VideoSize) {
390
+ for (const [key, input] of Object.entries(videoSizeInputs)) {
391
+ input.readOnly = canvasRecorder.sizeLocked;
392
+ if (document.activeElement !== input) {
393
+ input.value = String(size[key as keyof VideoSize]);
394
+ }
395
+ }
396
+ const pixelAspect = size.pixelWidth / size.pixelHeight;
397
+ const unitAspect = size.width / size.height;
398
+ const stretched = Math.abs(pixelAspect / unitAspect - 1) > 0.001;
399
+ videoSizeWarning.textContent = stretched ? "⚠ stretched" : "";
400
+ videoSizeWarning.title = stretched
401
+ ? `The pixels are ${pixelAspect.toFixed(3)} : 1 and the units are ${unitAspect.toFixed(3)} : 1, so the picture is stretched to fit.`
402
+ : "";
403
+ getById("videoSizeControls", HTMLSpanElement).title = canvasRecorder.sizeLocked
404
+ ? "The size of the video. This program sets it, so it can't be changed here."
405
+ : "The size of the video. Pixels: the saved file. Units: the coordinates everything is drawn in. Remembered for this video.";
406
+ }
407
+ showVideoSize(canvasRecorder.size);
408
+
409
+ /**
410
+ * The user asked for this size, in the size fields or with a button like the Video File
411
+ * panel's "Make video this size". Use it, and remember it for this video.
412
+ * @returns False if the size is locked, or `size` isn't usable. Nothing changes then.
413
+ */
414
+ function setVideoSizeFromGui(size: VideoSize): boolean {
415
+ if (canvasRecorder.sizeLocked) return false;
416
+ try {
417
+ canvasRecorder.size = size;
418
+ } catch {
419
+ // E.g. 0.4 pixels, which rounds to 0. Normal while typing.
420
+ return false;
421
+ }
422
+ try {
423
+ localStorage.setItem(videoSizeStorageKey, JSON.stringify(canvasRecorder.size));
424
+ } catch {
425
+ // Private browsing, or storage is full. The size still works until the page reloads.
426
+ }
427
+ return true;
428
+ }
429
+
430
+ for (const [key, input] of Object.entries(videoSizeInputs)) {
431
+ input.addEventListener("input", () => {
432
+ const value = input.valueAsNumber;
433
+ // Empty, 0 or negative is normal while typing. Wait for a usable number.
434
+ if (!(Number.isFinite(value) && value > 0)) return;
435
+ setVideoSizeFromGui({ ...canvasRecorder.size, [key]: value });
436
+ });
437
+ // Show the value as stored, e.g. rounded to whole pixels, once the user is done typing.
438
+ input.addEventListener("blur", () => showVideoSize(canvasRecorder.size));
439
+ }
440
+
441
+ canvasRecorder.onSizeChange((size) => {
442
+ showVideoSize(size);
443
+ if (isRecording) return;
444
+ if (zoomSelect.value === "fit") {
445
+ zoomToFit();
446
+ } else {
447
+ applyZoom(currentZoomFactor);
448
+ }
449
+ });
450
+
451
+ // Another window changed this video's size.
452
+ addEventListener("storage", (event) => {
453
+ if (event.key === videoSizeStorageKey) applySavedVideoSize();
454
+ });
455
+
456
+ // MARK: Local files
457
+
458
+ /**
459
+ * 🔓: shown when some of the video's files are on this computer, and the browser
460
+ * needs a click before it will read them. See src/local-files.ts.
461
+ */
462
+ const localFilesBtn = getById("localFilesBtn", HTMLButtonElement);
463
+
464
+ function updateLocalFilesButton() {
465
+ const names = localFilesNeedingPermission();
466
+ localFilesBtn.hidden = names.length === 0;
467
+ localFilesBtn.textContent =
468
+ names.length === 1 ? "🔓 Allow local file" : `🔓 Allow ${names.length} local files`;
469
+ localFilesBtn.title =
470
+ "The browser needs your OK before it reads these files again:\n" + names.join("\n");
471
+ }
472
+ onLocalFilesChange(updateLocalFilesButton);
473
+
474
+ /** Ask about every file that needs it. Then the sounds can load. */
475
+ async function allowLocalFiles() {
476
+ await requestLocalFileAccess();
477
+ // The images and video clips try again by themselves.
478
+ soundtrack.forgetFailures();
479
+ }
480
+ localFilesBtn.addEventListener("click", () => void allowLocalFiles());
481
+
482
+ /**
483
+ * Find out, without asking the user anything, whether the video's local files can be read.
484
+ * Any that can't put the 🔓 button on screen.
485
+ */
486
+ function checkVideosLocalFiles() {
487
+ void checkLocalFiles(localFileUrlsIn(toShow));
488
+ }
489
+
320
490
  /**
321
491
  * @param timeInMs Draw the animation at this time.
322
492
  * @param live True for interactive display (schedule markers drawn on top).
@@ -484,17 +654,48 @@ function loadPlayPositionRange() {
484
654
  playPositionRange.valueAsNumber = playPositionSeconds.valueAsNumber * 1000;
485
655
  }
486
656
 
487
- 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 });
488
659
  console.log(audioContext);
489
660
  const gainNode = audioContext.createGain();
490
661
  gainNode.connect(audioContext.destination);
491
662
 
492
- /** Set to true once the AudioBuffer has been fully built and is safe to play. */
493
- let audioReady = false;
494
- let audioSourceNode: AudioBufferSourceNode | null = null;
495
- /** 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. */
496
697
  let audioContextStartTime = 0;
497
- /** Media position (ms) at the moment startAudio() last started a source node. */
698
+ /** Media position (ms) at the moment startAudio() last anchored the clock. */
498
699
  let audioMediaStartMs = 0;
499
700
  let audioPlaybackRate = 1;
500
701
 
@@ -507,7 +708,7 @@ let audioPlaybackRate = 1;
507
708
  * https://developer.mozilla.org/en-US/docs/Web/API/Window/requestAnimationFrame
508
709
  */
509
710
  let rafFallbackMode = false;
510
- /** True when fallback-mode "playback" is running (mirrors audioSourceNode !== null). */
711
+ /** True when fallback-mode "playback" is running (mirrors {@link audioPlaying}). */
511
712
  let rafFallbackPlaying = false;
512
713
  /** performance.now() at the moment fallback playback last started. */
513
714
  let rafFallbackStartPerf = 0;
@@ -551,7 +752,6 @@ function startAudio(fromMs: number): void {
551
752
  rafFallbackPlaying = true;
552
753
  return;
553
754
  }
554
- if (!audioReady) return;
555
755
  if (audioContext.state !== "running") {
556
756
  if (!navigator.userActivation.isActive) {
557
757
  // No user gesture available (e.g. restoring play state on page load).
@@ -559,30 +759,35 @@ function startAudio(fromMs: number): void {
559
759
  enterRafFallback(fromMs, false);
560
760
  return;
561
761
  }
562
- // 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
563
763
  // once the context transitions to running. Do NOT check state synchronously
564
764
  // after this call; it will still read "suspended" before the promise resolves.
565
765
  audioContext.resume().catch(() => {});
566
766
  }
567
- const source = audioContext.createBufferSource();
568
- source.buffer = audioBuilder.getAudioBuffer();
569
- source.playbackRate.value = audioPlaybackRate;
570
- source.connect(gainNode);
571
767
  const contextNow = audioContext.currentTime;
572
- source.start(contextNow, fromMs / 1000);
573
- audioSourceNode = source;
574
768
  audioContextStartTime = contextNow;
575
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);
576
777
  }
577
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
+ */
578
785
  function stopAudio(): void {
579
786
  rafFallbackPlaying = false;
580
- if (audioSourceNode) {
581
- try {
582
- audioSourceNode.stop();
583
- } catch (_) {}
584
- audioSourceNode.disconnect();
585
- audioSourceNode = null;
787
+ if (audioPlaying) {
788
+ soundtrack.stop();
789
+ audioPlaying = false;
790
+ if (voiceRecording) endVoiceClip();
586
791
  }
587
792
  }
588
793
 
@@ -595,17 +800,29 @@ function setPlaybackRate(rate: number): void {
595
800
  const currentMs = currentAudioTimeMs();
596
801
  rafFallbackStartMs = currentMs;
597
802
  rafFallbackStartPerf = performance.now();
598
- } else if (audioSourceNode) {
803
+ } else if (audioPlaying) {
599
804
  const currentMs = currentAudioTimeMs();
600
805
  audioContextStartTime = audioContext.currentTime;
601
806
  audioMediaStartMs = currentMs;
602
- audioSourceNode.playbackRate.value = rate;
807
+ soundtrack.changeRate({
808
+ contextTime: audioContextStartTime,
809
+ mediaMs: audioMediaStartMs,
810
+ rate,
811
+ });
603
812
  }
604
813
  audioPlaybackRate = rate;
605
814
  }
606
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
+
607
825
  {
608
- const volumeSlider = getById("volumeAudio", HTMLInputElement);
609
826
  muteCheckbox.addEventListener("input", () => {
610
827
  if (!muteCheckbox.checked && rafFallbackMode) {
611
828
  // Un-muting is a user gesture — try to exit fallback and resume real audio.
@@ -618,75 +835,14 @@ function setPlaybackRate(rate: number): void {
618
835
  startAudio(currentMs);
619
836
  }
620
837
  }
621
- gainNode.gain.value = muteCheckbox.checked ? 0 : volumeSlider.valueAsNumber;
838
+ updateGain();
622
839
  });
623
- volumeSlider.addEventListener("input", () => {
624
- if (!muteCheckbox.checked) {
625
- gainNode.gain.value = volumeSlider.valueAsNumber;
626
- }
627
- });
628
- getById("speedAudio", HTMLSelectElement).addEventListener("change", (e) => {
629
- setPlaybackRate(parseFloat((e.target as HTMLSelectElement).value));
840
+ volumeSlider.addEventListener("input", updateGain);
841
+ speedSelect.addEventListener("change", () => {
842
+ setPlaybackRate(parseFloat(speedSelect.value));
630
843
  });
631
844
  }
632
845
 
633
- let audioBuilder = new AudioBuilder(toShow.duration);
634
-
635
- let reloadGeneration = 0;
636
-
637
- async function initAudio(): Promise<void> {
638
- const myGen = ++reloadGeneration;
639
- audioReady = false;
640
- stopAudio();
641
- const newBuilder = new AudioBuilder(toShow.duration);
642
-
643
- async function doIt(item: Showable, offset: number): Promise<boolean> {
644
- if (myGen !== reloadGeneration) return false;
645
- if (item.soundClips) {
646
- for (const clip of item.soundClips) {
647
- // A brand new clip has no source yet, and a URL being typed is wrong
648
- // until it's finished. Either way, skip that one clip, not all audio.
649
- if (clip.source === "") continue;
650
- try {
651
- await newBuilder.add(
652
- clip.source,
653
- offset + clip.startMsIntoScene,
654
- clip.startMsIntoClip,
655
- clip.lengthMs,
656
- );
657
- } catch (reason) {
658
- debugLog("audio", `Skipped "${clip.source}": ${reason}`);
659
- }
660
- if (myGen !== reloadGeneration) return false;
661
- }
662
- }
663
- if (item.children) {
664
- for (const { child, start } of item.children) {
665
- if (!(await doIt(child, offset + start))) return false;
666
- }
667
- }
668
- return true;
669
- }
670
-
671
- const time1 = performance.now();
672
- const completed = await doIt(toShow, 0);
673
- const time2 = performance.now();
674
- if (!completed) {
675
- console.log(
676
- `Audio init superseded after ${(time2 - time1).toFixed(0)} ms.`,
677
- );
678
- return;
679
- }
680
- audioBuilder = newBuilder;
681
- audioReady = true;
682
- console.log(`Audio ready in ${(time2 - time1).toFixed(0)} ms.`);
683
- // Sound clips on the timeline can now show their waveforms, and the ones
684
- // that play to the end of their file now know how long that is.
685
- timelineDisplay.redraw();
686
- }
687
-
688
- initAudio();
689
-
690
846
  /**
691
847
  * We disable {@link animationLoop} while rendering to a file.
692
848
  * We can reenable it when we are done rendering.
@@ -705,6 +861,8 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
705
861
  if (!playCheckBox.checked) {
706
862
  // Paused.
707
863
  stopAudio();
864
+ // Pausing is how a voice recording stops, once the video has started.
865
+ if (voiceRecording && !voiceChirping) stopVoiceRecording();
708
866
  playPositionSeconds.disabled = false;
709
867
  showFrame(playPositionSeconds.valueAsNumber * 1000, true);
710
868
  return;
@@ -713,8 +871,9 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
713
871
  // Playing.
714
872
  playPositionSeconds.disabled = true;
715
873
 
716
- if (!audioSourceNode && !rafFallbackPlaying) {
717
- // 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.
718
877
  let startMs = playPositionSeconds.valueAsNumber * 1000;
719
878
  if (startMs >= sectionEndTime - 0.05) {
720
879
  // At the end — jump to the beginning.
@@ -723,16 +882,24 @@ const animationLoop = new AnimationLoop((_rAFTimeInMs: number) => {
723
882
  loadPlayPositionRange();
724
883
  }
725
884
  startAudio(startMs);
726
- // If audio isn't built yet (and not in fallback mode), hold the current frame.
727
- if (!audioSourceNode && !rafFallbackPlaying) {
728
- showFrame(playPositionSeconds.valueAsNumber * 1000, true);
729
- return;
730
- }
731
885
  }
732
886
 
733
887
  const timeInMs = currentAudioTimeMs();
734
888
 
889
+ if (voiceRecording) {
890
+ voicePanel?.setPastEnd(
891
+ timeInMs > sectionEndTime ? timeInMs - sectionEndTime : undefined,
892
+ );
893
+ }
735
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
+ }
736
903
  // Repeating nothing would restart the audio on every frame.
737
904
  if (repeatRadioButton.checked && sectionEndTime > sectionStartTime) {
738
905
  // Loop: restart from the beginning of the section.
@@ -766,11 +933,15 @@ playPositionSeconds.addEventListener("input", () => {
766
933
  });
767
934
 
768
935
  // Cmd+Z / Ctrl+Z opens the history (undo) dialog when no text field is focused.
936
+ // A contenteditable, like the Multi Text editor, is a text field with its own undo,
937
+ // and an editor that handled the key itself has said so with preventDefault().
769
938
  addEventListener("keydown", (event) => {
770
939
  if (!(event.metaKey || event.ctrlKey) || event.key !== "z") return;
940
+ if (event.defaultPrevented) return;
771
941
  if (
772
942
  event.target instanceof HTMLInputElement ||
773
- event.target instanceof HTMLTextAreaElement
943
+ event.target instanceof HTMLTextAreaElement ||
944
+ (event.target instanceof HTMLElement && event.target.isContentEditable)
774
945
  )
775
946
  return;
776
947
  event.preventDefault();
@@ -823,6 +994,76 @@ getById("back5s", HTMLButtonElement).addEventListener("click", () => {
823
994
  */
824
995
  const FPS = canvasRecorder.fps;
825
996
 
997
+ // MARK: Frames
998
+
999
+ /**
1000
+ * Frame *n* covers the times from n / FPS (inclusive) to (n + 1) / FPS (exclusive), and is
1001
+ * always drawn at its center, (n + ½) / FPS. That's true for the whole video and for any part
1002
+ * of it, so separately saved pieces line up exactly.
1003
+ *
1004
+ * These measure in frames from the start of the whole video, with the centers at whole numbers.
1005
+ * The play position is stored to 0.1 ms (see {@link loadPlayPositionSeconds}), so a time that
1006
+ * was meant to be a center is allowed to miss by a little.
1007
+ */
1008
+ const FRAME_TOLERANCE = 0.01;
1009
+
1010
+ /** `ms` in frames, shifted so the frame centers are whole numbers. */
1011
+ function framePosition(ms: number): number {
1012
+ return (ms * FPS) / 1000 - 0.5;
1013
+ }
1014
+
1015
+ /** Where frame `n` is drawn, in ms from the start of the whole video. */
1016
+ function frameCenterMs(n: number): number {
1017
+ return ((n + 0.5) * 1000) / FPS;
1018
+ }
1019
+
1020
+ /** The first frame drawn at or after `ms`. */
1021
+ function firstFrameAtOrAfter(ms: number): number {
1022
+ return Math.ceil(framePosition(ms) - FRAME_TOLERANCE);
1023
+ }
1024
+
1025
+ /** How many frames are drawn from `startMs` (inclusive) to `endMs` (exclusive). */
1026
+ function framesBetween(startMs: number, endMs: number): number {
1027
+ return Math.max(0, firstFrameAtOrAfter(endMs) - firstFrameAtOrAfter(startMs));
1028
+ }
1029
+
1030
+ /**
1031
+ * Move one frame forward (+1) or back (-1), pausing playback.
1032
+ *
1033
+ * From a frame's center, that's exactly one frame. From anywhere else, it's the nearest
1034
+ * center in that direction, so the playhead always ends up on a time that's really rendered.
1035
+ * It stays inside the play limits.
1036
+ */
1037
+ function stepOneFrame(direction: 1 | -1): void {
1038
+ const position = framePosition(playPositionSeconds.valueAsNumber * 1000);
1039
+ let frame =
1040
+ direction > 0
1041
+ ? Math.floor(position + FRAME_TOLERANCE) + 1
1042
+ : Math.ceil(position - FRAME_TOLERANCE) - 1;
1043
+ const first = firstFrameAtOrAfter(sectionStartTime);
1044
+ const last = firstFrameAtOrAfter(sectionEndTime) - 1;
1045
+ frame = Math.max(first, Math.min(last, frame));
1046
+ playCheckBox.checked = false;
1047
+ stopAudio();
1048
+ loadPlayPositionSeconds(frameCenterMs(frame));
1049
+ loadPlayPositionRange();
1050
+ }
1051
+
1052
+ // Option-← and Option-→: one frame back or forward. Like the other hot keys, these use Option.
1053
+ // They work even in a text field, where they would otherwise move the cursor one word.
1054
+ // Arrow keys never cause a keypress event, so this has to be keydown.
1055
+ addEventListener("keydown", (event) => {
1056
+ if (!event.altKey || event.shiftKey || event.metaKey || event.ctrlKey) return;
1057
+ if (suspendLiveAnimationLoop) return; // Recording.
1058
+ if (event.code === "ArrowRight") {
1059
+ stepOneFrame(1);
1060
+ event.preventDefault();
1061
+ } else if (event.code === "ArrowLeft") {
1062
+ stepOneFrame(-1);
1063
+ event.preventDefault();
1064
+ }
1065
+ });
1066
+
826
1067
  /**
827
1068
  * This is the status of the save. It has no purpose during live / realtime operation
828
1069
  * so it initialize it to blank.
@@ -841,6 +1082,158 @@ const cancelRecordingButton = getById("cancelRecording", HTMLButtonElement);
841
1082
  */
842
1083
  const liveControls = getById("liveControls", HTMLFieldSetElement);
843
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
+
844
1237
  /**
845
1238
  * Someone hit the stop button.
846
1239
  */
@@ -858,7 +1251,21 @@ function escapeHtml(text: string): string {
858
1251
  .replace(/>/g, "&gt;");
859
1252
  }
860
1253
 
861
- async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration) {
1254
+ /**
1255
+ * Record the video and save it to a file the user picks.
1256
+ * @param saveStartMs Where to start, in the video's time.
1257
+ * @param saveEndMs Where to stop.
1258
+ * @param pixelWidth The saved file's width. Usually {@link canvasRecorder.pixelWidth}, but the
1259
+ * Save dialog can change it, just for this file. Nothing else sees the change: the picture
1260
+ * is still drawn in canvasRecorder's units, and simply stretched to this size.
1261
+ * @param pixelHeight The saved file's height. See `pixelWidth`.
1262
+ */
1263
+ async function startRecording(
1264
+ saveStartMs = 0,
1265
+ saveEndMs = toShow.duration,
1266
+ pixelWidth = canvasRecorder.pixelWidth,
1267
+ pixelHeight = canvasRecorder.pixelHeight,
1268
+ ) {
862
1269
  stopAudio();
863
1270
  startRecordingButton.disabled = true;
864
1271
  liveControls.disabled = true;
@@ -867,13 +1274,13 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration) {
867
1274
 
868
1275
  suspendLiveAnimationLoop = true;
869
1276
 
870
- // Lock canvas at 4K for the duration of recording.
1277
+ // Lock the canvas at the output size for the duration of recording.
871
1278
  // Disable all size-changing code paths so the encoder sees a constant frame size.
872
1279
  isRecording = true;
873
1280
  viewportResizeObserver.disconnect();
874
1281
  zoomControls.inert = true;
875
- canvas.width = canvasRecorder.pixelWidth;
876
- canvas.height = canvasRecorder.pixelHeight;
1282
+ canvas.width = pixelWidth;
1283
+ canvas.height = pixelHeight;
877
1284
  canvas.style.width = "";
878
1285
  canvas.style.height = "";
879
1286
  canvas.style.maxWidth = "100%";
@@ -897,7 +1304,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration) {
897
1304
  suggestedName: "canvas-recording.mp4",
898
1305
  types: [
899
1306
  {
900
- description: "WebM Video",
1307
+ description: "MP4 Video",
901
1308
  accept: { "video/mp4": [".mp4"] },
902
1309
  },
903
1310
  ],
@@ -911,38 +1318,28 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration) {
911
1318
  target: new StreamTarget(writableStream, { chunked: true }), // Batch writes for speed
912
1319
  });
913
1320
 
914
- // Canvas source (VP9 for good quality/size on macOS)
1321
+ // HEVC (H.265): Macs encode it in hardware, fast and well.
915
1322
  const videoSource = new CanvasSource(canvas, {
916
1323
  codec: "hevc",
917
- bitrate: 16_000_000, // ~8Mbps — tune higher for better quality
1324
+ // 16 Mbps. This file is the master that YouTube re-encodes, so a higher rate costs only
1325
+ // file size. See "Export bit rate" in development-plans/review-2026-11.md.
1326
+ bitrate: 16_000_000,
918
1327
  });
919
1328
 
920
1329
  output.addVideoTrack(videoSource, { frameRate: FPS });
921
1330
 
922
- const fullAudioBuffer = audioBuilder.getAudioBuffer();
923
- let audioBuffer: AudioBuffer;
924
- if (saveStartMs === 0 && saveEndMs >= toShow.duration) {
925
- audioBuffer = fullAudioBuffer;
926
- } else {
927
- const sr = fullAudioBuffer.sampleRate;
928
- const s0 = Math.round((saveStartMs / 1000) * sr);
929
- const s1 = Math.min(
930
- Math.round((saveEndMs / 1000) * sr),
931
- fullAudioBuffer.length,
932
- );
933
- const len = Math.max(0, s1 - s0);
934
- audioBuffer = new AudioBuffer({
935
- numberOfChannels: fullAudioBuffer.numberOfChannels,
936
- length: len,
937
- sampleRate: sr,
938
- });
939
- for (let ch = 0; ch < fullAudioBuffer.numberOfChannels; ch++) {
940
- audioBuffer.copyToChannel(
941
- fullAudioBuffer.getChannelData(ch).subarray(s0, s0 + len),
942
- ch,
943
- );
944
- }
945
- }
1331
+ // Frames come from the whole video's grid, even for part of it. See firstFrameAtOrAfter().
1332
+ const firstFrame = firstFrameAtOrAfter(saveStartMs);
1333
+ // The file starts where its first frame starts, so the sound starts there too.
1334
+ const audioStartMs = (firstFrame * 1000) / FPS;
1335
+
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();
946
1343
  const audioSource = new AudioBufferSource({
947
1344
  codec: "aac",
948
1345
  bitrate: QUALITY_HIGH,
@@ -960,7 +1357,7 @@ async function startRecording(saveStartMs = 0, saveEndMs = toShow.duration) {
960
1357
  let frameNumber = 0;
961
1358
  let warnedNoFramePromises = false;
962
1359
  while (!canceled) {
963
- const timeInMs = saveStartMs + (frameNumber + 0.5) * frameDuration;
1360
+ const timeInMs = frameCenterMs(firstFrame + frameNumber);
964
1361
  if (timeInMs >= saveEndMs) {
965
1362
  break;
966
1363
  }
@@ -1096,6 +1493,85 @@ const saveInfoStart = getById("saveInfoStart", HTMLTableCellElement);
1096
1493
  const saveInfoEnd = getById("saveInfoEnd", HTMLTableCellElement);
1097
1494
  const saveInfoDuration = getById("saveInfoDuration", HTMLTableCellElement);
1098
1495
  const saveInfoFrames = getById("saveInfoFrames", HTMLTableCellElement);
1496
+ const saveWidthInput = getById("saveWidth", HTMLInputElement);
1497
+ const saveHeightInput = getById("saveHeight", HTMLInputElement);
1498
+ const saveKeepAspectCheckbox = getById("saveKeepAspect", HTMLInputElement);
1499
+ const saveSizeNote = getById("saveSizeNote", HTMLDivElement);
1500
+ const saveOkBtn = getById("saveOkBtn", HTMLButtonElement);
1501
+
1502
+ // MARK: Save size
1503
+
1504
+ /**
1505
+ * Why the Save dialog's size can't be used, or undefined if it can.
1506
+ *
1507
+ * HEVC stores color at half resolution (4:2:0), so both numbers must be even.
1508
+ */
1509
+ function saveSizeProblem(width: number, height: number): string | undefined {
1510
+ if (!(Number.isInteger(width) && width > 0 && Number.isInteger(height) && height > 0)) {
1511
+ return "The size must be two whole numbers of pixels.";
1512
+ }
1513
+ if (width % 2 || height % 2) {
1514
+ return "Both numbers must be even.";
1515
+ }
1516
+ return undefined;
1517
+ }
1518
+
1519
+ /** Explain the Save dialog's size, and enable OK only when everything is usable. */
1520
+ function updateSaveSizeNote(): void {
1521
+ const width = saveWidthInput.valueAsNumber;
1522
+ const height = saveHeightInput.valueAsNumber;
1523
+ const { pixelWidth, pixelHeight } = canvasRecorder;
1524
+ const problem = saveSizeProblem(width, height);
1525
+ if (problem) {
1526
+ saveSizeNote.textContent = problem;
1527
+ saveSizeNote.style.color = "red";
1528
+ } else if (width === pixelWidth && height === pixelHeight) {
1529
+ saveSizeNote.textContent = "The video's own size.";
1530
+ saveSizeNote.style.color = "#555";
1531
+ } else {
1532
+ const stretched =
1533
+ Math.abs((width / height) / (pixelWidth / pixelHeight) - 1) > 0.001;
1534
+ saveSizeNote.textContent = stretched
1535
+ ? `Stretched: the video is ${pixelWidth} × ${pixelHeight}.`
1536
+ : `${Math.round((width / pixelWidth) * 100)}% of the video's ${pixelWidth} × ${pixelHeight}.`;
1537
+ saveSizeNote.style.color = stretched ? "#a06000" : "#555";
1538
+ }
1539
+ const startMs = (saveStartSecondsInput.valueAsNumber || 0) * 1000;
1540
+ const endMs = (saveEndSecondsInput.valueAsNumber || 0) * 1000;
1541
+ saveOkBtn.disabled = problem !== undefined || endMs <= startMs;
1542
+ }
1543
+
1544
+ /** Set the Save dialog's size to the video's own. */
1545
+ function resetSaveSize(): void {
1546
+ saveWidthInput.value = String(canvasRecorder.pixelWidth);
1547
+ saveHeightInput.value = String(canvasRecorder.pixelHeight);
1548
+ updateSaveSizeNote();
1549
+ }
1550
+
1551
+ /**
1552
+ * With Keep aspect ratio checked, typing one number sets the other.
1553
+ * The shape always comes from the video's own size, not the last pair typed, so it can't drift.
1554
+ * The other number is rounded to an even number of pixels.
1555
+ */
1556
+ function matchSaveAspect(changed: "width" | "height"): void {
1557
+ if (saveKeepAspectCheckbox.checked) {
1558
+ const aspect = canvasRecorder.pixelWidth / canvasRecorder.pixelHeight;
1559
+ const even = (n: number) => Math.max(2, Math.round(n / 2) * 2);
1560
+ if (changed === "width") {
1561
+ const width = saveWidthInput.valueAsNumber;
1562
+ if (width > 0) saveHeightInput.value = String(even(width / aspect));
1563
+ } else {
1564
+ const height = saveHeightInput.valueAsNumber;
1565
+ if (height > 0) saveWidthInput.value = String(even(height * aspect));
1566
+ }
1567
+ }
1568
+ updateSaveSizeNote();
1569
+ }
1570
+
1571
+ saveWidthInput.addEventListener("input", () => matchSaveAspect("width"));
1572
+ saveHeightInput.addEventListener("input", () => matchSaveAspect("height"));
1573
+ saveKeepAspectCheckbox.addEventListener("input", () => matchSaveAspect("width"));
1574
+ getById("saveVideoSizeBtn", HTMLButtonElement).addEventListener("click", resetSaveSize);
1099
1575
 
1100
1576
  function formatTimecode(ms: number): string {
1101
1577
  const totalFrames = Math.round((ms * FPS) / 1000);
@@ -1116,10 +1592,9 @@ function updateSaveDialogInfo(): void {
1116
1592
  saveInfoEnd.textContent = formatTimecode(endMs);
1117
1593
  saveInfoDuration.textContent = formatTimecode(durationMs);
1118
1594
  saveInfoDuration.style.color = invalid ? "red" : "";
1119
- saveInfoFrames.textContent = Math.floor(
1120
- (durationMs * FPS) / 1000,
1121
- ).toLocaleString();
1595
+ saveInfoFrames.textContent = framesBetween(startMs, endMs).toLocaleString();
1122
1596
  saveInfoFrames.style.color = invalid ? "red" : "";
1597
+ updateSaveSizeNote();
1123
1598
  }
1124
1599
 
1125
1600
  function setSaveRange(startMs: number, endMs: number): void {
@@ -1186,17 +1661,49 @@ getById("saveDialogCancelBtn", HTMLButtonElement).addEventListener(
1186
1661
  () => saveDialog.close(),
1187
1662
  );
1188
1663
 
1189
- getById("saveOkBtn", HTMLButtonElement).addEventListener("click", () => {
1664
+ const saveLocalFilesRow = getById("saveLocalFilesRow", HTMLDivElement);
1665
+ const saveLocalFilesNote = getById("saveLocalFilesNote", HTMLSpanElement);
1666
+ const saveLocalFilesBtn = getById("saveLocalFilesBtn", HTMLButtonElement);
1667
+
1668
+ /**
1669
+ * Check every local file the video uses, before a long recording starts, so it can't stop
1670
+ * halfway to wait for a permission nobody is there to give.
1671
+ * @returns True if they're all ready. Otherwise the Save dialog says what's wrong.
1672
+ */
1673
+ async function saveDialogLocalFilesReady(): Promise<boolean> {
1674
+ const problems = await checkLocalFiles(localFileUrlsIn(toShow));
1675
+ saveLocalFilesRow.hidden = problems.length === 0;
1676
+ const needPermission = problems.some((problem) => problem.reason === "permission");
1677
+ saveLocalFilesBtn.hidden = !needPermission;
1678
+ saveLocalFilesNote.textContent = problems.map((problem) => problem.message).join(" ");
1679
+ return problems.length === 0;
1680
+ }
1681
+
1682
+ saveLocalFilesBtn.addEventListener("click", async () => {
1683
+ await allowLocalFiles();
1684
+ await saveDialogLocalFilesReady();
1685
+ });
1686
+
1687
+ saveOkBtn.addEventListener("click", async () => {
1190
1688
  const startMs = (saveStartSecondsInput.valueAsNumber || 0) * 1000;
1191
1689
  const endMs = (saveEndSecondsInput.valueAsNumber || 0) * 1000;
1690
+ const width = saveWidthInput.valueAsNumber;
1691
+ const height = saveHeightInput.valueAsNumber;
1692
+ if (saveSizeProblem(width, height)) return;
1693
+ // Quick: no prompts, just IndexedDB. The click still counts for the file picker afterward.
1694
+ if (!(await saveDialogLocalFilesReady())) return;
1192
1695
  saveDialog.close();
1193
- startRecording(startMs, endMs);
1696
+ startRecording(startMs, endMs, width, height);
1194
1697
  });
1195
1698
 
1196
1699
  startRecordingButton.addEventListener("click", () => {
1197
1700
  populateSaveChapterSelect();
1701
+ // Always start from the video's own size, not whatever was used last time.
1702
+ resetSaveSize();
1198
1703
  setSaveRange(0, toShow.duration);
1704
+ saveLocalFilesRow.hidden = true;
1199
1705
  saveDialog.showModal();
1706
+ void saveDialogLocalFilesReady();
1200
1707
  });
1201
1708
 
1202
1709
  /**
@@ -1338,7 +1845,7 @@ const visualEditorAPI: VisualEditorAPI = {
1338
1845
  const selectable = currentRoot();
1339
1846
  if (!selectable) return;
1340
1847
  if (howMuch === "sound") {
1341
- void initAudio();
1848
+ soundtrack.request();
1342
1849
  } else if (howMuch === "properties") {
1343
1850
  updateScheduleEditor(selectedSlideChild ?? selectable);
1344
1851
  } else {
@@ -1358,13 +1865,16 @@ const visualEditorAPI: VisualEditorAPI = {
1358
1865
  return playheadInRootMs();
1359
1866
  },
1360
1867
  getDecodedBuffer(url: string): AudioBuffer | null {
1361
- return audioBuilder.getDecodedBuffer(url);
1868
+ return soundtrack.getDecodedBuffer(url);
1362
1869
  },
1363
1870
  };
1364
1871
 
1365
1872
  // MARK: Console API
1366
1873
  philDebug.chapterList = chapterList;
1367
- 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;
1368
1878
  /**
1369
1879
  * Transcribe one file from scratch, skipping the cache, and report how long
1370
1880
  * it took. `device` is "webgpu" or "wasm"; leave it out for the normal choice.
@@ -1579,27 +2089,21 @@ const schedulesShowingDurations = new WeakSet<ScheduleInfo>();
1579
2089
  /** The selectable whose `.parent` is currently set to {@link veRootParent}. */
1580
2090
  let _veRootSelectable: Showable | undefined;
1581
2091
 
1582
- let _durationAudioTimer: ReturnType<typeof setTimeout> | undefined;
1583
-
1584
2092
  /**
1585
2093
  * Synthetic {@link ShowableParent} that acts as the root of the editable tree.
1586
2094
  * When a selectable's `scheduleHasChanged()` chain reaches this object we:
1587
2095
  * - refresh all visible duration inputs,
1588
2096
  * - kick the auto-save / dirty-status machinery, and
1589
- * - debounce an audio reload.
2097
+ * - ask for a new soundtrack (which does nothing if no sound clip moved).
1590
2098
  */
1591
2099
  const veRootParent: ShowableParent = {
1592
2100
  scheduleHasChanged() {
1593
2101
  for (const cb of durationSyncCallbacks) cb();
1594
2102
  for (const cb of scheduleEditorRefreshers) cb();
1595
2103
  markDirty();
1596
- clearTimeout(_durationAudioTimer);
1597
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2104
+ soundtrack.request();
1598
2105
  // Redraw the timeline so block positions/sizes update during drags.
1599
- if (_veRootSelectable) {
1600
- timelineDisplay.setChapterDuration(_veRootSelectable.duration);
1601
- timelineDisplay.setBlocks(_buildTimelineBlocks(_veRootSelectable));
1602
- }
2106
+ refreshTimeline();
1603
2107
  scheduleChapterRefresh();
1604
2108
  },
1605
2109
  };
@@ -1619,12 +2123,8 @@ const toShowParent: ShowableParent = {
1619
2123
  for (const cb of durationSyncCallbacks) cb();
1620
2124
  for (const cb of scheduleEditorRefreshers) cb();
1621
2125
  markDirty();
1622
- clearTimeout(_durationAudioTimer);
1623
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
1624
- if (_veRootSelectable) {
1625
- timelineDisplay.setChapterDuration(_veRootSelectable.duration);
1626
- timelineDisplay.setBlocks(_buildTimelineBlocks(_veRootSelectable));
1627
- }
2126
+ soundtrack.request();
2127
+ refreshTimeline();
1628
2128
  scheduleChapterRefresh();
1629
2129
  },
1630
2130
  };
@@ -1838,11 +2338,10 @@ transcriptView = new TranscriptView({
1838
2338
  clips.splice(index, 1, ...pieces);
1839
2339
  selectedSoundClip = pieces[0];
1840
2340
  markDirty();
1841
- clearTimeout(_durationAudioTimer);
1842
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2341
+ soundtrack.request();
1843
2342
  // Show the owner's Sound Clips, with the remaining piece highlighted.
1844
2343
  selectInChapter(owner);
1845
- if (_veRootSelectable) _updateTimeline(_veRootSelectable);
2344
+ refreshTimeline();
1846
2345
  },
1847
2346
  });
1848
2347
  getById("timelineCanvas", HTMLCanvasElement).after(transcriptView.element);
@@ -1912,12 +2411,11 @@ timelineDisplay.onBlockClick = (id) => {
1912
2411
 
1913
2412
  /**
1914
2413
  * A sound clip's numbers changed, from a field or a drag on the timeline.
1915
- * 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.
1916
2415
  */
1917
2416
  function _onClipValueChanged(): void {
1918
2417
  markDirty();
1919
- clearTimeout(_durationAudioTimer);
1920
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
2418
+ soundtrack.request();
1921
2419
  for (const cb of soundClipSyncCallbacks) cb();
1922
2420
  timelineDisplay.redraw();
1923
2421
  }
@@ -1929,7 +2427,7 @@ const MIN_SOUND_CLIP_MS = 50;
1929
2427
 
1930
2428
  /** How long the file `clip` plays from is, once it has been decoded. */
1931
2429
  function soundFileMs(clip: SoundClip): number | undefined {
1932
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2430
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
1933
2431
  return buffer ? buffer.duration * 1000 : undefined;
1934
2432
  }
1935
2433
 
@@ -2031,7 +2529,7 @@ function soundClipBlock(clip: SoundClip, ownerStart: number): TimelineBlock {
2031
2529
  startMs: start,
2032
2530
  durationMs: () => soundClipLengthMs(clip) ?? 0,
2033
2531
  waveform: () => {
2034
- const buffer = audioBuilder.getDecodedBuffer(clip.source);
2532
+ const buffer = soundtrack.getDecodedBuffer(clip.source);
2035
2533
  return buffer ? { buffer, fromMs: clip.startMsIntoClip ?? 0 } : undefined;
2036
2534
  },
2037
2535
  onDragBody: (newStartMs) => {
@@ -2187,11 +2685,40 @@ function _buildTimelineBlocks(selectable: Showable): TimelineBlock[] {
2187
2685
  }
2188
2686
  }
2189
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
+
2190
2706
  return blocks;
2191
2707
  }
2192
2708
 
2709
+ /**
2710
+ * Redraw the timeline after an edit. It always shows the chapter, the root picked in the
2711
+ * `<select>`. Not {@link _veRootSelectable}: that's whatever the component editor shows, which
2712
+ * can be a child of the chapter. Passing both, one after the other, looked like a new chapter
2713
+ * every time, and reset the timeline's zoom and pan.
2714
+ */
2715
+ function refreshTimeline(): void {
2716
+ const chapter = currentRoot();
2717
+ if (chapter) _updateTimeline(chapter);
2718
+ }
2719
+
2193
2720
  function _updateTimeline(selectable: Showable): void {
2194
- timelineDisplay.setChapterDuration(selectable.duration);
2721
+ timelineDisplay.setChapter(selectable, selectable.duration);
2195
2722
  timelineDisplay.setBlocks(_buildTimelineBlocks(selectable));
2196
2723
  timelineDisplay.setSelectedId(selectedSlideChild ?? undefined);
2197
2724
  }
@@ -2679,10 +3206,6 @@ function buildDiffText(): string {
2679
3206
  : JSON.stringify(s.value);
2680
3207
  }
2681
3208
 
2682
- /**
2683
- * Generate TypeScript constructor + .set() lines for a removable component,
2684
- * omitting any property whose value matches the class default.
2685
- */
2686
3209
  /** Variable names already used in this diff, so generated code never declares one twice. */
2687
3210
  const usedVarNames = new Set<string>();
2688
3211
  function uniqueVarName(base: string): string {
@@ -2694,14 +3217,15 @@ function buildDiffText(): string {
2694
3217
 
2695
3218
  /**
2696
3219
  * TypeScript that recreates `comp`, a component added in the Visual Editor, and adds it to
2697
- * `parentExpr`. Covers everything the save file stores for such a component: schedules
3220
+ * `parentExpr`'s replaceable children, so the Visual Editor can still edit or delete it.
3221
+ * Covers everything the save file stores for such a component: schedules
2698
3222
  * and scalars that differ from the class's defaults, the user's name for it, its own
2699
3223
  * replaceable children (recursively), its duration, and its sound clips.
2700
3224
  */
2701
3225
  function generateComponentCode(
2702
3226
  comp: Showable,
2703
3227
  indent: string,
2704
- parentExpr = "this",
3228
+ parentExpr: string,
2705
3229
  ): string[] {
2706
3230
  const out: string[] = [];
2707
3231
  const rk = comp.registryKey ?? "unknown";
@@ -2802,13 +3326,45 @@ function buildDiffText(): string {
2802
3326
  );
2803
3327
  }
2804
3328
 
2805
- out.push(`${indent}${parentExpr}.addFixed({ child: ${varName} });`);
3329
+ out.push(
3330
+ `${indent}${parentExpr}.replaceableComponents!.push(${varName});`,
3331
+ );
2806
3332
 
2807
3333
  return out;
2808
3334
  }
2809
3335
 
2810
- function diffNode(
2811
- defaultEntry: SerializedFixedChild,
3336
+ /** A component's name in the diff: the user's name for it, or its own. */
3337
+ function displayName(comp: Showable): string {
3338
+ return comp.userEditableDescription ?? comp.description;
3339
+ }
3340
+
3341
+ /** `names`, with " #1", " #2"… added to any name used more than once. */
3342
+ function numberedNames(names: readonly string[]): string[] {
3343
+ const total = new Map<string, number>();
3344
+ for (const name of names) total.set(name, (total.get(name) ?? 0) + 1);
3345
+ const seen = new Map<string, number>();
3346
+ return names.map((name) => {
3347
+ if (total.get(name)! < 2) return name;
3348
+ const n = (seen.get(name) ?? 0) + 1;
3349
+ seen.set(name, n);
3350
+ return `${name} #${n}`;
3351
+ });
3352
+ }
3353
+
3354
+ /**
3355
+ * The differences in one component's own properties. The same for a fixed child, whose
3356
+ * default is its TypeScript, and for a replaceable child, whose default is its counterpart
3357
+ * in the TypeScript's list.
3358
+ */
3359
+ function diffProperties(
3360
+ defaultEntry: Pick<
3361
+ SerializedFixedChild,
3362
+ | "schedules"
3363
+ | "scalars"
3364
+ | "duration"
3365
+ | "userEditableDescription"
3366
+ | "soundClips"
3367
+ >,
2812
3368
  sel: Showable,
2813
3369
  path: string[],
2814
3370
  ): void {
@@ -2882,15 +3438,91 @@ function buildDiffText(): string {
2882
3438
  lines.push(`TypeScript: ${JSON.stringify(defClips)}`);
2883
3439
  lines.push(`Current: ${JSON.stringify(curClips)}`);
2884
3440
  }
3441
+ }
3442
+
3443
+ /**
3444
+ * The differences between a component's replaceable children and the TypeScript's.
3445
+ *
3446
+ * Children pair up by kind and name, in order, the way fixed children pair up by description.
3447
+ * Then any left over pair up by kind alone, so a child renamed in the Visual Editor is one
3448
+ * child with a new name, not one deleted and one added.
3449
+ *
3450
+ * A pair prints its property changes, the same way a fixed child does. A child with no
3451
+ * counterpart in the TypeScript prints as the TypeScript that makes it. A deleted child, or
3452
+ * an order that deleting and adding wouldn't give, gets one line. No changes, no lines.
3453
+ */
3454
+ function diffReplaceable(
3455
+ defaults: readonly SerializedChild[],
3456
+ sel: Showable,
3457
+ path: string[],
3458
+ ): void {
3459
+ // Only components with a registry key are saved, so only they can differ.
3460
+ const live = (sel.replaceableComponents?.get() ?? []).filter(
3461
+ (comp) => comp.registryKey !== undefined,
3462
+ );
3463
+ const key = (registryKey: string, name: string | undefined) =>
3464
+ `${registryKey}\0${name ?? ""}`;
3465
+ const liveFor = counterparts(
3466
+ defaults.map((d) => ({
3467
+ description: key(d.registryKey, d.userEditableDescription),
3468
+ })),
3469
+ live.map((comp) => ({
3470
+ description: key(comp.registryKey!, comp.userEditableDescription),
3471
+ comp,
3472
+ })),
3473
+ ).map((match) => match?.comp);
3474
+ for (const [index, d] of defaults.entries()) {
3475
+ liveFor[index] ??= live.find(
3476
+ (comp) => comp.registryKey === d.registryKey && !liveFor.includes(comp),
3477
+ );
3478
+ }
3479
+ const added = live.filter((comp) => !liveFor.includes(comp));
3480
+ const names = new Map(
3481
+ numberedNames(live.map(displayName)).map((name, index) => [
3482
+ live[index],
3483
+ name,
3484
+ ]),
3485
+ );
2885
3486
 
2886
- const currentComponents = sel.replaceableComponents?.get() ?? [];
2887
- if (currentComponents.length > 0) {
3487
+ const expectedOrder = [
3488
+ ...liveFor.filter((comp) => comp !== undefined),
3489
+ ...added,
3490
+ ];
3491
+ if (expectedOrder.some((comp, index) => comp !== live[index])) {
2888
3492
  printPathIfNeeded(path);
2889
- for (const comp of currentComponents) {
2890
- lines.push(...generateComponentCode(comp, " "));
3493
+ lines.push(
3494
+ ` [new order: ${live.map((comp) => names.get(comp)).join(", ")}]`,
3495
+ );
3496
+ }
3497
+
3498
+ for (const [index, d] of defaults.entries()) {
3499
+ const comp = liveFor[index];
3500
+ if (comp) {
3501
+ const childPath = [...path, names.get(comp)!];
3502
+ diffProperties(d, comp, childPath);
3503
+ diffReplaceable(d.components ?? [], comp, childPath);
3504
+ } else {
3505
+ printPathIfNeeded([...path, d.userEditableDescription ?? d.registryKey]);
3506
+ lines.push(` [deleted]`);
2891
3507
  }
2892
3508
  }
2893
3509
 
3510
+ const parentExpr = toVarName(path.at(-1) ?? "") || "parent";
3511
+ for (const comp of added) {
3512
+ printPathIfNeeded([...path, names.get(comp)!]);
3513
+ lines.push(` [added]`);
3514
+ lines.push(...generateComponentCode(comp, " ", parentExpr));
3515
+ }
3516
+ }
3517
+
3518
+ function diffNode(
3519
+ defaultEntry: SerializedFixedChild,
3520
+ sel: Showable,
3521
+ path: string[],
3522
+ ): void {
3523
+ diffProperties(defaultEntry, sel, path);
3524
+ diffReplaceable(defaultEntry.components ?? [], sel, path);
3525
+
2894
3526
  const liveFixed = getFixedComponents(sel);
2895
3527
  const defaultFixed = defaultEntry.fixedComponents ?? [];
2896
3528
  const liveFor = counterparts(defaultFixed, liveFixed);
@@ -2919,10 +3551,12 @@ function buildDiffText(): string {
2919
3551
  diffNode(tsDefaultsTree, toShow, [toShow.description]);
2920
3552
  }
2921
3553
 
2922
- if (lines.length === 1) lines.push("(no differences found)");
3554
+ if (lines.length === 0) lines.push("(no differences found)");
2923
3555
 
2924
3556
  return lines.join("\n");
2925
3557
  }
3558
+ /** The diff file's text, from the console, with or without syncing the file. */
3559
+ philDebug.diffText = () => console.log(buildDiffText());
2926
3560
 
2927
3561
  // MARK: Load-source helpers
2928
3562
 
@@ -3135,6 +3769,18 @@ async function initFromDB(unloadBackup?: string | null): Promise<void> {
3135
3769
  updateComponentEditor(currentSel);
3136
3770
  updateScheduleEditor(currentSel);
3137
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();
3138
3784
  }
3139
3785
 
3140
3786
 
@@ -3234,6 +3880,10 @@ function currentSaveTarget(): Showable | null {
3234
3880
  }
3235
3881
 
3236
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();
3237
3887
 
3238
3888
  // When the history dialog is open the live tree may hold a transient preview from
3239
3889
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
@@ -3328,6 +3978,7 @@ function _dialogSelectItem(index: number, target: Showable) {
3328
3978
  activeRootComponentEditor?.resetAll();
3329
3979
  updateComponentEditor(target);
3330
3980
  updateScheduleEditor(target);
3981
+ afterStateApplied();
3331
3982
 
3332
3983
  // The Abandon/Save buttons are no longer used; only Keep is shown.
3333
3984
  historyOkBtn.hidden = false;
@@ -3570,6 +4221,7 @@ async function _applyDialogSelection() {
3570
4221
  activeRootComponentEditor?.resetAll();
3571
4222
  updateComponentEditor(target);
3572
4223
  updateScheduleEditor(target);
4224
+ afterStateApplied();
3573
4225
  }
3574
4226
 
3575
4227
  historyOkBtn.addEventListener("click", () => {
@@ -3598,6 +4250,7 @@ historyCancelBtn.addEventListener("click", () => {
3598
4250
  activeRootComponentEditor?.resetAll();
3599
4251
  updateComponentEditor(target);
3600
4252
  updateScheduleEditor(target);
4253
+ afterStateApplied();
3601
4254
  }
3602
4255
  historyDialog.close();
3603
4256
  });
@@ -3740,9 +4393,19 @@ function buildScheduleSection(
3740
4393
  return playPositionSeconds.valueAsNumber * 1000;
3741
4394
  }
3742
4395
 
3743
- /** Time relative to the start of the selected scene — what keyframe.time values use. */
4396
+ /**
4397
+ * Where the component that owns this schedule starts, measured from the start of the Visual
4398
+ * Editor's root. 0 for anything in a parallel container at the top, which is why measuring
4399
+ * from the root used to look right. A clip in an In Series starts later.
4400
+ */
4401
+ function ownerStartMs() {
4402
+ const root = currentRoot();
4403
+ return root ? (startWithin(root, selectable) ?? 0) : 0;
4404
+ }
4405
+
4406
+ /** Time relative to the start of the component that owns this schedule — what keyframe.time values use. */
3744
4407
  function localTimeMs() {
3745
- return currentTimeMs() - rootStartMs;
4408
+ return currentTimeMs() - rootStartMs - ownerStartMs();
3746
4409
  }
3747
4410
 
3748
4411
  function addKeyframeAtCurrentTime() {
@@ -4553,7 +5216,7 @@ function buildScheduleSection(
4553
5216
  goToBtn.addEventListener("click", () => {
4554
5217
  const globalMs = Math.max(
4555
5218
  sectionStartTime,
4556
- Math.min(sectionEndTime, kf.time + rootStartMs),
5219
+ Math.min(sectionEndTime, kf.time + rootStartMs + ownerStartMs()),
4557
5220
  );
4558
5221
  stopAudio();
4559
5222
  loadPlayPositionSeconds(globalMs);
@@ -4694,10 +5357,13 @@ function updateComponentEditor(selectable: Showable) {
4694
5357
 
4695
5358
  if (replaceable && replaceables) {
4696
5359
  const moveChild = (fromIdx: number, toIdx: number) => {
4697
- const arr = replaceables.get();
4698
- const [item] = arr.splice(fromIdx, 1);
4699
- arr.splice(toIdx, 0, item);
4700
- replaceables.replace(arr);
5360
+ // In a series, the playhead follows the picture it was showing.
5361
+ keepingScene(selectable, () => {
5362
+ const arr = replaceables.get();
5363
+ const [item] = arr.splice(fromIdx, 1);
5364
+ arr.splice(toIdx, 0, item);
5365
+ replaceables.replace(arr);
5366
+ });
4701
5367
  activeRootComponentEditor?.resetAll();
4702
5368
  updateComponentEditor(selectable);
4703
5369
  };
@@ -4735,11 +5401,20 @@ function updateComponentEditor(selectable: Showable) {
4735
5401
  const deleteBtn = document.createElement("button");
4736
5402
  deleteBtn.type = "button";
4737
5403
  deleteBtn.textContent = "🗑";
5404
+ deleteBtn.title = "Delete component";
4738
5405
  deleteBtn.addEventListener("click", () => {
5406
+ // In a series, everything after this child moves earlier, and the playhead goes with it.
5407
+ const root = currentRoot();
5408
+ const childStart = root ? startWithin(root, child) : undefined;
5409
+ const childDuration = child.duration;
5410
+ const chainEndMs = seriesChainEndMs(selectable);
4739
5411
  const arr = replaceables.get();
4740
5412
  const i = arr.indexOf(child);
4741
5413
  if (i !== -1) arr.splice(i, 1);
4742
5414
  replaceables.replace(arr);
5415
+ if (childStart !== undefined) {
5416
+ playheadAfterRemoving(childStart, childStart + childDuration, chainEndMs);
5417
+ }
4743
5418
  if (selectedSlideChild === child) {
4744
5419
  selectedSlideChild = null;
4745
5420
  updateScheduleEditor(selectable);
@@ -4880,6 +5555,16 @@ function updateComponentEditor(selectable: Showable) {
4880
5555
  const entry = key === undefined ? undefined : componentRegistry.get(key);
4881
5556
  if (!entry) return;
4882
5557
  const newChild = entry.create();
5558
+ if (newChild instanceof VideoClipComponent) {
5559
+ // The class default is 16 × 9, and saved files rely on defaults never changing.
5560
+ // So fill the canvas here, as a value of its own, whatever size the canvas is.
5561
+ newChild.destinationRectSchedule.set({
5562
+ x: 0,
5563
+ y: 0,
5564
+ width: canvasRecorder.width,
5565
+ height: canvasRecorder.height,
5566
+ });
5567
+ }
4883
5568
  addTarget.replaceableComponents!.push(newChild);
4884
5569
  afterStructureEdit(newChild);
4885
5570
  });
@@ -4944,30 +5629,34 @@ function updateComponentEditor(selectable: Showable) {
4944
5629
  }
4945
5630
 
4946
5631
  /**
4947
- * The Sound Clips section of the schedule editor, for a component whose
4948
- * `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.
4949
5636
  *
4950
5637
  * Each card's Owner menu moves the clip to another component without changing
4951
5638
  * when it plays. Registers per-field sync callbacks into
4952
5639
  * {@link soundClipSyncCallbacks}, so drags on the timeline show up here.
4953
5640
  */
4954
5641
  function buildSoundClipSection(selectable: Showable): HTMLElement {
4955
- 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);
4956
5645
 
4957
5646
  /** The clip list changed shape: save, rebuild the audio, redraw this section and the timeline. */
4958
5647
  function afterStructureChange(): void {
4959
5648
  markDirty();
4960
- clearTimeout(_durationAudioTimer);
4961
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
5649
+ soundtrack.request();
4962
5650
  updateScheduleEditor(selectable);
4963
- if (_veRootSelectable) _updateTimeline(_veRootSelectable);
5651
+ refreshTimeline();
4964
5652
  }
4965
5653
 
4966
- /** 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. */
4967
5655
  const owners = soundOwners(toShow);
5656
+ /** Undefined until this component has a list. Then it has cards, with Owner menus that need it. */
4968
5657
  const self = owners.find(({ owner }) => owner === selectable);
4969
5658
  /** When this component starts, in video time. 0 if it can't be found, which shouldn't happen. */
4970
- const selfStartMs = self?.startMs ?? 0;
5659
+ const selfStartMs = startWithin(toShow, selectable) ?? 0;
4971
5660
 
4972
5661
  const section = document.createElement("fieldset");
4973
5662
  const legend = document.createElement("legend");
@@ -4987,6 +5676,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
4987
5676
  addBtn.style.marginLeft = "auto";
4988
5677
  addBtn.addEventListener("click", () => {
4989
5678
  const clip: SoundClip = { source: "", startMsIntoScene: playheadInOwner() };
5679
+ ensureList();
4990
5680
  clips.push(clip);
4991
5681
  selectedSoundClip = clip;
4992
5682
  afterStructureChange();
@@ -5010,6 +5700,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5010
5700
  alert("No sound clips found on the clipboard. Each one needs at least a source.");
5011
5701
  return;
5012
5702
  }
5703
+ ensureList();
5013
5704
  clips.push(...pasted);
5014
5705
  selectedSoundClip = pasted[0];
5015
5706
  afterStructureChange();
@@ -5072,7 +5763,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5072
5763
 
5073
5764
  const delBtn = document.createElement("button");
5074
5765
  delBtn.type = "button";
5075
- delBtn.textContent = "✕";
5766
+ delBtn.textContent = "🗑";
5076
5767
  delBtn.title = "Delete clip";
5077
5768
  delBtn.addEventListener("click", () => {
5078
5769
  clips.splice(i, 1);
@@ -5305,8 +5996,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5305
5996
  rehomeSoundClip(clip, self, to);
5306
5997
  selectedSoundClip = clip;
5307
5998
  markDirty();
5308
- clearTimeout(_durationAudioTimer);
5309
- _durationAudioTimer = setTimeout(() => void initAudio(), 300);
5999
+ soundtrack.request();
5310
6000
  const chapter = currentRoot();
5311
6001
  if (chapter && startWithin(chapter, to.owner) !== undefined) {
5312
6002
  // Follow the clip to its new owner.
@@ -5315,7 +6005,7 @@ function buildSoundClipSection(selectable: Showable): HTMLElement {
5315
6005
  // The new owner is in another chapter. Stay here; the clip is gone from this list.
5316
6006
  updateScheduleEditor(selectable);
5317
6007
  }
5318
- if (_veRootSelectable) _updateTimeline(_veRootSelectable);
6008
+ refreshTimeline();
5319
6009
  });
5320
6010
  ownerLabel.append(ownerSelect);
5321
6011
  const playsAt = document.createElement("span");
@@ -5370,6 +6060,9 @@ function buildNameSection(selectable: Showable): HTMLElement {
5370
6060
  resetBtn.disabled = selectable.userEditableDescription === undefined;
5371
6061
  const root = currentSaveTarget();
5372
6062
  if (root) updateComponentEditor(root);
6063
+ // The timeline's blocks and the Edit menu show the name, too.
6064
+ refreshTimeline();
6065
+ scheduleChapterRefresh();
5373
6066
  }
5374
6067
 
5375
6068
  input.addEventListener("input", () => syncName(input.value));
@@ -5426,16 +6119,7 @@ function updateScheduleEditor(selectable: Showable) {
5426
6119
  const multiText =
5427
6120
  selectable instanceof MultiTextComponent ? selectable : null;
5428
6121
 
5429
- if (
5430
- !scalars?.length &&
5431
- !schedules?.length &&
5432
- !isTraditionalText &&
5433
- !slideComponent &&
5434
- selectable.soundClips === undefined
5435
- ) {
5436
- scheduleEditorFieldset.hidden = true;
5437
- return;
5438
- }
6122
+ // Every component has something to edit: at least its name and its sound clips.
5439
6123
  scheduleEditorFieldset.hidden = false;
5440
6124
  scheduleEditorFieldset.append(buildNameSection(selectable));
5441
6125
 
@@ -5450,6 +6134,13 @@ function updateScheduleEditor(selectable: Showable) {
5450
6134
 
5451
6135
  const videoPanel = videoClip
5452
6136
  ? buildVideoClipPanel(videoClip, {
6137
+ setVideoSize: setVideoSizeFromGui,
6138
+ urlChanged() {
6139
+ activeRootComponentEditor?.update(videoClip, videoClip.urlScalar);
6140
+ markDirty();
6141
+ // Rebuild so the URL field shows the new value.
6142
+ updateScheduleEditor(videoClip);
6143
+ },
5453
6144
  scalarsChanged() {
5454
6145
  activeRootComponentEditor?.update(
5455
6146
  videoClip,
@@ -5496,6 +6187,12 @@ function updateScheduleEditor(selectable: Showable) {
5496
6187
  if (selectable instanceof SingleImageComponent) {
5497
6188
  const image = selectable;
5498
6189
  const imagePanel = buildStaticImagePanel(image, {
6190
+ urlChanged() {
6191
+ activeRootComponentEditor?.update(image, image.urlSchedule);
6192
+ markDirty();
6193
+ // Rebuild so the URL field shows the new value.
6194
+ updateScheduleEditor(image);
6195
+ },
5499
6196
  rectKeyframeChanged(kf) {
5500
6197
  // The same sync a drag on the canvas uses, so ✎ edit mode survives.
5501
6198
  markerSyncCallbacks.get(kf)?.(kf.value);
@@ -5591,9 +6288,7 @@ function updateScheduleEditor(selectable: Showable) {
5591
6288
  }
5592
6289
  scheduleEditorFieldset.append(section);
5593
6290
  }
5594
- if (selectable.soundClips !== undefined) {
5595
- scheduleEditorFieldset.append(buildSoundClipSection(selectable));
5596
- }
6291
+ scheduleEditorFieldset.append(buildSoundClipSection(selectable));
5597
6292
  }
5598
6293
 
5599
6294
  // MARK: Split
@@ -5616,6 +6311,74 @@ function splitTarget(clip: VideoClipComponent): InSeriesComponent | string {
5616
6311
  return parent;
5617
6312
  }
5618
6313
 
6314
+ // MARK: Keep the scene
6315
+
6316
+ /** Move the playhead to this time, measured from the start of the Visual Editor's root. */
6317
+ function seekInRoot(ms: number): void {
6318
+ stopAudio();
6319
+ loadPlayPositionSeconds(rootStartMs + ms);
6320
+ loadPlayPositionRange();
6321
+ // An edit moved the playhead. Keep it on the timeline's screen if it was there.
6322
+ timelineDisplay.movePlayMs(ms);
6323
+ }
6324
+
6325
+ /**
6326
+ * Before an edit removes time from `series`: where its chain of series ends, measured from the
6327
+ * start of the root. Removing time moves everything up to there earlier, and nothing after it.
6328
+ * Undefined if `series` isn't an In Series in the current root, so nothing moves.
6329
+ */
6330
+ function seriesChainEndMs(series: Showable): number | undefined {
6331
+ const root = currentRoot();
6332
+ if (!root || !(series instanceof InSeriesComponent)) return undefined;
6333
+ let top: Showable = series;
6334
+ while (top !== root && top.parent instanceof InSeriesComponent) {
6335
+ top = top.parent;
6336
+ }
6337
+ const start = startWithin(root, top);
6338
+ return start === undefined ? undefined : start + top.duration;
6339
+ }
6340
+
6341
+ /**
6342
+ * A series just lost the time from `fromMs` to `toMs` (measured from the start of the root), and
6343
+ * everything after it moved earlier to fill the gap. Move the playhead with it, so the preview
6344
+ * keeps showing the same picture. A playhead inside what's gone goes to where the gap was.
6345
+ * @param chainEndMs {@link seriesChainEndMs}, from before the edit.
6346
+ */
6347
+ function playheadAfterRemoving(
6348
+ fromMs: number,
6349
+ toMs: number,
6350
+ chainEndMs: number | undefined,
6351
+ ): void {
6352
+ if (chainEndMs === undefined) return;
6353
+ const at = playheadInRootMs();
6354
+ if (at < fromMs || at >= chainEndMs) return;
6355
+ seekInRoot(at >= toMs ? at - (toMs - fromMs) : fromMs);
6356
+ }
6357
+
6358
+ /**
6359
+ * Run `edit`, which reorders the children of `series`, then put the playhead on the same moment
6360
+ * of the same child, wherever that child is now.
6361
+ */
6362
+ function keepingScene(series: Showable, edit: () => void): void {
6363
+ const root = currentRoot();
6364
+ const seriesStart =
6365
+ root && series instanceof InSeriesComponent
6366
+ ? startWithin(root, series)
6367
+ : undefined;
6368
+ let anchor: { child: Showable; offsetMs: number } | undefined;
6369
+ if (seriesStart !== undefined) {
6370
+ const local = playheadInRootMs() - seriesStart;
6371
+ const found = series.children?.find(
6372
+ ({ start, child }) => local >= start && local < start + child.duration,
6373
+ );
6374
+ if (found) anchor = { child: found.child, offsetMs: local - found.start };
6375
+ }
6376
+ edit();
6377
+ if (!root || !anchor) return;
6378
+ const newStart = startWithin(root, anchor.child);
6379
+ if (newStart !== undefined) seekInRoot(newStart + anchor.offsetMs);
6380
+ }
6381
+
5619
6382
  /** How long a sound plays, for splitting: a clip whose file isn't decoded yet is taken to play forever. */
5620
6383
  function soundLengthForSplit(sound: SoundClip): number {
5621
6384
  return soundClipLengthMs(sound) ?? Infinity;
@@ -5651,8 +6414,16 @@ async function splitAtPlayhead(clip: VideoClipComponent): Promise<void> {
5651
6414
  : [second];
5652
6415
  const siblings = parent.replaceableComponents!.get();
5653
6416
  siblings.splice(siblings.indexOf(clip), 1, ...kept);
6417
+ const chainEndMs = seriesChainEndMs(parent);
5654
6418
  // Saves, rebuilds the audio, and redraws the timeline and the chapter list.
5655
6419
  parent.replaceableComponents!.replace(siblings);
6420
+ // Keep showing the same picture: a piece thrown away takes its time with it.
6421
+ const splitMs = clipStart + first.duration;
6422
+ if (choice.keep === "second") {
6423
+ playheadAfterRemoving(clipStart, splitMs, chainEndMs);
6424
+ } else if (choice.keep === "first") {
6425
+ playheadAfterRemoving(splitMs, splitMs + second.duration, chainEndMs);
6426
+ }
5656
6427
  selectedSoundClip = undefined;
5657
6428
  activeRootComponentEditor?.resetAll();
5658
6429
  if (root !== clip) {
@@ -5739,6 +6510,21 @@ function buildMultiTextFrame(text: MultiTextComponent): HTMLElement {
5739
6510
  textFrameCanvasStates.set(text, newState);
5740
6511
  applyCanvasState();
5741
6512
  },
6513
+ editText() {
6514
+ void openMultiTextDialog(text, {
6515
+ saveNow: _flushDirtyToDb,
6516
+ changed: markDirty,
6517
+ copyComponent: (component) =>
6518
+ buildComponents(serializeComponents([component]))[0],
6519
+ closed() {
6520
+ // The dialog covered the component list and this panel, so neither was kept up to date.
6521
+ activeRootComponentEditor?.resetAll();
6522
+ const root = currentSaveTarget();
6523
+ if (root) updateComponentEditor(root);
6524
+ updateScheduleEditor(text);
6525
+ },
6526
+ });
6527
+ },
5742
6528
  });
5743
6529
  // Adding a keyframe to Position, say, means there's no longer one frame.
5744
6530
  scheduleEditorRefreshers.push(applyCanvasState, panel.refresh);
@@ -6904,15 +7690,20 @@ document.addEventListener("keyup", (e) => {
6904
7690
  getById("recordJustSound", HTMLButtonElement).addEventListener(
6905
7691
  "click",
6906
7692
  async () => {
6907
- const blob = await audioBuilder.toBlob();
6908
- 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());
6909
7699
  },
6910
7700
  );
6911
7701
 
6912
7702
  function reload(): void {
6913
7703
  initChapters();
6914
7704
  updateFromSelect();
6915
- initAudio();
7705
+ // Reload means everything, including sound files changed on disk.
7706
+ soundtrack.forget();
6916
7707
  }
6917
7708
 
6918
7709
  getById("reloadBtn", HTMLButtonElement).addEventListener("click", reload);
@@ -7083,6 +7874,9 @@ function refreshEditorsAfterLoad(): void {
7083
7874
  activeRootComponentEditor?.resetAll();
7084
7875
  updateComponentEditor(current);
7085
7876
  updateScheduleEditor(current);
7877
+ afterStateApplied();
7878
+ // The loaded state may use local files that need 🔓.
7879
+ checkVideosLocalFiles();
7086
7880
  }
7087
7881
 
7088
7882
  /**