canvas-recorder-lib 0.7.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -99,6 +99,7 @@ import {
99
99
  type TimelineWord,
100
100
  } from "./timeline-display.ts";
101
101
  import {
102
+ forgetTranscriptFailures,
102
103
  forgetTranscripts,
103
104
  makeTranscript,
104
105
  onTranscriptsChange,
@@ -476,6 +477,7 @@ async function allowLocalFiles() {
476
477
  await requestLocalFileAccess();
477
478
  // The images and video clips try again by themselves.
478
479
  soundtrack.forgetFailures();
480
+ forgetTranscriptFailures();
479
481
  }
480
482
  localFilesBtn.addEventListener("click", () => void allowLocalFiles());
481
483
 
@@ -3880,11 +3882,6 @@ function currentSaveTarget(): Showable | null {
3880
3882
  }
3881
3883
 
3882
3884
  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();
3887
-
3888
3885
  // When the history dialog is open the live tree may hold a transient preview from
3889
3886
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
3890
3887
  // persisted as if the user had accepted it.
@@ -8085,12 +8082,30 @@ if (import.meta.hot) {
8085
8082
  // Changing a typescript file invokes this.
8086
8083
  // Changing a css file would cause vite:beforeUpdate, instead.
8087
8084
  import.meta.hot.on("vite:beforeFullReload", (_data) => {
8085
+ finishVoiceOnUnload();
8088
8086
  saveState();
8089
8087
  saveOnUnload();
8090
8088
  });
8091
8089
  }
8092
8090
 
8093
- window.addEventListener("beforeunload", saveOnUnload);
8091
+ /**
8092
+ * Start closing any voice recording's files. They may not finish in time.
8093
+ *
8094
+ * Only when the page is really going away. Not on visibilitychange: a page is hidden by
8095
+ * another tab, another app or another desktop, often to read a script, and the recording
8096
+ * should keep going.
8097
+ *
8098
+ * TODO: test this, and add the clip being recorded before {@link saveOnUnload}'s backup.
8099
+ * See "Risks" in development-plans/voice-recording.md.
8100
+ */
8101
+ function finishVoiceOnUnload() {
8102
+ voicePanel?.recorder.flush();
8103
+ }
8104
+
8105
+ window.addEventListener("beforeunload", () => {
8106
+ finishVoiceOnUnload();
8107
+ saveOnUnload();
8108
+ });
8094
8109
  document.addEventListener("visibilitychange", () => {
8095
8110
  if (document.visibilityState === "hidden") saveOnUnload();
8096
8111
  });
package/dev/soundtrack.ts CHANGED
@@ -139,7 +139,7 @@ export class Soundtrack {
139
139
  this.#decoded.clear();
140
140
  this.#failed.clear();
141
141
  this.#knownSources.clear();
142
- this.request();
142
+ this.#loadAgain();
143
143
  }
144
144
 
145
145
  /**
@@ -160,6 +160,12 @@ export class Soundtrack {
160
160
  forgetFailures(): void {
161
161
  for (const url of this.#failed) this.#decoding.delete(url);
162
162
  this.#failed.clear();
163
+ this.#loadAgain();
164
+ }
165
+
166
+ /** Load every clip's file that isn't loaded or loading. {@link request} skips that when no clip moved. */
167
+ #loadAgain(): void {
168
+ this.#clipsJson = "";
163
169
  this.request();
164
170
  }
165
171
 
@@ -191,13 +197,15 @@ export class Soundtrack {
191
197
  const time1 = performance.now();
192
198
  const response = await fetchMedia(url);
193
199
  const encoded = await response.arrayBuffer();
200
+ // Before decoding: decodeAudioData() detaches the buffer, so it reads as 0 bytes after.
201
+ const bytes = encoded.byteLength;
194
202
  const time2 = performance.now();
195
203
  // decodeAudioData() takes about ⅜ - ¾ of a second to decode 4 minutes and 18 seconds of audio.
196
204
  const decoded = await this.#decoder.decodeAudioData(encoded);
197
205
  const time3 = performance.now();
198
206
  debugLog(
199
207
  "audio",
200
- `Decoded "${url}": ${(encoded.byteLength / 1024).toFixed(0)} KB, ` +
208
+ `Decoded "${url}": ${(bytes / 1024).toFixed(0)} KB, ` +
201
209
  `read ${(time2 - time1).toFixed(0)} ms, decode ${(time3 - time2).toFixed(0)} ms`,
202
210
  );
203
211
  if (decoded.numberOfChannels === 1) return decoded;
@@ -123,6 +123,17 @@ export function transcriptStatus(url: string): TranscriptStatus | undefined {
123
123
  return waiting;
124
124
  }
125
125
 
126
+ /**
127
+ * Try the files that couldn't be read again, e.g. after 🔓 Allow local files.
128
+ * Each one is asked about again as it's drawn.
129
+ */
130
+ export function forgetTranscriptFailures(): void {
131
+ for (const [url, status] of statuses) {
132
+ if (status.kind === "failed") statuses.delete(url);
133
+ }
134
+ changed();
135
+ }
136
+
126
137
  /** The finished transcript of `url`, if there is one. Never starts any work. */
127
138
  export function readyTranscript(url: string): Transcript | undefined {
128
139
  const status = statuses.get(url);
@@ -186,12 +197,29 @@ async function pump(): Promise<void> {
186
197
  }
187
198
  }
188
199
 
189
- /** From the cache, or made now and cached. */
200
+ /**
201
+ * From the cache, or made now and cached.
202
+ *
203
+ * If the file can't be read now (no permission yet, or it's gone), the newest transcript
204
+ * of that URL instead, if there is one. It isn't checked against the file, even after the
205
+ * file can be read again, until the page reloads.
206
+ */
190
207
  async function transcriptFor(
191
208
  url: string,
192
209
  onProgress: (progress: TranscribeProgress) => void,
193
210
  ): Promise<Transcript> {
194
- const key = await cacheKey(url);
211
+ let key: string;
212
+ try {
213
+ key = await cacheKey(url);
214
+ } catch (error) {
215
+ const newest = await newestCached(url);
216
+ if (!newest) throw error;
217
+ debugLog(
218
+ "transcripts",
219
+ `Using the last transcript of "${url}" without checking the file: ${String(error).replace(/^Error:\s*/, "")}`,
220
+ );
221
+ return newest;
222
+ }
195
223
  const cached = await readCache(key);
196
224
  if (cached) return cached;
197
225
  const transcript = await makeTranscript(url, onProgress);
@@ -304,10 +332,10 @@ type CacheRecord = Transcript & { readonly key: string; readonly url: string };
304
332
  * save. Only a server that sends none of those headers gets its files hashed.
305
333
  */
306
334
  async function cacheKey(url: string): Promise<string> {
307
- const absolute = new URL(url, location.href).href;
308
- const prefix = `${PIPELINE_VERSION}|${MODELS.whisper}|${absolute}|`;
335
+ const prefix = keyPrefix(url);
309
336
  // For a local file, fetchMedia() answers with its size and modification time.
310
337
  const head = await fetchMedia(url, { method: "HEAD", cache: "no-cache" });
338
+ if (!head.ok) throw new Error(`${head.status} ${head.statusText}`);
311
339
  const etag = head.headers.get("etag");
312
340
  const modified = head.headers.get("last-modified");
313
341
  const length = head.headers.get("content-length");
@@ -318,6 +346,29 @@ async function cacheKey(url: string): Promise<string> {
318
346
  return prefix + Array.from(digest, (b) => b.toString(16).padStart(2, "0")).join("");
319
347
  }
320
348
 
349
+ /** Every {@link cacheKey} of this URL starts with this: everything but the file's fingerprint. */
350
+ function keyPrefix(url: string): string {
351
+ return `${PIPELINE_VERSION}|${MODELS.whisper}|${new URL(url, location.href).href}|`;
352
+ }
353
+
354
+ /** The newest transcript of this URL, whatever the file's fingerprint was then. */
355
+ async function newestCached(url: string): Promise<Transcript | undefined> {
356
+ const prefix = keyPrefix(url);
357
+ const db = await openDb();
358
+ const records = await new Promise<CacheRecord[]>((resolve, reject) => {
359
+ const request = db
360
+ .transaction(STORE)
361
+ .objectStore(STORE)
362
+ .getAll(IDBKeyRange.bound(prefix, prefix + "￿"));
363
+ request.onsuccess = () => resolve(request.result as CacheRecord[]);
364
+ request.onerror = () => reject(request.error);
365
+ });
366
+ return records.reduce<CacheRecord | undefined>(
367
+ (newest, record) => (newest && newest.madeAt >= record.madeAt ? newest : record),
368
+ undefined,
369
+ );
370
+ }
371
+
321
372
  let dbPromise: Promise<IDBDatabase> | undefined;
322
373
  function openDb(): Promise<IDBDatabase> {
323
374
  dbPromise ??= new Promise((resolve, reject) => {
@@ -287,7 +287,7 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
287
287
  );
288
288
  const choicesBox = element("div");
289
289
  const micLine = element("div", "vr-small", "Turning on the mic…");
290
- const folderName = element("b", "", "not chosen yet");
290
+ const folderName = element("b", "", "…");
291
291
  const changeFolder = element("button", "", "Change…");
292
292
  changeFolder.style.padding = "0 6px";
293
293
  const folderLine = element("div", "vr-small", "Folder: ", folderName, " ", changeFolder);
@@ -329,6 +329,27 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
329
329
  options.onClose?.();
330
330
  };
331
331
 
332
+ // The folder. Independent of the mic, so it shows even if the mic is refused.
333
+ // Not awaited: the mic should start while this click still counts as a click.
334
+ let folder: FileSystemDirectoryHandle | undefined;
335
+ const showFolder = () => {
336
+ folderName.textContent = folder ? folder.name || "browser storage" : "not chosen yet";
337
+ };
338
+ void rememberedFolder().then((remembered) => {
339
+ // ??=, in case Change… or setFolder() got here first.
340
+ folder ??= remembered;
341
+ showFolder();
342
+ });
343
+ changeFolder.addEventListener("click", async () => {
344
+ changeFolder.blur();
345
+ try {
346
+ folder = (await chooseFolder()) ?? folder;
347
+ showFolder();
348
+ } catch (error) {
349
+ say(error instanceof Error ? error.message : String(error), true);
350
+ }
351
+ });
352
+
332
353
  let recorder: VoiceRecorder;
333
354
  try {
334
355
  recorder = await VoiceRecorder.open(options.context, loadChoices());
@@ -416,20 +437,6 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
416
437
  }
417
438
  showSettings();
418
439
 
419
- // The folder.
420
- let folder = await rememberedFolder();
421
- const folderTitle = () => (folder ? folder.name || "browser storage" : "not chosen yet");
422
- folderName.textContent = folderTitle();
423
- changeFolder.addEventListener("click", async () => {
424
- changeFolder.blur();
425
- try {
426
- folder = (await chooseFolder()) ?? folder;
427
- folderName.textContent = folderTitle();
428
- } catch (error) {
429
- say(error instanceof Error ? error.message : String(error), true);
430
- }
431
- });
432
-
433
440
  // What we heard of the chirp.
434
441
  recorder.onHeard = (result: HeardResult) => {
435
442
  if (result.roundTripMs === undefined) {
@@ -455,9 +462,11 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
455
462
  const seconds = Math.floor((performance.now() - started) / 1000);
456
463
  time.textContent = `${Math.floor(seconds / 60)}:${String(seconds % 60).padStart(2, "0")}`;
457
464
  };
465
+ /** What the button says: ■ Stop. That's what a click does, even if the two ever disagree. */
466
+ let showingStop = false;
458
467
  record.addEventListener("click", async () => {
459
468
  record.blur();
460
- if (recorder.recording) {
469
+ if (showingStop) {
461
470
  options.onStop();
462
471
  return;
463
472
  }
@@ -465,7 +474,7 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
465
474
  try {
466
475
  if (!folder || !(await canWrite(folder, true))) {
467
476
  folder = await chooseFolder();
468
- folderName.textContent = folderTitle();
477
+ showFolder();
469
478
  }
470
479
  if (!folder) {
471
480
  say("Choose a folder for the recordings first.", true);
@@ -483,6 +492,7 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
483
492
  const result: VoicePanel = {
484
493
  recorder,
485
494
  setRecording(on) {
495
+ showingStop = on;
486
496
  panel.classList.toggle("vr-recording", on);
487
497
  record.textContent = on ? "■ Stop" : "● Record";
488
498
  window.clearInterval(clock);
@@ -500,7 +510,7 @@ export async function openVoicePanel(options: VoicePanelOptions): Promise<VoiceP
500
510
  say,
501
511
  setFolder(newFolder) {
502
512
  folder = newFolder;
503
- folderName.textContent = folderTitle();
513
+ showFolder();
504
514
  },
505
515
  async close() {
506
516
  window.clearInterval(clock);
@@ -22,7 +22,7 @@ import { ownerOf, parseSoundClips, rehomeSoundClip, soundOwners, startWithin, ti
22
22
  import { askHowToSplit, askHowToSplitSound } from "./split-dialog.js";
23
23
  import { SyncedFile } from "./synced-file.js";
24
24
  import { TimelineDisplay, } from "./timeline-display.js";
25
- import { forgetTranscripts, makeTranscript, onTranscriptsChange, readyTranscript, setTranscriptsEnabled, statusText, transcriptsEnabled, transcriptStatus, transcriptsSummary, } from "./transcripts.js";
25
+ import { forgetTranscriptFailures, forgetTranscripts, makeTranscript, onTranscriptsChange, readyTranscript, setTranscriptsEnabled, statusText, transcriptsEnabled, transcriptStatus, transcriptsSummary, } from "./transcripts.js";
26
26
  import { transcriptFileName, transcriptJson } from "./transcript-export.js";
27
27
  import { wordFlag } from "./transcript-align.js";
28
28
  import { canvasRecorder } from "../lib/main-control.js";
@@ -336,6 +336,7 @@ async function allowLocalFiles() {
336
336
  await requestLocalFileAccess();
337
337
  // The images and video clips try again by themselves.
338
338
  soundtrack.forgetFailures();
339
+ forgetTranscriptFailures();
339
340
  }
340
341
  localFilesBtn.addEventListener("click", () => void allowLocalFiles());
341
342
  /**
@@ -3229,10 +3230,6 @@ function currentSaveTarget() {
3229
3230
  return selectable.schedules?.length ? selectable : null;
3230
3231
  }
3231
3232
  function saveOnUnload() {
3232
- // Start closing any voice recording's files. They may not finish in time.
3233
- // TODO: test this, and add the clip being recorded before the save below.
3234
- // See "Risks" in development-plans/voice-recording.md.
3235
- voicePanel?.recorder.flush();
3236
3233
  // When the history dialog is open the live tree may hold a transient preview from
3237
3234
  // _dialogSelectItem. Back up the pre-dialog state instead, so a preview is never
3238
3235
  // persisted as if the user had accepted it.
@@ -6990,11 +6987,28 @@ if (import.meta.hot) {
6990
6987
  // Changing a typescript file invokes this.
6991
6988
  // Changing a css file would cause vite:beforeUpdate, instead.
6992
6989
  import.meta.hot.on("vite:beforeFullReload", (_data) => {
6990
+ finishVoiceOnUnload();
6993
6991
  saveState();
6994
6992
  saveOnUnload();
6995
6993
  });
6996
6994
  }
6997
- window.addEventListener("beforeunload", saveOnUnload);
6995
+ /**
6996
+ * Start closing any voice recording's files. They may not finish in time.
6997
+ *
6998
+ * Only when the page is really going away. Not on visibilitychange: a page is hidden by
6999
+ * another tab, another app or another desktop, often to read a script, and the recording
7000
+ * should keep going.
7001
+ *
7002
+ * TODO: test this, and add the clip being recorded before {@link saveOnUnload}'s backup.
7003
+ * See "Risks" in development-plans/voice-recording.md.
7004
+ */
7005
+ function finishVoiceOnUnload() {
7006
+ voicePanel?.recorder.flush();
7007
+ }
7008
+ window.addEventListener("beforeunload", () => {
7009
+ finishVoiceOnUnload();
7010
+ saveOnUnload();
7011
+ });
6998
7012
  document.addEventListener("visibilitychange", () => {
6999
7013
  if (document.visibilityState === "hidden")
7000
7014
  saveOnUnload();