canvas-recorder-lib 0.6.0 → 0.7.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (62) hide show
  1. package/BREAKING-CHANGES.md +6 -0
  2. package/README.md +37 -23
  3. package/dev/audio-builder.ts +69 -163
  4. package/dev/canvas-recorder.ts +350 -169
  5. package/dev/player-body.ts +8 -0
  6. package/dev/sound-clips.ts +3 -2
  7. package/dev/soundtrack.ts +442 -0
  8. package/dev/transcripts.ts +55 -4
  9. package/dev/video-clip-panel.ts +1 -1
  10. package/dev/voice/chirp.ts +129 -0
  11. package/dev/voice/folder.ts +84 -0
  12. package/dev/voice/voice-panel.ts +523 -0
  13. package/dev/voice/voice-recorder.ts +603 -0
  14. package/dist/dev/audio-builder.d.ts +14 -31
  15. package/dist/dev/audio-builder.d.ts.map +1 -1
  16. package/dist/dev/audio-builder.js +62 -135
  17. package/dist/dev/audio-builder.js.map +1 -1
  18. package/dist/dev/canvas-recorder.js +336 -156
  19. package/dist/dev/canvas-recorder.js.map +1 -1
  20. package/dist/dev/player-body.d.ts +1 -1
  21. package/dist/dev/player-body.d.ts.map +1 -1
  22. package/dist/dev/player-body.js +8 -0
  23. package/dist/dev/player-body.js.map +1 -1
  24. package/dist/dev/sound-clips.d.ts +3 -2
  25. package/dist/dev/sound-clips.d.ts.map +1 -1
  26. package/dist/dev/sound-clips.js +3 -2
  27. package/dist/dev/sound-clips.js.map +1 -1
  28. package/dist/dev/soundtrack.d.ts +115 -0
  29. package/dist/dev/soundtrack.d.ts.map +1 -0
  30. package/dist/dev/soundtrack.js +376 -0
  31. package/dist/dev/soundtrack.js.map +1 -0
  32. package/dist/dev/transcripts.d.ts +5 -0
  33. package/dist/dev/transcripts.d.ts.map +1 -1
  34. package/dist/dev/transcripts.js +50 -4
  35. package/dist/dev/transcripts.js.map +1 -1
  36. package/dist/dev/video-clip-panel.js +1 -1
  37. package/dist/dev/video-clip-panel.js.map +1 -1
  38. package/dist/dev/voice/chirp.d.ts +27 -0
  39. package/dist/dev/voice/chirp.d.ts.map +1 -0
  40. package/dist/dev/voice/chirp.js +107 -0
  41. package/dist/dev/voice/chirp.js.map +1 -0
  42. package/dist/dev/voice/folder.d.ts +18 -0
  43. package/dist/dev/voice/folder.d.ts.map +1 -0
  44. package/dist/dev/voice/folder.js +68 -0
  45. package/dist/dev/voice/folder.js.map +1 -0
  46. package/dist/dev/voice/voice-panel.d.ts +44 -0
  47. package/dist/dev/voice/voice-panel.d.ts.map +1 -0
  48. package/dist/dev/voice/voice-panel.js +428 -0
  49. package/dist/dev/voice/voice-panel.js.map +1 -0
  50. package/dist/dev/voice/voice-recorder.d.ts +141 -0
  51. package/dist/dev/voice/voice-recorder.d.ts.map +1 -0
  52. package/dist/dev/voice/voice-recorder.js +506 -0
  53. package/dist/dev/voice/voice-recorder.js.map +1 -0
  54. package/dist/src/showable.d.ts +9 -0
  55. package/dist/src/showable.d.ts.map +1 -1
  56. package/dist/src/showable.js.map +1 -1
  57. package/dist/src/snapshot.d.ts.map +1 -1
  58. package/dist/src/snapshot.js +27 -11
  59. package/dist/src/snapshot.js.map +1 -1
  60. package/package.json +1 -1
  61. package/src/showable.ts +9 -0
  62. package/src/snapshot.ts +30 -15
@@ -191,8 +191,16 @@ export const playerBodyHtml = `
191
191
  <option value="2">2×</option>
192
192
  </select>
193
193
  </label>
194
+ <button
195
+ type="button"
196
+ id="recordModeBtn"
197
+ title="Show or hide the voice recorder. It turns the mic on while it's showing."
198
+ >
199
+ 🎙 Record mode
200
+ </button>
194
201
  </div>
195
202
  </fieldset>
203
+ <div id="voicePanelHolder"></div>
196
204
  <div
197
205
  style="
198
206
  border: 0.3em inset rgb(178, 178, 178);
@@ -26,8 +26,9 @@ function displayName(showable: Showable): string {
26
26
 
27
27
  /**
28
28
  * Every Showable under `root` (including `root`) whose `soundClips` is
29
- * defined, in tree order. That's what makes a Showable a place a sound can
30
- * live, even when its list is empty.
29
+ * defined, in tree order. Any Showable can hold sounds, but these are the
30
+ * ones that have a list, usually because they have, or had, a clip.
31
+ * That keeps the Owner menus short.
31
32
  *
32
33
  * This is the same walk the audio builder does, so the start times agree with
33
34
  * what you hear. A Showable that appears more than once in the tree is listed
@@ -0,0 +1,442 @@
1
+ /**
2
+ * The video's sound, live: every sound clip in the tree, each played by its own
3
+ * `AudioBufferSourceNode`, mixed by the browser.
4
+ *
5
+ * - **Decoded files are kept** for the life of the page, mixed down to mono.
6
+ * An edit never fetches or decodes a file again.
7
+ * - **An edit only touches the clips it changed.** {@link Soundtrack.request} is
8
+ * cheap enough to call on every mouse move: when no clip moved, it does nothing,
9
+ * and otherwise it replaces only the nodes whose clips changed. Everything else
10
+ * keeps playing, sample for sample.
11
+ * - **A file that isn't decoded yet doesn't hold anything up.** Its clips join in
12
+ * when it's ready.
13
+ * - **The saved video gets one mixed buffer,** from {@link Soundtrack.mix}, after
14
+ * {@link Soundtrack.ready}.
15
+ *
16
+ * The clock belongs to the player. It says where the video is with an
17
+ * {@link Anchor}, and this follows.
18
+ *
19
+ * See development-plans/live-sound-mixing.md.
20
+ * @module
21
+ */
22
+
23
+ import { debugLog } from "../src/debug-log.ts";
24
+ import { fetchMedia } from "../src/local-files.ts";
25
+ import { Showable } from "../src/showable.ts";
26
+ import { AudioBuilder } from "./audio-builder.ts";
27
+
28
+ /**
29
+ * Every file is decoded at this rate, and the saved video's sound uses it too.
30
+ * So do the player's AudioContext and the voice recorder.
31
+ */
32
+ export const SAMPLE_RATE = 48000;
33
+
34
+ /**
35
+ * How far ahead a change while playing takes effect, in seconds.
36
+ * The old node stops and the new one starts at the same moment, so both requests
37
+ * must reach the audio thread before that moment comes.
38
+ */
39
+ const SWAP_AHEAD_S = 0.03;
40
+
41
+ /** One sound clip, in the video's time. */
42
+ export type PlacedSoundClip = {
43
+ readonly source: string;
44
+ /** When the clip starts, in ms from the start of the video. Can be negative. */
45
+ readonly startMs: number;
46
+ /** Where in the file to start, in ms. Negative means silence first. */
47
+ readonly trimMs: number;
48
+ /** How much to play. Infinity plays to the end of the file. */
49
+ readonly lengthMs: number;
50
+ };
51
+
52
+ /**
53
+ * Every sound clip in the tree, in the video's time. Read only.
54
+ *
55
+ * A clip with no source yet is left out: a brand new clip, or a URL that's still
56
+ * being typed.
57
+ */
58
+ export function collectSoundClips(root: Showable): PlacedSoundClip[] {
59
+ const result: PlacedSoundClip[] = [];
60
+ function walk(item: Showable, offset: number) {
61
+ for (const clip of item.soundClips ?? []) {
62
+ if (clip.source === "") continue;
63
+ result.push({
64
+ source: clip.source,
65
+ startMs: offset + clip.startMsIntoScene,
66
+ trimMs: clip.startMsIntoClip ?? 0,
67
+ lengthMs: clip.lengthMs ?? Infinity,
68
+ });
69
+ }
70
+ for (const { child, start } of item.children ?? []) {
71
+ walk(child, offset + start);
72
+ }
73
+ }
74
+ walk(root, 0);
75
+ return result;
76
+ }
77
+
78
+ /**
79
+ * Where the video is: at `contextTime`, in the audio context's clock, the video
80
+ * is at `mediaMs`, moving at `rate`.
81
+ */
82
+ export type Anchor = {
83
+ readonly contextTime: number;
84
+ readonly mediaMs: number;
85
+ readonly rate: number;
86
+ };
87
+
88
+ type PlayingNode = {
89
+ readonly node: AudioBufferSourceNode;
90
+ /** Which clip this plays. See {@link Soundtrack.#keyOf}. */
91
+ readonly key: string;
92
+ /** The {@link Soundtrack.#anchorVersion} it was scheduled for. */
93
+ readonly anchorVersion: number;
94
+ };
95
+
96
+ export type SoundtrackOptions = {
97
+ /** Where the clips play. An `OfflineAudioContext` works too, for testing. */
98
+ readonly context: BaseAudioContext;
99
+ /** Usually a gain node, for the volume and mute controls. */
100
+ readonly destination: AudioNode;
101
+ /** The whole video. Read on every {@link Soundtrack.request}. */
102
+ readonly root: () => Showable;
103
+ /** A file finished decoding: its waveform and length are known now. */
104
+ readonly onDecoded?: () => void;
105
+ /** A clip names a file that wasn't in the list before. */
106
+ readonly onNewSource?: () => void;
107
+ };
108
+
109
+ export class Soundtrack {
110
+ readonly #options: SoundtrackOptions;
111
+
112
+ constructor(options: SoundtrackOptions) {
113
+ this.#options = options;
114
+ }
115
+
116
+ // MARK: Decoded files
117
+
118
+ /** Decodes, and resamples to {@link SAMPLE_RATE}. It never renders anything. */
119
+ readonly #decoder = new OfflineAudioContext({
120
+ length: 1,
121
+ sampleRate: SAMPLE_RATE,
122
+ });
123
+ readonly #decoding = new Map<string, Promise<AudioBuffer>>();
124
+ readonly #decoded = new Map<string, AudioBuffer>();
125
+ /** Files that couldn't be read. Not tried again until {@link forgetFailures}. */
126
+ readonly #failed = new Set<string>();
127
+
128
+ /**
129
+ * The decoded file, mono, or null if it hasn't been decoded yet (or can't be).
130
+ * Its length is the file's length.
131
+ */
132
+ getDecodedBuffer(url: string): AudioBuffer | null {
133
+ return this.#decoded.get(url) ?? null;
134
+ }
135
+
136
+ /** Read and decode every file again, e.g. one re-recorded under the same name. */
137
+ forget(): void {
138
+ this.#decoding.clear();
139
+ this.#decoded.clear();
140
+ this.#failed.clear();
141
+ this.#knownSources.clear();
142
+ this.#loadAgain();
143
+ }
144
+
145
+ /**
146
+ * Use `buffer` as the decoded file for `url`, instead of reading the file.
147
+ * For a file this page just wrote, like a voice recording, whose samples are
148
+ * already in memory. It must be mono, at {@link SAMPLE_RATE}, and exactly as
149
+ * long as the file.
150
+ */
151
+ provide(url: string, buffer: AudioBuffer): void {
152
+ this.#decoding.set(url, Promise.resolve(buffer));
153
+ this.#decoded.set(url, buffer);
154
+ this.#failed.delete(url);
155
+ this.#options.onDecoded?.();
156
+ if (this.#anchor) this.#resync();
157
+ }
158
+
159
+ /** Try the files that couldn't be read again, e.g. after 🔓 Allow local files. */
160
+ forgetFailures(): void {
161
+ for (const url of this.#failed) this.#decoding.delete(url);
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 = "";
169
+ this.request();
170
+ }
171
+
172
+ #load(url: string): Promise<AudioBuffer> {
173
+ return this.#decoding.getOrInsertComputed(url, () => {
174
+ const promise = this.#decode(url).then(
175
+ (buffer) => {
176
+ // forget() may have come in the meantime.
177
+ if (this.#decoding.get(url) === promise) {
178
+ this.#decoded.set(url, buffer);
179
+ this.#options.onDecoded?.();
180
+ if (this.#anchor) this.#resync();
181
+ }
182
+ return buffer;
183
+ },
184
+ (reason) => {
185
+ if (this.#decoding.get(url) === promise) this.#failed.add(url);
186
+ debugLog("audio", `Skipped "${url}": ${reason}`);
187
+ throw reason;
188
+ },
189
+ );
190
+ // ready() looks at failures with allSettled(). This is for everyone else.
191
+ promise.catch(() => {});
192
+ return promise;
193
+ });
194
+ }
195
+
196
+ async #decode(url: string): Promise<AudioBuffer> {
197
+ const time1 = performance.now();
198
+ const response = await fetchMedia(url);
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;
202
+ const time2 = performance.now();
203
+ // decodeAudioData() takes about ⅜ - ¾ of a second to decode 4 minutes and 18 seconds of audio.
204
+ const decoded = await this.#decoder.decodeAudioData(encoded);
205
+ const time3 = performance.now();
206
+ debugLog(
207
+ "audio",
208
+ `Decoded "${url}": ${(bytes / 1024).toFixed(0)} KB, ` +
209
+ `read ${(time2 - time1).toFixed(0)} ms, decode ${(time3 - time2).toFixed(0)} ms`,
210
+ );
211
+ if (decoded.numberOfChannels === 1) return decoded;
212
+ // Average the channels, don't sum them: identical channels (the usual
213
+ // "stereo") come out exactly as they went in, where a sum would double
214
+ // the level and clip.
215
+ const mono = new AudioBuffer({
216
+ numberOfChannels: 1,
217
+ length: decoded.length,
218
+ sampleRate: decoded.sampleRate,
219
+ });
220
+ const out = mono.getChannelData(0);
221
+ for (let channel = 0; channel < decoded.numberOfChannels; channel++) {
222
+ const data = decoded.getChannelData(channel);
223
+ for (let i = 0; i < out.length; i++) out[i] += data[i];
224
+ }
225
+ const scale = 1 / decoded.numberOfChannels;
226
+ for (let i = 0; i < out.length; i++) out[i] *= scale;
227
+ return mono;
228
+ }
229
+
230
+ // MARK: The clip list
231
+
232
+ #clips: readonly PlacedSoundClip[] = [];
233
+ /** {@link #clips} and the video's length, as JSON: how a request knows nothing changed. */
234
+ #clipsJson = "";
235
+ #requested = false;
236
+ /** Every source a clip has named, so {@link SoundtrackOptions.onNewSource} only fires for new ones. */
237
+ readonly #knownSources = new Set<string>();
238
+
239
+ /**
240
+ * Something may have changed: a clip, a component's timing, the tree.
241
+ *
242
+ * Call it as often as you like, even several times per mouse move. Calls in the
243
+ * same task are combined into one, and that one does almost nothing unless a clip
244
+ * moved. Nothing here allocates anything the size of the video.
245
+ */
246
+ request(): void {
247
+ if (this.#requested) return;
248
+ this.#requested = true;
249
+ queueMicrotask(() => this.#update());
250
+ }
251
+
252
+ #update(): void {
253
+ this.#requested = false;
254
+ const root = this.#options.root();
255
+ const clips = collectSoundClips(root);
256
+ const json = JSON.stringify([root.duration, clips]);
257
+ if (json === this.#clipsJson) return;
258
+ this.#clipsJson = json;
259
+ this.#clips = clips;
260
+ let newSource = false;
261
+ for (const { source } of clips) {
262
+ if (!this.#knownSources.has(source)) {
263
+ this.#knownSources.add(source);
264
+ newSource = true;
265
+ }
266
+ void this.#load(source).catch(() => {});
267
+ }
268
+ if (newSource) this.#options.onNewSource?.();
269
+ if (this.#anchor) this.#resync();
270
+ }
271
+
272
+ /**
273
+ * Resolves when every file the newest clip list names has been decoded, or has
274
+ * failed. The newest: if the list changes while this waits, it waits for that
275
+ * one too.
276
+ */
277
+ async ready(): Promise<void> {
278
+ for (;;) {
279
+ if (this.#requested) this.#update();
280
+ const json = this.#clipsJson;
281
+ await Promise.allSettled(this.#clips.map(({ source }) => this.#load(source)));
282
+ if (!this.#requested && json === this.#clipsJson) return;
283
+ }
284
+ }
285
+
286
+ /**
287
+ * The soundtrack from `fromMs` to `toMs`, mixed into one mono buffer, for saving.
288
+ * Call {@link ready} first, or clips whose file isn't decoded yet are left out.
289
+ */
290
+ mix(fromMs: number, toMs: number): AudioBuilder {
291
+ if (this.#requested) this.#update();
292
+ const builder = new AudioBuilder(
293
+ Math.max(0, toMs - fromMs),
294
+ SAMPLE_RATE,
295
+ );
296
+ for (const clip of this.#clips) {
297
+ const buffer = this.#decoded.get(clip.source);
298
+ if (buffer) {
299
+ builder.add(buffer, clip.startMs - fromMs, clip.trimMs, clip.lengthMs);
300
+ }
301
+ }
302
+ return builder;
303
+ }
304
+
305
+ // MARK: Playing
306
+
307
+ /** Undefined when stopped. */
308
+ #anchor: Anchor | undefined;
309
+ /**
310
+ * Changes whenever the anchor moves (a seek, a new speed). A node scheduled for an
311
+ * older anchor plays at the wrong times, so it has to be replaced.
312
+ */
313
+ #anchorVersion = 0;
314
+ #nodes: PlayingNode[] = [];
315
+
316
+ /** Start playing at `anchor`, from scratch. */
317
+ play(anchor: Anchor): void {
318
+ this.stop();
319
+ this.#anchor = anchor;
320
+ this.#anchorVersion++;
321
+ for (const clip of this.#clips) {
322
+ this.#schedule(clip, anchor.mediaMs);
323
+ }
324
+ }
325
+
326
+ /**
327
+ * Keep playing, at a new speed. `anchor` must agree with the old one about where
328
+ * the video is now, so nothing jumps.
329
+ */
330
+ changeRate(anchor: Anchor): void {
331
+ if (!this.#anchor) return;
332
+ // The nodes already playing are right again at once. The ones waiting to start
333
+ // were timed for the old speed, so all of them are replaced, a moment from now.
334
+ for (const { node } of this.#nodes) node.playbackRate.value = anchor.rate;
335
+ this.#anchor = anchor;
336
+ this.#anchorVersion++;
337
+ this.#resync();
338
+ }
339
+
340
+ /** Stop at once. */
341
+ stop(): void {
342
+ for (const { node } of this.#nodes) {
343
+ try {
344
+ node.stop();
345
+ } catch {
346
+ // Already stopped.
347
+ }
348
+ node.disconnect();
349
+ }
350
+ this.#nodes = [];
351
+ this.#anchor = undefined;
352
+ }
353
+
354
+ /** The video's time at `contextTime`, by the current anchor. */
355
+ #mediaMsAt(contextTime: number): number {
356
+ const anchor = this.#anchor!;
357
+ return anchor.mediaMs + (contextTime - anchor.contextTime) * anchor.rate * 1000;
358
+ }
359
+
360
+ /**
361
+ * Identifies one clip at one place: equal keys play exactly the same sound at the
362
+ * same time, so a node can be kept.
363
+ */
364
+ #keyOf(clip: PlacedSoundClip): string {
365
+ return JSON.stringify([clip.source, clip.startMs, clip.trimMs, clip.lengthMs]);
366
+ }
367
+
368
+ /**
369
+ * Bring the nodes up to date with {@link #clips}, while playing.
370
+ * A node whose clip is unchanged keeps playing. Every other node stops, and its
371
+ * replacement starts, at the same moment, {@link SWAP_AHEAD_S} from now.
372
+ */
373
+ #resync(): void {
374
+ const swapTime = this.#options.context.currentTime + SWAP_AHEAD_S;
375
+ const fromMs = this.#mediaMsAt(swapTime);
376
+ /** Clips with no node yet, by key. An array, in case two clips are identical. */
377
+ const unplayed = new Map<string, PlacedSoundClip[]>();
378
+ for (const clip of this.#clips) {
379
+ unplayed.getOrInsertComputed(this.#keyOf(clip), () => []).push(clip);
380
+ }
381
+ const kept: PlayingNode[] = [];
382
+ for (const playing of this.#nodes) {
383
+ const waiting = unplayed.get(playing.key);
384
+ if (playing.anchorVersion === this.#anchorVersion && waiting?.length) {
385
+ waiting.pop();
386
+ kept.push(playing);
387
+ } else {
388
+ try {
389
+ playing.node.stop(swapTime);
390
+ } catch {
391
+ // Already stopped.
392
+ }
393
+ playing.node.onended = () => playing.node.disconnect();
394
+ }
395
+ }
396
+ this.#nodes = kept;
397
+ for (const clips of unplayed.values()) {
398
+ for (const clip of clips) this.#schedule(clip, fromMs);
399
+ }
400
+ }
401
+
402
+ /**
403
+ * Start a node for the part of `clip` from `fromMs` on, in the video's time, if
404
+ * its file is decoded and there's anything left to play.
405
+ */
406
+ #schedule(clip: PlacedSoundClip, fromMs: number): void {
407
+ const buffer = this.#decoded.get(clip.source);
408
+ const anchor = this.#anchor;
409
+ if (!buffer || !anchor) return;
410
+ let { startMs, trimMs, lengthMs } = clip;
411
+ if (trimMs < 0) {
412
+ // Nothing to play before the file starts: start later instead.
413
+ startMs -= trimMs;
414
+ lengthMs += trimMs;
415
+ trimMs = 0;
416
+ }
417
+ const endMs = Math.min(
418
+ startMs + lengthMs,
419
+ startMs + buffer.duration * 1000 - trimMs,
420
+ this.#options.root().duration,
421
+ );
422
+ // Nothing before the video starts, either, and nothing already played.
423
+ const beginMs = Math.max(startMs, fromMs, 0);
424
+ if (endMs - beginMs < 0.001) return;
425
+ const node = this.#options.context.createBufferSource();
426
+ node.buffer = buffer; // Shared, not copied.
427
+ node.playbackRate.value = anchor.rate;
428
+ node.connect(this.#options.destination);
429
+ // Only `when` depends on the speed. The offset and the duration are in the
430
+ // file's own time.
431
+ node.start(
432
+ anchor.contextTime + (beginMs - anchor.mediaMs) / 1000 / anchor.rate,
433
+ (trimMs + beginMs - startMs) / 1000,
434
+ (endMs - beginMs) / 1000,
435
+ );
436
+ this.#nodes.push({
437
+ node,
438
+ key: this.#keyOf(clip),
439
+ anchorVersion: this.#anchorVersion,
440
+ });
441
+ }
442
+ }
@@ -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) => {
@@ -485,7 +485,7 @@ export function buildVideoClipPanel(
485
485
  return;
486
486
  }
487
487
  if (!isRealTime(speed)) {
488
- // AudioBuilder can't change the speed of a sound, so anything but 1×
488
+ // The soundtrack can't change the speed of a sound, so anything but 1×
489
489
  // would drift out of sync.
490
490
  setStatus(`Audio needs 1× — currently ${Number.isNaN(speed) ? "—" : formatSpeed(speed)}`, "#a06000");
491
491
  importBtn.disabled = true;