canvas-recorder-lib 0.7.0 → 0.7.2

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 (175) hide show
  1. package/README.md +38 -8
  2. package/dev/audio-builder.ts +5 -1
  3. package/dev/canvas-recorder.css +15 -4
  4. package/dev/canvas-recorder.ts +276 -88
  5. package/dev/delay-files.ts +1 -1
  6. package/dev/format-editor.ts +7 -2
  7. package/dev/fourier-panel.ts +11 -3
  8. package/dev/handwriting-panel.ts +14 -9
  9. package/dev/local-file-row.ts +12 -5
  10. package/dev/multi-text-dialog.ts +15 -6
  11. package/dev/multi-text-panel.ts +6 -2
  12. package/dev/player-body.ts +4 -0
  13. package/dev/schedule-helpers.ts +11 -4
  14. package/dev/sound-clips.ts +4 -1
  15. package/dev/soundtrack.ts +52 -13
  16. package/dev/split-dialog.ts +49 -19
  17. package/dev/static-image-panel.ts +17 -5
  18. package/dev/synced-file.ts +4 -5
  19. package/dev/timeline-display.ts +152 -50
  20. package/dev/transcribe-core.ts +48 -17
  21. package/dev/transcribe-worker.ts +20 -9
  22. package/dev/transcript-align.ts +95 -20
  23. package/dev/transcript-export.ts +18 -7
  24. package/dev/transcript-view.ts +78 -22
  25. package/dev/transcripts.ts +97 -26
  26. package/dev/video-clip-panel.ts +64 -18
  27. package/dev/voice/chirp.ts +21 -5
  28. package/dev/voice/folder.ts +22 -7
  29. package/dev/voice/voice-panel.ts +61 -27
  30. package/dev/voice/voice-recorder.ts +74 -18
  31. package/dist/dev/audio-builder.js.map +1 -1
  32. package/dist/dev/canvas-recorder.css +15 -4
  33. package/dist/dev/canvas-recorder.js +185 -48
  34. package/dist/dev/canvas-recorder.js.map +1 -1
  35. package/dist/dev/format-editor.d.ts.map +1 -1
  36. package/dist/dev/format-editor.js.map +1 -1
  37. package/dist/dev/fourier-panel.d.ts.map +1 -1
  38. package/dist/dev/fourier-panel.js.map +1 -1
  39. package/dist/dev/handwriting-panel.d.ts.map +1 -1
  40. package/dist/dev/handwriting-panel.js +10 -8
  41. package/dist/dev/handwriting-panel.js.map +1 -1
  42. package/dist/dev/local-file-row.d.ts.map +1 -1
  43. package/dist/dev/local-file-row.js +12 -4
  44. package/dist/dev/local-file-row.js.map +1 -1
  45. package/dist/dev/multi-text-dialog.d.ts.map +1 -1
  46. package/dist/dev/multi-text-dialog.js +4 -2
  47. package/dist/dev/multi-text-dialog.js.map +1 -1
  48. package/dist/dev/multi-text-panel.d.ts.map +1 -1
  49. package/dist/dev/multi-text-panel.js +2 -1
  50. package/dist/dev/multi-text-panel.js.map +1 -1
  51. package/dist/dev/player-body.d.ts +1 -1
  52. package/dist/dev/player-body.d.ts.map +1 -1
  53. package/dist/dev/player-body.js +4 -0
  54. package/dist/dev/player-body.js.map +1 -1
  55. package/dist/dev/schedule-helpers.d.ts.map +1 -1
  56. package/dist/dev/schedule-helpers.js +4 -1
  57. package/dist/dev/schedule-helpers.js.map +1 -1
  58. package/dist/dev/sound-clips.d.ts.map +1 -1
  59. package/dist/dev/sound-clips.js.map +1 -1
  60. package/dist/dev/soundtrack.d.ts +12 -0
  61. package/dist/dev/soundtrack.d.ts.map +1 -1
  62. package/dist/dev/soundtrack.js +42 -9
  63. package/dist/dev/soundtrack.js.map +1 -1
  64. package/dist/dev/split-dialog.d.ts.map +1 -1
  65. package/dist/dev/split-dialog.js +17 -10
  66. package/dist/dev/split-dialog.js.map +1 -1
  67. package/dist/dev/static-image-panel.d.ts.map +1 -1
  68. package/dist/dev/static-image-panel.js +7 -3
  69. package/dist/dev/static-image-panel.js.map +1 -1
  70. package/dist/dev/synced-file.d.ts.map +1 -1
  71. package/dist/dev/synced-file.js.map +1 -1
  72. package/dist/dev/timeline-display.d.ts.map +1 -1
  73. package/dist/dev/timeline-display.js +62 -17
  74. package/dist/dev/timeline-display.js.map +1 -1
  75. package/dist/dev/transcribe-core.d.ts.map +1 -1
  76. package/dist/dev/transcribe-core.js +13 -3
  77. package/dist/dev/transcribe-core.js.map +1 -1
  78. package/dist/dev/transcribe-worker.d.ts.map +1 -1
  79. package/dist/dev/transcribe-worker.js +9 -3
  80. package/dist/dev/transcribe-worker.js.map +1 -1
  81. package/dist/dev/transcript-align.d.ts.map +1 -1
  82. package/dist/dev/transcript-align.js +52 -9
  83. package/dist/dev/transcript-align.js.map +1 -1
  84. package/dist/dev/transcript-export.d.ts.map +1 -1
  85. package/dist/dev/transcript-export.js +10 -4
  86. package/dist/dev/transcript-export.js.map +1 -1
  87. package/dist/dev/transcript-view.d.ts +2 -0
  88. package/dist/dev/transcript-view.d.ts.map +1 -1
  89. package/dist/dev/transcript-view.js +32 -11
  90. package/dist/dev/transcript-view.js.map +1 -1
  91. package/dist/dev/transcripts.d.ts +5 -0
  92. package/dist/dev/transcripts.d.ts.map +1 -1
  93. package/dist/dev/transcripts.js +54 -6
  94. package/dist/dev/transcripts.js.map +1 -1
  95. package/dist/dev/video-clip-panel.d.ts.map +1 -1
  96. package/dist/dev/video-clip-panel.js +25 -8
  97. package/dist/dev/video-clip-panel.js.map +1 -1
  98. package/dist/dev/voice/chirp.d.ts.map +1 -1
  99. package/dist/dev/voice/chirp.js +5 -1
  100. package/dist/dev/voice/chirp.js.map +1 -1
  101. package/dist/dev/voice/folder.d.ts.map +1 -1
  102. package/dist/dev/voice/folder.js +1 -1
  103. package/dist/dev/voice/folder.js.map +1 -1
  104. package/dist/dev/voice/voice-panel.d.ts.map +1 -1
  105. package/dist/dev/voice/voice-panel.js +42 -23
  106. package/dist/dev/voice/voice-panel.js.map +1 -1
  107. package/dist/dev/voice/voice-recorder.d.ts.map +1 -1
  108. package/dist/dev/voice/voice-recorder.js +34 -9
  109. package/dist/dev/voice/voice-recorder.js.map +1 -1
  110. package/dist/lib/main-control.d.ts.map +1 -1
  111. package/dist/lib/main-control.js.map +1 -1
  112. package/dist/src/corner-rounder.d.ts.map +1 -1
  113. package/dist/src/corner-rounder.js +1 -1
  114. package/dist/src/corner-rounder.js.map +1 -1
  115. package/dist/src/local-files.d.ts.map +1 -1
  116. package/dist/src/local-files.js +5 -2
  117. package/dist/src/local-files.js.map +1 -1
  118. package/dist/src/peano-fourier/fourier-shared.d.ts +7 -0
  119. package/dist/src/peano-fourier/fourier-shared.d.ts.map +1 -1
  120. package/dist/src/peano-fourier/fourier-shared.js +8 -1
  121. package/dist/src/peano-fourier/fourier-shared.js.map +1 -1
  122. package/dist/src/slide-components/fourier.d.ts.map +1 -1
  123. package/dist/src/slide-components/fourier.js +12 -4
  124. package/dist/src/slide-components/fourier.js.map +1 -1
  125. package/dist/src/slide-components/image.d.ts.map +1 -1
  126. package/dist/src/slide-components/image.js +1 -1
  127. package/dist/src/slide-components/image.js.map +1 -1
  128. package/dist/src/slide-components/in-parallel.d.ts.map +1 -1
  129. package/dist/src/slide-components/in-parallel.js.map +1 -1
  130. package/dist/src/slide-components/multi-text.d.ts.map +1 -1
  131. package/dist/src/slide-components/multi-text.js +1 -1
  132. package/dist/src/slide-components/multi-text.js.map +1 -1
  133. package/dist/src/slide-components/rectangle.d.ts.map +1 -1
  134. package/dist/src/slide-components/rectangle.js +1 -1
  135. package/dist/src/slide-components/rectangle.js.map +1 -1
  136. package/dist/src/slide-components/registry.js.map +1 -1
  137. package/dist/src/slide-components/serialize.d.ts.map +1 -1
  138. package/dist/src/slide-components/serialize.js +2 -1
  139. package/dist/src/slide-components/serialize.js.map +1 -1
  140. package/dist/src/slide-components/split-video-clip.d.ts.map +1 -1
  141. package/dist/src/slide-components/split-video-clip.js +4 -1
  142. package/dist/src/slide-components/split-video-clip.js.map +1 -1
  143. package/dist/src/slide-components/video-clip.d.ts.map +1 -1
  144. package/dist/src/slide-components/video-clip.js +7 -4
  145. package/dist/src/slide-components/video-clip.js.map +1 -1
  146. package/dist/src/slide-components/video-info.d.ts.map +1 -1
  147. package/dist/src/slide-components/video-info.js.map +1 -1
  148. package/dist/src/slow-image-sources.d.ts.map +1 -1
  149. package/dist/src/slow-image-sources.js +1 -1
  150. package/dist/src/slow-image-sources.js.map +1 -1
  151. package/dist/src/snapshot.d.ts.map +1 -1
  152. package/dist/src/snapshot.js +1 -1
  153. package/dist/src/snapshot.js.map +1 -1
  154. package/dist/src/utility.d.ts.map +1 -1
  155. package/dist/src/utility.js +1 -3
  156. package/dist/src/utility.js.map +1 -1
  157. package/lib/main-control.ts +3 -1
  158. package/package.json +4 -1
  159. package/src/corner-rounder.ts +5 -12
  160. package/src/glib/letters-base.ts +1 -1
  161. package/src/local-files.ts +19 -6
  162. package/src/peano-fourier/fourier-shared.ts +8 -1
  163. package/src/slide-components/fourier.ts +32 -10
  164. package/src/slide-components/image.ts +4 -1
  165. package/src/slide-components/in-parallel.ts +1 -2
  166. package/src/slide-components/multi-text.ts +17 -4
  167. package/src/slide-components/rectangle.ts +4 -1
  168. package/src/slide-components/registry.ts +1 -1
  169. package/src/slide-components/serialize.ts +4 -1
  170. package/src/slide-components/split-video-clip.ts +4 -1
  171. package/src/slide-components/video-clip.ts +21 -8
  172. package/src/slide-components/video-info.ts +4 -1
  173. package/src/slow-image-sources.ts +5 -1
  174. package/src/snapshot.ts +13 -4
  175. package/src/utility.ts +70 -33
@@ -8,7 +8,10 @@ import {
8
8
  TranscribeProgress,
9
9
  } from "./transcribe-core.ts";
10
10
  import type { TranscriptWord } from "./transcript-align.ts";
11
- import type { TranscribeReply, TranscribeRequest } from "./transcribe-worker.ts";
11
+ import type {
12
+ TranscribeReply,
13
+ TranscribeRequest,
14
+ } from "./transcribe-worker.ts";
12
15
 
13
16
  /**
14
17
  * Word-by-word transcripts of sound files, for the timeline.
@@ -123,6 +126,17 @@ export function transcriptStatus(url: string): TranscriptStatus | undefined {
123
126
  return waiting;
124
127
  }
125
128
 
129
+ /**
130
+ * Try the files that couldn't be read again, e.g. after 🔓 Allow local files.
131
+ * Each one is asked about again as it's drawn.
132
+ */
133
+ export function forgetTranscriptFailures(): void {
134
+ for (const [url, status] of statuses) {
135
+ if (status.kind === "failed") statuses.delete(url);
136
+ }
137
+ changed();
138
+ }
139
+
126
140
  /** The finished transcript of `url`, if there is one. Never starts any work. */
127
141
  export function readyTranscript(url: string): Transcript | undefined {
128
142
  const status = statuses.get(url);
@@ -143,7 +157,9 @@ export function transcriptsSummary(): string {
143
157
  : "reading the file";
144
158
  return `${name}: ${progress}${more}`;
145
159
  }
146
- const failed = [...statuses.values()].filter((s) => s.kind === "failed").length;
160
+ const failed = [...statuses.values()].filter(
161
+ (s) => s.kind === "failed",
162
+ ).length;
147
163
  return failed ? `${failed} failed (see the Debug Log)` : "";
148
164
  }
149
165
 
@@ -186,12 +202,29 @@ async function pump(): Promise<void> {
186
202
  }
187
203
  }
188
204
 
189
- /** From the cache, or made now and cached. */
205
+ /**
206
+ * From the cache, or made now and cached.
207
+ *
208
+ * If the file can't be read now (no permission yet, or it's gone), the newest transcript
209
+ * of that URL instead, if there is one. It isn't checked against the file, even after the
210
+ * file can be read again, until the page reloads.
211
+ */
190
212
  async function transcriptFor(
191
213
  url: string,
192
214
  onProgress: (progress: TranscribeProgress) => void,
193
215
  ): Promise<Transcript> {
194
- const key = await cacheKey(url);
216
+ let key: string;
217
+ try {
218
+ key = await cacheKey(url);
219
+ } catch (error) {
220
+ const newest = await newestCached(url);
221
+ if (!newest) throw error;
222
+ debugLog(
223
+ "transcripts",
224
+ `Using the last transcript of "${url}" without checking the file: ${String(error).replace(/^Error:\s*/, "")}`,
225
+ );
226
+ return newest;
227
+ }
195
228
  const cached = await readCache(key);
196
229
  if (cached) return cached;
197
230
  const transcript = await makeTranscript(url, onProgress);
@@ -223,7 +256,8 @@ export async function makeTranscript(
223
256
  /** The file at `url` as 16 kHz mono, the way the models want it. */
224
257
  async function decode(url: string): Promise<Float32Array> {
225
258
  const response = await fetchMedia(url);
226
- if (!response.ok) throw new Error(`${response.status} ${response.statusText}`);
259
+ if (!response.ok)
260
+ throw new Error(`${response.status} ${response.statusText}`);
227
261
  // decodeAudioData resamples to its context's rate, which does the 16 kHz part.
228
262
  const context = new OfflineAudioContext(1, 1, SAMPLE_RATE);
229
263
  const audio = await context.decodeAudioData(await response.arrayBuffer());
@@ -231,7 +265,8 @@ async function decode(url: string): Promise<Float32Array> {
231
265
  const mono = new Float32Array(audio.length);
232
266
  for (let channel = 0; channel < audio.numberOfChannels; channel++) {
233
267
  const data = audio.getChannelData(channel);
234
- for (let i = 0; i < mono.length; i++) mono[i] += data[i] / audio.numberOfChannels;
268
+ for (let i = 0; i < mono.length; i++)
269
+ mono[i] += data[i] / audio.numberOfChannels;
235
270
  }
236
271
  return mono;
237
272
  }
@@ -260,20 +295,23 @@ function runWorker(
260
295
  worker = new Worker(new URL("./transcribe-worker.js", import.meta.url), {
261
296
  type: "module",
262
297
  });
263
- worker.addEventListener("message", (event: MessageEvent<TranscribeReply>) => {
264
- const reply = event.data;
265
- const job = pending.get(reply.id);
266
- if (!job) return;
267
- if (reply.kind === "progress") {
268
- job.onProgress?.(reply.progress);
269
- } else if (reply.kind === "done") {
270
- pending.delete(reply.id);
271
- job.resolve(reply);
272
- } else {
273
- pending.delete(reply.id);
274
- job.reject(new Error(reply.message));
275
- }
276
- });
298
+ worker.addEventListener(
299
+ "message",
300
+ (event: MessageEvent<TranscribeReply>) => {
301
+ const reply = event.data;
302
+ const job = pending.get(reply.id);
303
+ if (!job) return;
304
+ if (reply.kind === "progress") {
305
+ job.onProgress?.(reply.progress);
306
+ } else if (reply.kind === "done") {
307
+ pending.delete(reply.id);
308
+ job.resolve(reply);
309
+ } else {
310
+ pending.delete(reply.id);
311
+ job.reject(new Error(reply.message));
312
+ }
313
+ },
314
+ );
277
315
  worker.addEventListener("error", (event) => {
278
316
  for (const job of pending.values()) job.reject(new Error(event.message));
279
317
  pending.clear();
@@ -304,10 +342,10 @@ type CacheRecord = Transcript & { readonly key: string; readonly url: string };
304
342
  * save. Only a server that sends none of those headers gets its files hashed.
305
343
  */
306
344
  async function cacheKey(url: string): Promise<string> {
307
- const absolute = new URL(url, location.href).href;
308
- const prefix = `${PIPELINE_VERSION}|${MODELS.whisper}|${absolute}|`;
345
+ const prefix = keyPrefix(url);
309
346
  // For a local file, fetchMedia() answers with its size and modification time.
310
347
  const head = await fetchMedia(url, { method: "HEAD", cache: "no-cache" });
348
+ if (!head.ok) throw new Error(`${head.status} ${head.statusText}`);
311
349
  const etag = head.headers.get("etag");
312
350
  const modified = head.headers.get("last-modified");
313
351
  const length = head.headers.get("content-length");
@@ -315,7 +353,33 @@ async function cacheKey(url: string): Promise<string> {
315
353
  if (modified && length) return `${prefix}${modified} ${length}`;
316
354
  const bytes = await (await fetchMedia(url)).arrayBuffer();
317
355
  const digest = new Uint8Array(await crypto.subtle.digest("SHA-256", bytes));
318
- return prefix + Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
356
+ return (
357
+ prefix + Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("")
358
+ );
359
+ }
360
+
361
+ /** Every {@link cacheKey} of this URL starts with this: everything but the file's fingerprint. */
362
+ function keyPrefix(url: string): string {
363
+ return `${PIPELINE_VERSION}|${MODELS.whisper}|${new URL(url, location.href).href}|`;
364
+ }
365
+
366
+ /** The newest transcript of this URL, whatever the file's fingerprint was then. */
367
+ async function newestCached(url: string): Promise<Transcript | undefined> {
368
+ const prefix = keyPrefix(url);
369
+ const db = await openDb();
370
+ const records = await new Promise<CacheRecord[]>((resolve, reject) => {
371
+ const request = db
372
+ .transaction(STORE)
373
+ .objectStore(STORE)
374
+ .getAll(IDBKeyRange.bound(prefix, prefix + "￿"));
375
+ request.onsuccess = () => resolve(request.result as CacheRecord[]);
376
+ request.onerror = () => reject(request.error);
377
+ });
378
+ return records.reduce<CacheRecord | undefined>(
379
+ (newest, record) =>
380
+ newest && newest.madeAt >= record.madeAt ? newest : record,
381
+ undefined,
382
+ );
319
383
  }
320
384
 
321
385
  let dbPromise: Promise<IDBDatabase> | undefined;
@@ -335,16 +399,23 @@ async function readCache(key: string): Promise<Transcript | undefined> {
335
399
  const db = await openDb();
336
400
  return new Promise((resolve, reject) => {
337
401
  const request = db.transaction(STORE).objectStore(STORE).get(key);
338
- request.onsuccess = () => resolve(request.result as CacheRecord | undefined);
402
+ request.onsuccess = () =>
403
+ resolve(request.result as CacheRecord | undefined);
339
404
  request.onerror = () => reject(request.error);
340
405
  });
341
406
  }
342
407
 
343
- async function writeCache(key: string, url: string, transcript: Transcript): Promise<void> {
408
+ async function writeCache(
409
+ key: string,
410
+ url: string,
411
+ transcript: Transcript,
412
+ ): Promise<void> {
344
413
  const db = await openDb();
345
414
  return new Promise((resolve, reject) => {
346
415
  const transaction = db.transaction(STORE, "readwrite");
347
- transaction.objectStore(STORE).put({ ...transcript, key, url } satisfies CacheRecord);
416
+ transaction
417
+ .objectStore(STORE)
418
+ .put({ ...transcript, key, url } satisfies CacheRecord);
348
419
  transaction.oncomplete = () => resolve();
349
420
  transaction.onerror = () => reject(transaction.error);
350
421
  });
@@ -13,7 +13,11 @@ import {
13
13
  shrinkToAspect,
14
14
  VideoInfo,
15
15
  } from "../src/slide-components/video-info.ts";
16
- import { ALIGN_HORIZONTALLY, ALIGN_VERTICALLY, buildSnapRow } from "./rect-snap.ts";
16
+ import {
17
+ ALIGN_HORIZONTALLY,
18
+ ALIGN_VERTICALLY,
19
+ buildSnapRow,
20
+ } from "./rect-snap.ts";
17
21
  import { buildLocalFileRow } from "./local-file-row.ts";
18
22
  import {
19
23
  LocalFileError,
@@ -86,7 +90,8 @@ function quietError(error: unknown): string {
86
90
  if (error instanceof LocalFileError) return error.message;
87
91
  const text = String(error);
88
92
  if (/404|not found|Failed to fetch/i.test(text)) return "Not found";
89
- if (/unsupported|unrecognized|format/i.test(text)) return "Not a video file this can read";
93
+ if (/unsupported|unrecognized|format/i.test(text))
94
+ return "Not a video file this can read";
90
95
  return text.replace(/^Error:\s*/, "");
91
96
  }
92
97
 
@@ -245,7 +250,10 @@ export function buildVideoClipPanel(
245
250
 
246
251
  const statusEl = line(panel, "font-weight:bold;margin-bottom:0.2em");
247
252
  const statsEl = line(panel, "font-size:0.9em;line-height:1.4");
248
- const derivedEl = line(panel, "font-size:0.9em;line-height:1.4;margin-top:0.3em");
253
+ const derivedEl = line(
254
+ panel,
255
+ "font-size:0.9em;line-height:1.4;margin-top:0.3em",
256
+ );
249
257
 
250
258
  const timingRow = line(panel, "margin-top:0.5em");
251
259
  const WHOLE_FILE_TITLE =
@@ -266,17 +274,23 @@ export function buildVideoClipPanel(
266
274
  const SIZE_VIDEO_TITLE =
267
275
  "Make the whole video exactly this clip's size, in pixels, and fill it with this clip, " +
268
276
  "one video pixel per output pixel. The units stay as wide as they are now.";
269
- const sizeVideoBtn = button(rectRow, "Make video this size", SIZE_VIDEO_TITLE);
277
+ const sizeVideoBtn = button(
278
+ rectRow,
279
+ "Make video this size",
280
+ SIZE_VIDEO_TITLE,
281
+ );
270
282
  const rectButtons = [
271
283
  {
272
284
  text: "Fit canvas",
273
- title: "As large as possible while the whole video stays on the canvas. Centered.",
285
+ title:
286
+ "As large as possible while the whole video stays on the canvas. Centered.",
274
287
  make: (info: VideoInfo) =>
275
288
  centeredOnCanvas(maxFit(info.video.width, info.video.height)),
276
289
  },
277
290
  {
278
291
  text: "Cover canvas",
279
- title: "Just large enough to cover the whole canvas. Some of the video will be off screen. Centered.",
292
+ title:
293
+ "Just large enough to cover the whole canvas. Some of the video will be off screen. Centered.",
280
294
  make: (info: VideoInfo) =>
281
295
  centeredOnCanvas(minCover(info.video.width, info.video.height)),
282
296
  },
@@ -288,11 +302,15 @@ export function buildVideoClipPanel(
288
302
  },
289
303
  {
290
304
  text: "Shrink to video",
291
- title: "Shrink the rectangle to the area the video actually covers inside it, so the handles hug the picture.",
305
+ title:
306
+ "Shrink the rectangle to the area the video actually covers inside it, so the handles hug the picture.",
292
307
  make: (info: VideoInfo, rect: ReadOnlyRect) =>
293
308
  shrinkToAspect(rect, info.video.width / info.video.height),
294
309
  },
295
- ].map(({ text, title, make }) => ({ btn: button(rectRow, text, title), make }));
310
+ ].map(({ text, title, make }) => ({
311
+ btn: button(rectRow, text, title),
312
+ make,
313
+ }));
296
314
 
297
315
  /**
298
316
  * Snap one edge of the Dest Rect to the canvas, or center it, keeping its
@@ -323,7 +341,11 @@ export function buildVideoClipPanel(
323
341
  audioStatusEl.style.marginRight = "0.5em";
324
342
  audioRow.append(audioStatusEl);
325
343
  const importBtn = button(audioRow, "Import audio", "");
326
- const removeAudioBtn = button(audioRow, "Remove", "Remove the audio this panel imported.");
344
+ const removeAudioBtn = button(
345
+ audioRow,
346
+ "Remove",
347
+ "Remove the audio this panel imported.",
348
+ );
327
349
 
328
350
  /** The last answer we got from the file, or why there isn't one. */
329
351
  let info: VideoInfo | undefined;
@@ -407,7 +429,10 @@ export function buildVideoClipPanel(
407
429
  if (ready) {
408
430
  const fileMs = info!.durationMs;
409
431
  if (end > fileMs + 0.5) {
410
- add(`End is past the end of the file (${Math.round(fileMs)} ms).`, "#a06000");
432
+ add(
433
+ `End is past the end of the file (${Math.round(fileMs)} ms).`,
434
+ "#a06000",
435
+ );
411
436
  } else if (fileMs > 0) {
412
437
  const used = (Math.max(0, Math.max(start, end) - start) / fileMs) * 100;
413
438
  add(`Using ${used.toFixed(used < 10 ? 1 : 0)}% of the file.`);
@@ -433,7 +458,9 @@ export function buildVideoClipPanel(
433
458
 
434
459
  const splitProblem = hooks.splitProblem();
435
460
  splitBtn.disabled = splitProblem !== undefined;
436
- splitBtn.title = splitProblem ? `${SPLIT_TITLE}\n\n${splitProblem}` : SPLIT_TITLE;
461
+ splitBtn.title = splitProblem
462
+ ? `${SPLIT_TITLE}\n\n${splitProblem}`
463
+ : SPLIT_TITLE;
437
464
  wholeFileBtn.disabled = !ready;
438
465
  realTimeBtn.hidden = Number.isNaN(speed) || isRealTime(speed);
439
466
  realTimeBtn.disabled = !(end > start);
@@ -473,13 +500,22 @@ export function buildVideoClipPanel(
473
500
  if (state !== "ready" || !info) {
474
501
  setStatus(imported.length ? "Audio: imported" : "Audio:");
475
502
  importBtn.disabled = true;
476
- importBtn.textContent = imported.length ? "Re-import audio" : "Import audio";
503
+ importBtn.textContent = imported.length
504
+ ? "Re-import audio"
505
+ : "Import audio";
477
506
  return;
478
507
  }
479
508
  const audio = info.audio;
480
- importBtn.textContent = imported.length ? "Re-import audio" : "Import audio";
509
+ importBtn.textContent = imported.length
510
+ ? "Re-import audio"
511
+ : "Import audio";
481
512
  if (!audio) {
482
- setStatus(imported.length ? "Audio: imported, but this file has none" : "No audio track", "#888");
513
+ setStatus(
514
+ imported.length
515
+ ? "Audio: imported, but this file has none"
516
+ : "No audio track",
517
+ "#888",
518
+ );
483
519
  importBtn.disabled = true;
484
520
  importBtn.title = "This file has no audio track.";
485
521
  return;
@@ -487,7 +523,10 @@ export function buildVideoClipPanel(
487
523
  if (!isRealTime(speed)) {
488
524
  // The soundtrack can't change the speed of a sound, so anything but 1×
489
525
  // would drift out of sync.
490
- setStatus(`Audio needs 1× — currently ${Number.isNaN(speed) ? "—" : formatSpeed(speed)}`, "#a06000");
526
+ setStatus(
527
+ `Audio needs 1× — currently ${Number.isNaN(speed) ? "—" : formatSpeed(speed)}`,
528
+ "#a06000",
529
+ );
491
530
  importBtn.disabled = true;
492
531
  importBtn.title = "Click Play at 1× first.";
493
532
  return;
@@ -501,7 +540,8 @@ export function buildVideoClipPanel(
501
540
  setStatus("");
502
541
  } else if (imported.length > 1) {
503
542
  setStatus("Audio imported, then cut into pieces");
504
- importBtn.title += "\n\nRe-import replaces the pieces with one sound clip, lined up with the picture.";
543
+ importBtn.title +=
544
+ "\n\nRe-import replaces the pieces with one sound clip, lined up with the picture.";
505
545
  } else if (sameSoundClip(imported[0], expected)) {
506
546
  setStatus("Audio imported ✓", "#070");
507
547
  } else {
@@ -593,7 +633,12 @@ export function buildVideoClipPanel(
593
633
  const unitsPerPixel = width / pixelWidth;
594
634
  return {
595
635
  size: { pixelWidth, pixelHeight, width, height },
596
- rect: { x: 0, y: 0, width: videoWidth * unitsPerPixel, height: videoHeight * unitsPerPixel },
636
+ rect: {
637
+ x: 0,
638
+ y: 0,
639
+ width: videoWidth * unitsPerPixel,
640
+ height: videoHeight * unitsPerPixel,
641
+ },
597
642
  };
598
643
  }
599
644
 
@@ -603,7 +648,8 @@ export function buildVideoClipPanel(
603
648
  // Several keyframes and none chosen: clicking explains that, so keep the button enabled.
604
649
  if (typeof target === "string") return false;
605
650
  const { size, rect } = clipSize(info);
606
- const close = (a: number, b: number) => Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(b));
651
+ const close = (a: number, b: number) =>
652
+ Math.abs(a - b) <= 1e-6 * Math.max(1, Math.abs(b));
607
653
  const current = canvasRecorder.size;
608
654
  return (
609
655
  current.pixelWidth === size.pixelWidth &&
@@ -36,7 +36,8 @@ function sweepSamples({ from, to, seconds }: Sweep, sampleRate: number) {
36
36
  const k = Math.log(to / from);
37
37
  for (let i = 0; i < count; i++) {
38
38
  const t = i / sampleRate;
39
- const phase = (2 * Math.PI * from * seconds * (Math.exp((t * k) / seconds) - 1)) / k;
39
+ const phase =
40
+ (2 * Math.PI * from * seconds * (Math.exp((t * k) / seconds) - 1)) / k;
40
41
  samples[i] = AMPLITUDE * Math.sin(phase);
41
42
  }
42
43
  const fade = Math.min(count / 2, Math.round(FADE_SECONDS * sampleRate));
@@ -78,7 +79,9 @@ export function findSound(
78
79
  for (let i = 0; i < sound.length; i += step) {
79
80
  sum += sound[i] * recording[lag + i];
80
81
  }
81
- const norm = Math.sqrt(energy(recording, lag, sound.length, step) * (soundEnergy / step));
82
+ const norm = Math.sqrt(
83
+ energy(recording, lag, sound.length, step) * (soundEnergy / step),
84
+ );
82
85
  return norm > 0 ? sum / norm : 0;
83
86
  };
84
87
  // Coarse: every 4th lag, every 4th sample.
@@ -93,7 +96,11 @@ export function findSound(
93
96
  }
94
97
  // Exact: every lag near the best one, every sample.
95
98
  const exact = new Map<number, number>();
96
- for (let lag = Math.max(first, best - 6); lag <= Math.min(last, best + 6); lag++) {
99
+ for (
100
+ let lag = Math.max(first, best - 6);
101
+ lag <= Math.min(last, best + 6);
102
+ lag++
103
+ ) {
97
104
  exact.set(lag, score(lag, 1));
98
105
  }
99
106
  for (const [lag, s] of exact) {
@@ -116,10 +123,19 @@ export function findSound(
116
123
  for (let i = best; i < best + sound.length; i++) {
117
124
  peak = Math.max(peak, Math.abs(recording[i]));
118
125
  }
119
- return { position, match: Math.max(0, here), peakDb: 20 * Math.log10(peak || 1e-12) };
126
+ return {
127
+ position,
128
+ match: Math.max(0, here),
129
+ peakDb: 20 * Math.log10(peak || 1e-12),
130
+ };
120
131
  }
121
132
 
122
- function energy(samples: Float32Array, start: number, length: number, step: number) {
133
+ function energy(
134
+ samples: Float32Array,
135
+ start: number,
136
+ length: number,
137
+ step: number,
138
+ ) {
123
139
  let sum = 0;
124
140
  for (let i = 0; i < length; i += step) {
125
141
  const v = samples[start + i];
@@ -27,7 +27,9 @@ function inStore<T>(
27
27
  open.onupgradeneeded = () => open.result.createObjectStore(STORE);
28
28
  open.onerror = () => reject(open.error);
29
29
  open.onsuccess = () => {
30
- const request = run(open.result.transaction(STORE, mode).objectStore(STORE));
30
+ const request = run(
31
+ open.result.transaction(STORE, mode).objectStore(STORE),
32
+ );
31
33
  request.onsuccess = () => resolve(request.result);
32
34
  request.onerror = () => reject(request.error);
33
35
  };
@@ -35,7 +37,9 @@ function inStore<T>(
35
37
  }
36
38
 
37
39
  /** The folder chosen last time, if there is one. */
38
- export async function rememberedFolder(): Promise<FileSystemDirectoryHandle | undefined> {
40
+ export async function rememberedFolder(): Promise<
41
+ FileSystemDirectoryHandle | undefined
42
+ > {
39
43
  try {
40
44
  return await inStore("readonly", (store) => store.get(KEY));
41
45
  } catch {
@@ -44,15 +48,21 @@ export async function rememberedFolder(): Promise<FileSystemDirectoryHandle | un
44
48
  }
45
49
 
46
50
  /** Save recordings here from now on. */
47
- export async function rememberFolder(folder: FileSystemDirectoryHandle): Promise<void> {
51
+ export async function rememberFolder(
52
+ folder: FileSystemDirectoryHandle,
53
+ ): Promise<void> {
48
54
  await inStore("readwrite", (store) => store.put(folder, KEY));
49
55
  }
50
56
 
51
57
  /** Ask the user for a folder. Undefined if they cancel. Call this from a click. */
52
- export async function chooseFolder(): Promise<FileSystemDirectoryHandle | undefined> {
58
+ export async function chooseFolder(): Promise<
59
+ FileSystemDirectoryHandle | undefined
60
+ > {
53
61
  const picker = (
54
62
  window as unknown as {
55
- showDirectoryPicker?: (options: object) => Promise<FileSystemDirectoryHandle>;
63
+ showDirectoryPicker?: (
64
+ options: object,
65
+ ) => Promise<FileSystemDirectoryHandle>;
56
66
  }
57
67
  ).showDirectoryPicker;
58
68
  if (!picker) {
@@ -71,7 +81,10 @@ export async function chooseFolder(): Promise<FileSystemDirectoryHandle | undefi
71
81
  }
72
82
 
73
83
  /** Can we write to this folder? If ask is true, ask for permission if we need it. That needs a click. */
74
- export async function canWrite(folder: FileSystemDirectoryHandle, ask: boolean): Promise<boolean> {
84
+ export async function canWrite(
85
+ folder: FileSystemDirectoryHandle,
86
+ ask: boolean,
87
+ ): Promise<boolean> {
75
88
  const handle = folder as WithPermission;
76
89
  // Folders that don't need permission, like the browser's private storage, don't have these.
77
90
  if (!handle.queryPermission || !handle.requestPermission) {
@@ -80,5 +93,7 @@ export async function canWrite(folder: FileSystemDirectoryHandle, ask: boolean):
80
93
  if ((await handle.queryPermission({ mode: "readwrite" })) == "granted") {
81
94
  return true;
82
95
  }
83
- return ask && (await handle.requestPermission({ mode: "readwrite" })) == "granted";
96
+ return (
97
+ ask && (await handle.requestPermission({ mode: "readwrite" })) == "granted"
98
+ );
84
99
  }