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
@@ -0,0 +1,603 @@
1
+ import { addLocalFile } from "../../src/local-files.ts";
2
+ import { SAMPLE_RATE } from "../soundtrack.ts";
3
+ import { chirpSamples, findSound } from "./chirp.ts";
4
+
5
+ /**
6
+ * The voice recorder's engine: the mic, the files, and the chirp. No user interface; see
7
+ * voice-panel.ts. Nothing here knows about the player, except that it shares the player's
8
+ * AudioContext.
9
+ *
10
+ * Sharing the AudioContext means sharing its clock, the one the video plays by. An AudioWorklet
11
+ * copies the mic's samples, and says exactly which frame of that clock each one belongs to. So a
12
+ * clip's place in the video is exact, with no clocks to match up.
13
+ *
14
+ * - A **session** runs from ● Record to the stop. It starts with the chirp.
15
+ * - A session holds one or more **clips**. The player starts one whenever the video starts moving,
16
+ * and ends it whenever the video stops or jumps. So a seek ends one clip and starts the next.
17
+ * - Each clip is its own WAV file (32-bit float, mono, 48 kHz), written as it goes, and kept in memory
18
+ * too. The file holds a little more than the clip at each end: the chirp, or what came between
19
+ * two clips, at the start, and {@link TAIL_S} at the end. The clip's trim hides the extra.
20
+ *
21
+ * Copied from riemann-surfaces-3d's src/recording/voice-recorder.ts (9bbe2f9), without the log or
22
+ * the Stop and Marker sounds. See development-plans/voice-recording.md.
23
+ * @module
24
+ */
25
+
26
+ /** The browser's voice processing. Each one is a checkbox. */
27
+ export const PROCESSING = [
28
+ {
29
+ name: "echoCancellation",
30
+ label: "Echo cancellation",
31
+ help: "For calls. Removes whatever your own speakers are playing. It would erase the chirp.",
32
+ },
33
+ {
34
+ name: "noiseSuppression",
35
+ label: "Noise suppression",
36
+ help: "Removes steady background noise, like fans and hum, and some clicks.",
37
+ },
38
+ {
39
+ name: "autoGainControl",
40
+ label: "Automatic gain control",
41
+ help: "Turns the volume up and down to keep your voice level. It turns background noise up during your pauses.",
42
+ },
43
+ {
44
+ name: "voiceIsolation",
45
+ label: "Voice isolation",
46
+ help: "Only in newer browsers. Tries to keep your voice and nothing else.",
47
+ },
48
+ ] as const;
49
+ export type ProcessingName = (typeof PROCESSING)[number]["name"];
50
+ export type ProcessingChoices = Partial<Record<ProcessingName, boolean>>;
51
+
52
+ /** Noise suppression on, the rest off. From riemann's feedback: "The helicopter is gone." */
53
+ export const DEFAULT_PROCESSING: ProcessingChoices = { noiseSuppression: true };
54
+
55
+ /** The parts of PROCESSING that this browser offers. */
56
+ export function supportedProcessing() {
57
+ const supported = navigator.mediaDevices.getSupportedConstraints() as Record<
58
+ string,
59
+ boolean | undefined
60
+ >;
61
+ return PROCESSING.filter(({ name }) => supported[name]);
62
+ }
63
+
64
+ /** How far ahead to schedule the chirp, in seconds, so it's sure to land inside the recording. */
65
+ const CHIRP_LEAD_S = 0.25;
66
+ /**
67
+ * How long after the chirp ends the video starts, in seconds. The chirp reaches the mic about a
68
+ * tenth of a second after it's played, and the clip starts after that.
69
+ */
70
+ const AFTER_CHIRP_S = 0.15;
71
+ /** Look for the chirp from a little before it was played to this long after, in seconds. */
72
+ const SEARCH_AFTER_S = 0.3;
73
+ /** A match better than this means the chirp really was heard. Noise scores about 0.03, speech up to about 0.08. */
74
+ const HEARD = 0.15;
75
+ /** How much more than the clip each file holds at the end, in seconds. In case Pause cut off a word. */
76
+ const TAIL_S = 0.5;
77
+ /**
78
+ * How long the mic and the OS take to deliver a sound, until the chirp measures it.
79
+ * Measured on a MacBook Air: a 106 ms round trip, less Chrome's 34 ms output.
80
+ */
81
+ const DEFAULT_DELAY_MS = 72;
82
+ const DELAY_KEY = "voice-recorder.mic-delay-ms";
83
+
84
+ /**
85
+ * The AudioWorklet. It runs on the audio thread, and sends the mic's samples to the page in blocks of
86
+ * 2048, with the clock frame of the first one, and the levels for the meter. It's a string, so it
87
+ * needs no build setup.
88
+ */
89
+ const WORKLET = /* js */ `
90
+ class VoiceRecorderProcessor extends AudioWorkletProcessor {
91
+ constructor() {
92
+ super();
93
+ this.reset();
94
+ }
95
+ reset() {
96
+ this.samples = new Float32Array(2048);
97
+ this.filled = 0;
98
+ this.peak = 0;
99
+ this.squares = 0;
100
+ }
101
+ process(inputs) {
102
+ const channels = inputs[0];
103
+ const length = channels.length ? channels[0].length : 128;
104
+ if (this.filled + length > this.samples.length) {
105
+ this.send();
106
+ }
107
+ if (this.filled == 0) {
108
+ this.first = currentFrame;
109
+ }
110
+ for (let i = 0; i < length; i++) {
111
+ // Mono. Average the channels if there's more than one.
112
+ let v = 0;
113
+ for (const channel of channels) {
114
+ v += channel[i];
115
+ }
116
+ if (channels.length > 1) {
117
+ v /= channels.length;
118
+ }
119
+ this.samples[this.filled + i] = v;
120
+ this.peak = Math.max(this.peak, Math.abs(v));
121
+ this.squares += v * v;
122
+ }
123
+ this.filled += length;
124
+ if (this.filled == this.samples.length) {
125
+ this.send();
126
+ }
127
+ return true;
128
+ }
129
+ send() {
130
+ const samples = this.samples.subarray(0, this.filled);
131
+ const rms = Math.sqrt(this.squares / Math.max(1, this.filled));
132
+ this.port.postMessage({ first: this.first, samples, peak: this.peak, rms }, [this.samples.buffer]);
133
+ this.reset();
134
+ }
135
+ }
136
+ registerProcessor("voice-recorder", VoiceRecorderProcessor);
137
+ `;
138
+
139
+ /** addModule() for each context only once: registering the processor twice is an error. */
140
+ const workletLoaded = new WeakMap<BaseAudioContext, Promise<void>>();
141
+
142
+ type Chunk = { first: number; samples: Float32Array; peak: number; rms: number };
143
+
144
+ export type HeardResult = {
145
+ /** Undefined if the chirp wasn't found: speakers off, or headphones. */
146
+ roundTripMs?: number;
147
+ match: number;
148
+ peakDb: number;
149
+ };
150
+
151
+ /** A finished clip: its file, and the part of the file that goes in the video. */
152
+ export type RecordedClip = {
153
+ /** The file's `local:` URL. */
154
+ readonly url: string;
155
+ /** The whole file, mono, at {@link SAMPLE_RATE}. For `Soundtrack.provide()`. */
156
+ readonly buffer: AudioBuffer;
157
+ /** Where in the file the clip starts, in ms. */
158
+ readonly trimMs: number;
159
+ /** How long the clip is, in ms. */
160
+ readonly lengthMs: number;
161
+ };
162
+
163
+ /** The clip being recorded now, for the live waveform. */
164
+ export type LiveClip = {
165
+ /** The file so far. It's longer than the recording: it grows by doubling. */
166
+ readonly buffer: AudioBuffer;
167
+ /** Where in `buffer` the clip starts, in ms. */
168
+ readonly trimMs: number;
169
+ /** How long the clip is so far, in ms. */
170
+ readonly lengthMs: number;
171
+ };
172
+
173
+ /** One file, and the clip it holds. */
174
+ type ClipFile = {
175
+ readonly folder: FileSystemDirectoryHandle;
176
+ readonly name: string;
177
+ /** The clock frame of the file's first sample. */
178
+ readonly startFrame: number;
179
+ /** Stop writing at this clock frame. Undefined until the clip ends. */
180
+ endFrame?: number;
181
+ /** The samples so far. Longer than {@link frames}: it grows by doubling. */
182
+ buffer: AudioBuffer;
183
+ frames: number;
184
+ readonly handle: Promise<FileSystemFileHandle>;
185
+ /** Writes happen in order, one after another. */
186
+ writing: Promise<FileSystemWritableFileStream>;
187
+ /** In the clock's time, in seconds. Undefined until the player starts the clip. */
188
+ clipStart?: number;
189
+ clipEnd?: number;
190
+ readonly finished: Promise<RecordedClip>;
191
+ readonly resolve: (clip: RecordedClip) => void;
192
+ readonly reject: (reason: unknown) => void;
193
+ done: boolean;
194
+ };
195
+
196
+ type Session = {
197
+ readonly folder: FileSystemDirectoryHandle;
198
+ /** The start of every file name, usually the video's name. */
199
+ readonly prefix: string;
200
+ /** The file for the clip being recorded, or the next one. */
201
+ current?: ClipFile;
202
+ /** Where the next file starts: where the last clip ended. */
203
+ nextStartFrame: number;
204
+ };
205
+
206
+ /** A file name made from the video's name and the time, like `my-video 2026-11-07 14-05-33.250.wav`. */
207
+ function fileName(prefix: string, now: Date): string {
208
+ const pad = (n: number, width = 2) => String(n).padStart(width, "0");
209
+ const date = `${now.getFullYear()}-${pad(now.getMonth() + 1)}-${pad(now.getDate())}`;
210
+ const time = `${pad(now.getHours())}-${pad(now.getMinutes())}-${pad(now.getSeconds())}.${pad(now.getMilliseconds(), 3)}`;
211
+ // No colons or slashes: Windows doesn't allow them, and the Finder shows a colon as a slash.
212
+ const safe = prefix.replace(/[\\/:*?"<>|]/g, "-");
213
+ return `${safe} ${date} ${time}.wav`;
214
+ }
215
+
216
+ export class VoiceRecorder {
217
+ readonly context: AudioContext;
218
+ readonly #node: AudioWorkletNode;
219
+ #source?: MediaStreamAudioSourceNode;
220
+ #stream?: MediaStream;
221
+ #choices: ProcessingChoices;
222
+ #session?: Session;
223
+ /** Every file still receiving samples: the current one, and any finishing their tails. */
224
+ readonly #files = new Set<ClipFile>();
225
+ /** The chirp, while we wait to find it. */
226
+ #listening?: { file: ClipFile; samples: Float32Array };
227
+ /** How long the mic and the OS take to deliver a sound, in ms. Measured by the chirp. */
228
+ micDelayMs: number;
229
+ /** Called for each block of audio, about 23 times a second, with levels from 0 to 1. */
230
+ onLevel?: (peak: number, rms: number) => void;
231
+ /** Called when the chirp is found in the recording, or isn't. */
232
+ onHeard?: (result: HeardResult) => void;
233
+
234
+ private constructor(
235
+ context: AudioContext,
236
+ node: AudioWorkletNode,
237
+ choices: ProcessingChoices,
238
+ ) {
239
+ this.context = context;
240
+ this.#node = node;
241
+ this.#choices = choices;
242
+ const saved = Number(localStorage.getItem(DELAY_KEY));
243
+ this.micDelayMs = saved > 0 ? saved : DEFAULT_DELAY_MS;
244
+ node.port.onmessage = (event: MessageEvent<Chunk>) => this.#receive(event.data);
245
+ }
246
+
247
+ /**
248
+ * Turn on the mic. Call this from a click, so the browser lets the audio start.
249
+ * The browser asks for permission to use the mic the first time.
250
+ */
251
+ static async open(context: AudioContext, choices: ProcessingChoices): Promise<VoiceRecorder> {
252
+ await workletLoaded.getOrInsertComputed(context, async () => {
253
+ const url = URL.createObjectURL(new Blob([WORKLET], { type: "text/javascript" }));
254
+ try {
255
+ await context.audioWorklet.addModule(url);
256
+ } finally {
257
+ URL.revokeObjectURL(url);
258
+ }
259
+ });
260
+ const node = new AudioWorkletNode(context, "voice-recorder");
261
+ // An audio node only runs if it leads to the speakers. The worklet never writes anything to its
262
+ // output, so this is silent.
263
+ node.connect(context.destination);
264
+ const recorder = new VoiceRecorder(context, node, choices);
265
+ try {
266
+ await recorder.#connectMic();
267
+ } catch (error) {
268
+ node.disconnect();
269
+ throw error;
270
+ }
271
+ await context.resume();
272
+ return recorder;
273
+ }
274
+
275
+ #constraints(): MediaTrackConstraints {
276
+ const result: Record<string, unknown> = { channelCount: { ideal: 1 } };
277
+ for (const { name } of supportedProcessing()) {
278
+ result[name] = this.#choices[name] ?? false;
279
+ }
280
+ return result as MediaTrackConstraints;
281
+ }
282
+
283
+ async #connectMic() {
284
+ this.#stream = await navigator.mediaDevices.getUserMedia({ audio: this.#constraints() });
285
+ this.#source = new MediaStreamAudioSourceNode(this.context, { mediaStream: this.#stream });
286
+ this.#source.connect(this.#node);
287
+ }
288
+
289
+ get #track() {
290
+ return this.#stream?.getAudioTracks()[0];
291
+ }
292
+
293
+ /** What the mic actually got. The browser can quietly ignore a request. */
294
+ actualSettings(): Record<string, unknown> {
295
+ return (this.#track?.getSettings() ?? {}) as Record<string, unknown>;
296
+ }
297
+
298
+ /** The mic's name, like "MacBook Pro Microphone". */
299
+ get micName(): string {
300
+ return this.#track?.label ?? "";
301
+ }
302
+
303
+ /**
304
+ * Turn one kind of voice processing on or off. Works in the middle of a recording. First try
305
+ * changing the mic that's already open. If the browser won't, open the mic again. The recording
306
+ * keeps going, on the same clock, with maybe a moment of silence.
307
+ */
308
+ async setProcessing(name: ProcessingName, on: boolean): Promise<void> {
309
+ this.#choices = { ...this.#choices, [name]: on };
310
+ try {
311
+ await this.#track?.applyConstraints(this.#constraints());
312
+ } catch {
313
+ // Handled below.
314
+ }
315
+ if (this.actualSettings()[name] !== on) {
316
+ const old = this.#source;
317
+ this.#stream?.getTracks().forEach((track) => track.stop());
318
+ old?.disconnect();
319
+ await this.#connectMic();
320
+ }
321
+ }
322
+
323
+ // MARK: Sessions and clips
324
+
325
+ /** True from {@link start} to {@link stop}. */
326
+ get recording(): boolean {
327
+ return this.#session !== undefined;
328
+ }
329
+
330
+ /**
331
+ * Start a session: play the chirp, and start recording.
332
+ * Resolves a moment after the chirp, when the video should start.
333
+ *
334
+ * @param prefix The start of each file's name, usually the video's name.
335
+ */
336
+ async start(folder: FileSystemDirectoryHandle, prefix: string): Promise<void> {
337
+ if (this.#session) return;
338
+ await this.context.resume();
339
+ const chirp = chirpSamples(SAMPLE_RATE);
340
+ const when = this.context.currentTime + CHIRP_LEAD_S;
341
+ const chirpFrame = Math.round(when * SAMPLE_RATE);
342
+ const session: Session = { folder, prefix, nextStartFrame: chirpFrame };
343
+ this.#session = session;
344
+ // The first file starts with the chirp.
345
+ const file = this.#openFile(session, chirpFrame);
346
+ session.current = file;
347
+ this.#listening = { file, samples: chirp };
348
+ // Straight to the speakers, so the player's mute doesn't silence it.
349
+ const buffer = new AudioBuffer({ numberOfChannels: 1, length: chirp.length, sampleRate: SAMPLE_RATE });
350
+ buffer.copyToChannel(chirp, 0);
351
+ const node = new AudioBufferSourceNode(this.context, { buffer });
352
+ node.connect(this.context.destination);
353
+ node.onended = () => node.disconnect();
354
+ node.start(when);
355
+ const videoStarts = when + buffer.duration + AFTER_CHIRP_S;
356
+ await new Promise((resolve) =>
357
+ setTimeout(resolve, Math.max(0, videoStarts - this.context.currentTime) * 1000),
358
+ );
359
+ }
360
+
361
+ /**
362
+ * The video started moving at `contextTime`, on the AudioContext's clock.
363
+ * Resolves when the clip's file is finished and on the `local:` list: {@link TAIL_S} after
364
+ * {@link endClip}. Does nothing (and never resolves) outside a session.
365
+ */
366
+ beginClip(contextTime: number): Promise<RecordedClip> {
367
+ const session = this.#session;
368
+ if (!session) return new Promise(() => {});
369
+ if (session.current?.clipStart !== undefined) this.endClip(contextTime);
370
+ session.current ??= this.#openFile(session, session.nextStartFrame);
371
+ session.current.clipStart = contextTime;
372
+ return session.current.finished;
373
+ }
374
+
375
+ /** The video stopped or jumped at `contextTime`. Does nothing if no clip is being recorded. */
376
+ endClip(contextTime: number): void {
377
+ const session = this.#session;
378
+ const file = session?.current;
379
+ if (!session || file?.clipStart === undefined) return;
380
+ file.clipEnd = Math.max(file.clipStart, contextTime);
381
+ file.endFrame = Math.round(
382
+ (file.clipEnd + this.micDelayMs / 1000 + TAIL_S) * SAMPLE_RATE,
383
+ );
384
+ session.current = undefined;
385
+ session.nextStartFrame = Math.round(file.clipEnd * SAMPLE_RATE);
386
+ }
387
+
388
+ /** The clip being recorded now, if there is one. */
389
+ liveClip(): LiveClip | undefined {
390
+ const file = this.#session?.current;
391
+ if (file?.clipStart === undefined) return undefined;
392
+ const trimMs = this.#trimMs(file);
393
+ return {
394
+ buffer: file.buffer,
395
+ trimMs,
396
+ lengthMs: Math.max(0, (file.frames / SAMPLE_RATE) * 1000 - trimMs),
397
+ };
398
+ }
399
+
400
+ /** End the session. Any clip ends now; its file finishes {@link TAIL_S} later. */
401
+ stop(): void {
402
+ const session = this.#session;
403
+ if (!session) return;
404
+ this.endClip(this.context.currentTime);
405
+ // A file with no clip yet: ■ Stop during the chirp.
406
+ if (session.current) void this.#finish(session.current);
407
+ this.#session = undefined;
408
+ }
409
+
410
+ /**
411
+ * Finish every file now, without waiting for the tails. For a page that's closing.
412
+ * Each write still has to reach the disk, so this may not finish in time.
413
+ */
414
+ flush(): void {
415
+ this.stop();
416
+ for (const file of this.#files) void this.#finish(file);
417
+ }
418
+
419
+ /** Turn off the mic. Stops recording first, and waits a little for the files to finish. */
420
+ async close(): Promise<void> {
421
+ this.stop();
422
+ const files = [...this.#files];
423
+ // The tails need the mic. Wait for them, but not forever.
424
+ await Promise.race([
425
+ Promise.allSettled(files.map((file) => file.finished)),
426
+ new Promise((resolve) => setTimeout(resolve, (TAIL_S + 1) * 1000)),
427
+ ]);
428
+ for (const file of files) void this.#finish(file);
429
+ this.#stream?.getTracks().forEach((track) => track.stop());
430
+ this.#source?.disconnect();
431
+ this.#node.disconnect();
432
+ }
433
+
434
+ // MARK: Files
435
+
436
+ #openFile(session: Session, startFrame: number): ClipFile {
437
+ const name = fileName(session.prefix, new Date());
438
+ const handle = session.folder.getFileHandle(name, { create: true });
439
+ let resolve!: (clip: RecordedClip) => void;
440
+ let reject!: (reason: unknown) => void;
441
+ const finished = new Promise<RecordedClip>((res, rej) => {
442
+ resolve = res;
443
+ reject = rej;
444
+ });
445
+ // The player may never use this file (■ Stop during the chirp), and then nobody listens.
446
+ finished.catch(() => {});
447
+ const file: ClipFile = {
448
+ folder: session.folder,
449
+ name,
450
+ startFrame,
451
+ buffer: new AudioBuffer({ numberOfChannels: 1, length: 10 * SAMPLE_RATE, sampleRate: SAMPLE_RATE }),
452
+ frames: 0,
453
+ handle,
454
+ writing: handle
455
+ .then((handle) => handle.createWritable())
456
+ .then(async (stream) => {
457
+ await stream.write(wavHeader(0));
458
+ return stream;
459
+ }),
460
+ finished,
461
+ resolve,
462
+ reject,
463
+ done: false,
464
+ };
465
+ // A failed write is reported once, by #finish().
466
+ file.writing.catch(() => {});
467
+ this.#files.add(file);
468
+ return file;
469
+ }
470
+
471
+ /** Where in the file the clip starts, in ms, corrected for the mic's delay. */
472
+ #trimMs(file: ClipFile): number {
473
+ const fileStart = file.startFrame / SAMPLE_RATE;
474
+ return ((file.clipStart ?? fileStart) - fileStart) * 1000 + this.micDelayMs;
475
+ }
476
+
477
+ /** A block of audio from the worklet. */
478
+ #receive(chunk: Chunk) {
479
+ this.onLevel?.(chunk.peak, chunk.rms);
480
+ for (const file of this.#files) {
481
+ const from = Math.max(0, file.startFrame - chunk.first);
482
+ const to = Math.min(
483
+ chunk.samples.length,
484
+ (file.endFrame ?? Infinity) - chunk.first,
485
+ );
486
+ if (to > from) this.#append(file, chunk.samples.subarray(from, to));
487
+ if (file.endFrame !== undefined && chunk.first + chunk.samples.length >= file.endFrame) {
488
+ void this.#finish(file);
489
+ }
490
+ }
491
+ this.#lookForChirp();
492
+ }
493
+
494
+ #append(file: ClipFile, samples: Float32Array) {
495
+ const needed = file.frames + samples.length;
496
+ if (needed > file.buffer.length) {
497
+ const bigger = new AudioBuffer({
498
+ numberOfChannels: 1,
499
+ length: Math.max(needed, file.buffer.length * 2),
500
+ sampleRate: SAMPLE_RATE,
501
+ });
502
+ bigger.getChannelData(0).set(file.buffer.getChannelData(0).subarray(0, file.frames));
503
+ file.buffer = bigger;
504
+ }
505
+ file.buffer.getChannelData(0).set(samples, file.frames);
506
+ file.frames = needed;
507
+ const data = samples.slice();
508
+ file.writing = file.writing.then(async (stream) => {
509
+ await stream.write(data);
510
+ return stream;
511
+ });
512
+ file.writing.catch(() => {});
513
+ }
514
+
515
+ /** Once enough has arrived, find the chirp, and measure the mic's delay with it. */
516
+ #lookForChirp() {
517
+ const listening = this.#listening;
518
+ if (!listening) return;
519
+ const { file, samples } = listening;
520
+ // The file starts when the chirp was played, so a sound that took no time at all would be at 0.
521
+ if (!file.done && file.frames < samples.length + SEARCH_AFTER_S * SAMPLE_RATE) return;
522
+ this.#listening = undefined;
523
+ const recording = file.buffer.getChannelData(0).subarray(0, file.frames);
524
+ const found = findSound(recording, samples, 0, SEARCH_AFTER_S * SAMPLE_RATE);
525
+ const heard = found.match > HEARD;
526
+ const result: HeardResult = {
527
+ roundTripMs: heard ? (found.position / SAMPLE_RATE) * 1000 : undefined,
528
+ match: found.match,
529
+ peakDb: found.peakDb,
530
+ };
531
+ if (result.roundTripMs !== undefined) {
532
+ const delayMs = result.roundTripMs - this.context.outputLatency * 1000;
533
+ if (delayMs > 0 && delayMs < 500) {
534
+ this.micDelayMs = delayMs;
535
+ localStorage.setItem(DELAY_KEY, String(delayMs));
536
+ }
537
+ }
538
+ this.onHeard?.(result);
539
+ }
540
+
541
+ /** Close the file, and put it on the `local:` list. Safe to call more than once. */
542
+ async #finish(file: ClipFile): Promise<void> {
543
+ if (file.done) return;
544
+ file.done = true;
545
+ this.#files.delete(file);
546
+ // A file that's finished early, like a closing page's, may still hold the chirp's search.
547
+ this.#lookForChirp();
548
+ const frames = file.frames;
549
+ try {
550
+ const stream = await file.writing;
551
+ await stream.write({ type: "write", position: 0, data: wavHeader(frames) });
552
+ await stream.close();
553
+ const handle = await file.handle;
554
+ if (file.clipStart === undefined) {
555
+ // ■ Stop during the chirp: there's no clip.
556
+ await file.folder.removeEntry(file.name).catch(() => {});
557
+ file.reject(new Error("No clip"));
558
+ return;
559
+ }
560
+ const buffer = new AudioBuffer({
561
+ numberOfChannels: 1,
562
+ length: Math.max(1, frames),
563
+ sampleRate: SAMPLE_RATE,
564
+ });
565
+ buffer.copyToChannel(file.buffer.getChannelData(0).subarray(0, frames), 0);
566
+ const trimMs = this.#trimMs(file);
567
+ const lengthMs = ((file.clipEnd ?? file.clipStart) - file.clipStart) * 1000;
568
+ file.resolve({ url: await addLocalFile(handle), buffer, trimMs, lengthMs });
569
+ } catch (error) {
570
+ file.reject(error);
571
+ }
572
+ }
573
+ }
574
+
575
+ /**
576
+ * The header for a 32-bit float, mono WAV file with this many samples. 58 bytes. It's written as a
577
+ * placeholder first, and again with the real length when the file is finished.
578
+ */
579
+ function wavHeader(frames: number) {
580
+ const dataBytes = frames * 4;
581
+ const header = new DataView(new ArrayBuffer(58));
582
+ const text = (at: number, value: string) =>
583
+ [...value].forEach((c, i) => header.setUint8(at + i, c.charCodeAt(0)));
584
+ text(0, "RIFF");
585
+ header.setUint32(4, 50 + dataBytes, true);
586
+ text(8, "WAVE");
587
+ text(12, "fmt ");
588
+ header.setUint32(16, 18, true);
589
+ // 3 is IEEE float.
590
+ header.setUint16(20, 3, true);
591
+ header.setUint16(22, 1, true);
592
+ header.setUint32(24, SAMPLE_RATE, true);
593
+ header.setUint32(28, SAMPLE_RATE * 4, true);
594
+ header.setUint16(32, 4, true);
595
+ header.setUint16(34, 32, true);
596
+ header.setUint16(36, 0, true);
597
+ text(38, "fact");
598
+ header.setUint32(42, 4, true);
599
+ header.setUint32(46, frames, true);
600
+ text(50, "data");
601
+ header.setUint32(54, dataBytes, true);
602
+ return header.buffer;
603
+ }
@@ -1,33 +1,26 @@
1
1
  /**
2
- * This creates a complete audio clip by joining multiple clips.
3
- * It starts with all silence and you can add the clips wherever you need them.
2
+ * The soundtrack mixed into one buffer, for the saved video and 🎤 Record Just Sound.
3
+ *
4
+ * Live playback doesn't use this: it gives each clip its own node, and the browser
5
+ * mixes them. See dev/soundtrack.ts.
4
6
  *
7
+ * It starts with all silence and you can add the clips wherever you need them.
5
8
  * Overlapping clips are mixed: each one is added to whatever is already
6
9
  * there, so two sounds at the same time are both heard.
7
10
  *
8
- * The result is always **mono**. Every source is mixed down to one channel as
9
- * it is added. Nothing recorded for these videos is really stereo: a Mac
10
- * screen recording, for example, writes its one microphone signal into both
11
- * channels, and CapCut's exports have done the same. One channel is less to
12
- * test and can't put a sound in only one ear by accident.
11
+ * The result is always **mono**, and so are the sources: dev/soundtrack.ts mixes
12
+ * each file down to one channel when it decodes it. Nothing recorded for these
13
+ * videos is really stereo: a Mac screen recording, for example, writes its one
14
+ * microphone signal into both channels, and CapCut's exports have done the same.
15
+ * One channel is less to test and can't put a sound in only one ear by accident.
13
16
  */
14
17
  export declare class AudioBuilder {
15
- #private;
16
- /**
17
- * Like AudioContext, but this lets you process data at full speed.
18
- * AudioContext doesn't allow you to process things faster than realtime.
19
- */
20
- private audioContext;
21
18
  /**
22
19
  * This is the sound we are building.
23
20
  */
24
21
  private buffer;
25
22
  getAudioBuffer(): AudioBuffer;
26
- constructor(totalDurationMs: number);
27
- clearCache(): void;
28
- warmCache(url: string): void;
29
- /** Returns the decoded buffer synchronously if already cached, otherwise null. */
30
- getDecodedBuffer(url: string): AudioBuffer | null;
23
+ constructor(totalDurationMs: number, sampleRate?: number);
31
24
  /**
32
25
  * Add a new clip to the soundtrack.
33
26
  * It is mixed with (added to) any sounds already at that position.
@@ -35,14 +28,7 @@ export declare class AudioBuilder {
35
28
  * The sum can go past ±1, which clips. That's fine for what this is used
36
29
  * for, a voiceover with the occasional overlap; the WAV encoder clamps, and
37
30
  * live playback clips the same way.
38
- * @param url Where to find the file.
39
- *
40
- * I typically use vite dev mode to run my project.
41
- * I put the files in the `/public` directory of the project.
42
- * And the url will start with "./".
43
- *
44
- * CORS can be an issue depending on the server.
45
- * A `local:` URL reads a file on the user's computer. See src/local-files.ts.
31
+ * @param sourceBuffer The decoded sound, mono, at this builder's sample rate.
46
32
  * @param startMsInDestination 0 to play the new clip at the the beginning of the video.
47
33
  * 1000 to start this clip 1 second after the video starts.
48
34
  *
@@ -79,11 +65,8 @@ export declare class AudioBuilder {
79
65
  * whichever comes first.
80
66
  *
81
67
  * The default is `Infinity`, to copy the entire clip or as much as will fit.
82
- * @returns This promise will resolve (or reject) when the request is complete.
83
68
  */
84
- add(url: string, startMsInDestination: number, trimFromStartMs?: number, length?: number): Promise<void>;
85
- toBlob(): Promise<Blob>;
86
- assignToAudioElement(audioElement: HTMLAudioElement): Promise<void>;
87
- private audioBufferToWav;
69
+ add(sourceBuffer: AudioBuffer, startMsInDestination: number, trimFromStartMs?: number, length?: number): void;
70
+ toBlob(): Blob;
88
71
  }
89
72
  //# sourceMappingURL=audio-builder.d.ts.map
@@ -1 +1 @@
1
- {"version":3,"file":"audio-builder.d.ts","sourceRoot":"","sources":["../../dev/audio-builder.ts"],"names":[],"mappings":"AAEA;;;;;;;;;;;;GAYG;AACH,qBAAa,YAAY;;IACvB;;;OAGG;IACH,OAAO,CAAC,YAAY,CAAsB;IAC1C;;OAEG;IACH,OAAO,CAAC,MAAM,CAAc;IAE5B,cAAc,IAAI,WAAW;gBAIjB,eAAe,EAAE,MAAM;IAwCnC,UAAU;IAKV,SAAS,CAAC,GAAG,EAAE,MAAM;IAIrB,kFAAkF;IAClF,gBAAgB,CAAC,GAAG,EAAE,MAAM,GAAG,WAAW,GAAG,IAAI;IAajD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OAoDG;IACG,GAAG,CACP,GAAG,EAAE,MAAM,EACX,oBAAoB,EAAE,MAAM,EAC5B,eAAe,GAAE,MAAU,EAC3B,MAAM,GAAE,MAAiB,GACxB,OAAO,CAAC,IAAI,CAAC;IAgEV,MAAM,IAAI,OAAO,CAAC,IAAI,CAAC;IAKvB,oBAAoB,CAAC,YAAY,EAAE,gBAAgB,GAAG,OAAO,CAAC,IAAI,CAAC;IAQzE,OAAO,CAAC,gBAAgB;CA4CzB"}
1
+ {"version":3,"file":"audio-builder.d.ts","sourceRoot":"","sources":["../../dev/audio-builder.ts"],"names":[],"mappings":"AAAA;;;;;;;;;;;;;;;GAeG;AACH,qBAAa,YAAY;IACvB;;OAEG;IACH,OAAO,CAAC,MAAM,CAAc;IAE5B,cAAc,IAAI,WAAW;gBAIjB,eAAe,EAAE,MAAM,EAAE,UAAU,SAAQ;IAcvD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;OA4CG;IACH,GAAG,CACD,YAAY,EAAE,WAAW,EACzB,oBAAoB,EAAE,MAAM,EAC5B,eAAe,GAAE,MAAU,EAC3B,MAAM,GAAE,MAAiB,GACxB,IAAI;IA0CP,MAAM,IAAI,IAAI;CAGf"}