canvas-recorder-lib 0.6.0 → 0.7.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/BREAKING-CHANGES.md +6 -0
- package/README.md +37 -23
- package/dev/audio-builder.ts +69 -163
- package/dev/canvas-recorder.ts +333 -167
- package/dev/player-body.ts +8 -0
- package/dev/sound-clips.ts +3 -2
- package/dev/soundtrack.ts +434 -0
- package/dev/video-clip-panel.ts +1 -1
- package/dev/voice/chirp.ts +129 -0
- package/dev/voice/folder.ts +84 -0
- package/dev/voice/voice-panel.ts +513 -0
- package/dev/voice/voice-recorder.ts +603 -0
- package/dist/dev/audio-builder.d.ts +14 -31
- package/dist/dev/audio-builder.d.ts.map +1 -1
- package/dist/dev/audio-builder.js +62 -135
- package/dist/dev/audio-builder.js.map +1 -1
- package/dist/dev/canvas-recorder.js +320 -154
- package/dist/dev/canvas-recorder.js.map +1 -1
- package/dist/dev/player-body.d.ts +1 -1
- package/dist/dev/player-body.d.ts.map +1 -1
- package/dist/dev/player-body.js +8 -0
- package/dist/dev/player-body.js.map +1 -1
- package/dist/dev/sound-clips.d.ts +3 -2
- package/dist/dev/sound-clips.d.ts.map +1 -1
- package/dist/dev/sound-clips.js +3 -2
- package/dist/dev/sound-clips.js.map +1 -1
- package/dist/dev/soundtrack.d.ts +115 -0
- package/dist/dev/soundtrack.d.ts.map +1 -0
- package/dist/dev/soundtrack.js +369 -0
- package/dist/dev/soundtrack.js.map +1 -0
- package/dist/dev/video-clip-panel.js +1 -1
- package/dist/dev/video-clip-panel.js.map +1 -1
- package/dist/dev/voice/chirp.d.ts +27 -0
- package/dist/dev/voice/chirp.d.ts.map +1 -0
- package/dist/dev/voice/chirp.js +107 -0
- package/dist/dev/voice/chirp.js.map +1 -0
- package/dist/dev/voice/folder.d.ts +18 -0
- package/dist/dev/voice/folder.d.ts.map +1 -0
- package/dist/dev/voice/folder.js +68 -0
- package/dist/dev/voice/folder.js.map +1 -0
- package/dist/dev/voice/voice-panel.d.ts +44 -0
- package/dist/dev/voice/voice-panel.d.ts.map +1 -0
- package/dist/dev/voice/voice-panel.js +418 -0
- package/dist/dev/voice/voice-panel.js.map +1 -0
- package/dist/dev/voice/voice-recorder.d.ts +141 -0
- package/dist/dev/voice/voice-recorder.d.ts.map +1 -0
- package/dist/dev/voice/voice-recorder.js +506 -0
- package/dist/dev/voice/voice-recorder.js.map +1 -0
- package/dist/src/showable.d.ts +9 -0
- package/dist/src/showable.d.ts.map +1 -1
- package/dist/src/showable.js.map +1 -1
- package/dist/src/snapshot.d.ts.map +1 -1
- package/dist/src/snapshot.js +27 -11
- package/dist/src/snapshot.js.map +1 -1
- package/package.json +1 -1
- package/src/showable.ts +9 -0
- package/src/snapshot.ts +30 -15
package/dev/player-body.ts
CHANGED
|
@@ -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);
|
package/dev/sound-clips.ts
CHANGED
|
@@ -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.
|
|
30
|
-
*
|
|
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,434 @@
|
|
|
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.request();
|
|
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.request();
|
|
164
|
+
}
|
|
165
|
+
|
|
166
|
+
#load(url: string): Promise<AudioBuffer> {
|
|
167
|
+
return this.#decoding.getOrInsertComputed(url, () => {
|
|
168
|
+
const promise = this.#decode(url).then(
|
|
169
|
+
(buffer) => {
|
|
170
|
+
// forget() may have come in the meantime.
|
|
171
|
+
if (this.#decoding.get(url) === promise) {
|
|
172
|
+
this.#decoded.set(url, buffer);
|
|
173
|
+
this.#options.onDecoded?.();
|
|
174
|
+
if (this.#anchor) this.#resync();
|
|
175
|
+
}
|
|
176
|
+
return buffer;
|
|
177
|
+
},
|
|
178
|
+
(reason) => {
|
|
179
|
+
if (this.#decoding.get(url) === promise) this.#failed.add(url);
|
|
180
|
+
debugLog("audio", `Skipped "${url}": ${reason}`);
|
|
181
|
+
throw reason;
|
|
182
|
+
},
|
|
183
|
+
);
|
|
184
|
+
// ready() looks at failures with allSettled(). This is for everyone else.
|
|
185
|
+
promise.catch(() => {});
|
|
186
|
+
return promise;
|
|
187
|
+
});
|
|
188
|
+
}
|
|
189
|
+
|
|
190
|
+
async #decode(url: string): Promise<AudioBuffer> {
|
|
191
|
+
const time1 = performance.now();
|
|
192
|
+
const response = await fetchMedia(url);
|
|
193
|
+
const encoded = await response.arrayBuffer();
|
|
194
|
+
const time2 = performance.now();
|
|
195
|
+
// decodeAudioData() takes about ⅜ - ¾ of a second to decode 4 minutes and 18 seconds of audio.
|
|
196
|
+
const decoded = await this.#decoder.decodeAudioData(encoded);
|
|
197
|
+
const time3 = performance.now();
|
|
198
|
+
debugLog(
|
|
199
|
+
"audio",
|
|
200
|
+
`Decoded "${url}": ${(encoded.byteLength / 1024).toFixed(0)} KB, ` +
|
|
201
|
+
`read ${(time2 - time1).toFixed(0)} ms, decode ${(time3 - time2).toFixed(0)} ms`,
|
|
202
|
+
);
|
|
203
|
+
if (decoded.numberOfChannels === 1) return decoded;
|
|
204
|
+
// Average the channels, don't sum them: identical channels (the usual
|
|
205
|
+
// "stereo") come out exactly as they went in, where a sum would double
|
|
206
|
+
// the level and clip.
|
|
207
|
+
const mono = new AudioBuffer({
|
|
208
|
+
numberOfChannels: 1,
|
|
209
|
+
length: decoded.length,
|
|
210
|
+
sampleRate: decoded.sampleRate,
|
|
211
|
+
});
|
|
212
|
+
const out = mono.getChannelData(0);
|
|
213
|
+
for (let channel = 0; channel < decoded.numberOfChannels; channel++) {
|
|
214
|
+
const data = decoded.getChannelData(channel);
|
|
215
|
+
for (let i = 0; i < out.length; i++) out[i] += data[i];
|
|
216
|
+
}
|
|
217
|
+
const scale = 1 / decoded.numberOfChannels;
|
|
218
|
+
for (let i = 0; i < out.length; i++) out[i] *= scale;
|
|
219
|
+
return mono;
|
|
220
|
+
}
|
|
221
|
+
|
|
222
|
+
// MARK: The clip list
|
|
223
|
+
|
|
224
|
+
#clips: readonly PlacedSoundClip[] = [];
|
|
225
|
+
/** {@link #clips} and the video's length, as JSON: how a request knows nothing changed. */
|
|
226
|
+
#clipsJson = "";
|
|
227
|
+
#requested = false;
|
|
228
|
+
/** Every source a clip has named, so {@link SoundtrackOptions.onNewSource} only fires for new ones. */
|
|
229
|
+
readonly #knownSources = new Set<string>();
|
|
230
|
+
|
|
231
|
+
/**
|
|
232
|
+
* Something may have changed: a clip, a component's timing, the tree.
|
|
233
|
+
*
|
|
234
|
+
* Call it as often as you like, even several times per mouse move. Calls in the
|
|
235
|
+
* same task are combined into one, and that one does almost nothing unless a clip
|
|
236
|
+
* moved. Nothing here allocates anything the size of the video.
|
|
237
|
+
*/
|
|
238
|
+
request(): void {
|
|
239
|
+
if (this.#requested) return;
|
|
240
|
+
this.#requested = true;
|
|
241
|
+
queueMicrotask(() => this.#update());
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
#update(): void {
|
|
245
|
+
this.#requested = false;
|
|
246
|
+
const root = this.#options.root();
|
|
247
|
+
const clips = collectSoundClips(root);
|
|
248
|
+
const json = JSON.stringify([root.duration, clips]);
|
|
249
|
+
if (json === this.#clipsJson) return;
|
|
250
|
+
this.#clipsJson = json;
|
|
251
|
+
this.#clips = clips;
|
|
252
|
+
let newSource = false;
|
|
253
|
+
for (const { source } of clips) {
|
|
254
|
+
if (!this.#knownSources.has(source)) {
|
|
255
|
+
this.#knownSources.add(source);
|
|
256
|
+
newSource = true;
|
|
257
|
+
}
|
|
258
|
+
void this.#load(source).catch(() => {});
|
|
259
|
+
}
|
|
260
|
+
if (newSource) this.#options.onNewSource?.();
|
|
261
|
+
if (this.#anchor) this.#resync();
|
|
262
|
+
}
|
|
263
|
+
|
|
264
|
+
/**
|
|
265
|
+
* Resolves when every file the newest clip list names has been decoded, or has
|
|
266
|
+
* failed. The newest: if the list changes while this waits, it waits for that
|
|
267
|
+
* one too.
|
|
268
|
+
*/
|
|
269
|
+
async ready(): Promise<void> {
|
|
270
|
+
for (;;) {
|
|
271
|
+
if (this.#requested) this.#update();
|
|
272
|
+
const json = this.#clipsJson;
|
|
273
|
+
await Promise.allSettled(this.#clips.map(({ source }) => this.#load(source)));
|
|
274
|
+
if (!this.#requested && json === this.#clipsJson) return;
|
|
275
|
+
}
|
|
276
|
+
}
|
|
277
|
+
|
|
278
|
+
/**
|
|
279
|
+
* The soundtrack from `fromMs` to `toMs`, mixed into one mono buffer, for saving.
|
|
280
|
+
* Call {@link ready} first, or clips whose file isn't decoded yet are left out.
|
|
281
|
+
*/
|
|
282
|
+
mix(fromMs: number, toMs: number): AudioBuilder {
|
|
283
|
+
if (this.#requested) this.#update();
|
|
284
|
+
const builder = new AudioBuilder(
|
|
285
|
+
Math.max(0, toMs - fromMs),
|
|
286
|
+
SAMPLE_RATE,
|
|
287
|
+
);
|
|
288
|
+
for (const clip of this.#clips) {
|
|
289
|
+
const buffer = this.#decoded.get(clip.source);
|
|
290
|
+
if (buffer) {
|
|
291
|
+
builder.add(buffer, clip.startMs - fromMs, clip.trimMs, clip.lengthMs);
|
|
292
|
+
}
|
|
293
|
+
}
|
|
294
|
+
return builder;
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
// MARK: Playing
|
|
298
|
+
|
|
299
|
+
/** Undefined when stopped. */
|
|
300
|
+
#anchor: Anchor | undefined;
|
|
301
|
+
/**
|
|
302
|
+
* Changes whenever the anchor moves (a seek, a new speed). A node scheduled for an
|
|
303
|
+
* older anchor plays at the wrong times, so it has to be replaced.
|
|
304
|
+
*/
|
|
305
|
+
#anchorVersion = 0;
|
|
306
|
+
#nodes: PlayingNode[] = [];
|
|
307
|
+
|
|
308
|
+
/** Start playing at `anchor`, from scratch. */
|
|
309
|
+
play(anchor: Anchor): void {
|
|
310
|
+
this.stop();
|
|
311
|
+
this.#anchor = anchor;
|
|
312
|
+
this.#anchorVersion++;
|
|
313
|
+
for (const clip of this.#clips) {
|
|
314
|
+
this.#schedule(clip, anchor.mediaMs);
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
/**
|
|
319
|
+
* Keep playing, at a new speed. `anchor` must agree with the old one about where
|
|
320
|
+
* the video is now, so nothing jumps.
|
|
321
|
+
*/
|
|
322
|
+
changeRate(anchor: Anchor): void {
|
|
323
|
+
if (!this.#anchor) return;
|
|
324
|
+
// The nodes already playing are right again at once. The ones waiting to start
|
|
325
|
+
// were timed for the old speed, so all of them are replaced, a moment from now.
|
|
326
|
+
for (const { node } of this.#nodes) node.playbackRate.value = anchor.rate;
|
|
327
|
+
this.#anchor = anchor;
|
|
328
|
+
this.#anchorVersion++;
|
|
329
|
+
this.#resync();
|
|
330
|
+
}
|
|
331
|
+
|
|
332
|
+
/** Stop at once. */
|
|
333
|
+
stop(): void {
|
|
334
|
+
for (const { node } of this.#nodes) {
|
|
335
|
+
try {
|
|
336
|
+
node.stop();
|
|
337
|
+
} catch {
|
|
338
|
+
// Already stopped.
|
|
339
|
+
}
|
|
340
|
+
node.disconnect();
|
|
341
|
+
}
|
|
342
|
+
this.#nodes = [];
|
|
343
|
+
this.#anchor = undefined;
|
|
344
|
+
}
|
|
345
|
+
|
|
346
|
+
/** The video's time at `contextTime`, by the current anchor. */
|
|
347
|
+
#mediaMsAt(contextTime: number): number {
|
|
348
|
+
const anchor = this.#anchor!;
|
|
349
|
+
return anchor.mediaMs + (contextTime - anchor.contextTime) * anchor.rate * 1000;
|
|
350
|
+
}
|
|
351
|
+
|
|
352
|
+
/**
|
|
353
|
+
* Identifies one clip at one place: equal keys play exactly the same sound at the
|
|
354
|
+
* same time, so a node can be kept.
|
|
355
|
+
*/
|
|
356
|
+
#keyOf(clip: PlacedSoundClip): string {
|
|
357
|
+
return JSON.stringify([clip.source, clip.startMs, clip.trimMs, clip.lengthMs]);
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
/**
|
|
361
|
+
* Bring the nodes up to date with {@link #clips}, while playing.
|
|
362
|
+
* A node whose clip is unchanged keeps playing. Every other node stops, and its
|
|
363
|
+
* replacement starts, at the same moment, {@link SWAP_AHEAD_S} from now.
|
|
364
|
+
*/
|
|
365
|
+
#resync(): void {
|
|
366
|
+
const swapTime = this.#options.context.currentTime + SWAP_AHEAD_S;
|
|
367
|
+
const fromMs = this.#mediaMsAt(swapTime);
|
|
368
|
+
/** Clips with no node yet, by key. An array, in case two clips are identical. */
|
|
369
|
+
const unplayed = new Map<string, PlacedSoundClip[]>();
|
|
370
|
+
for (const clip of this.#clips) {
|
|
371
|
+
unplayed.getOrInsertComputed(this.#keyOf(clip), () => []).push(clip);
|
|
372
|
+
}
|
|
373
|
+
const kept: PlayingNode[] = [];
|
|
374
|
+
for (const playing of this.#nodes) {
|
|
375
|
+
const waiting = unplayed.get(playing.key);
|
|
376
|
+
if (playing.anchorVersion === this.#anchorVersion && waiting?.length) {
|
|
377
|
+
waiting.pop();
|
|
378
|
+
kept.push(playing);
|
|
379
|
+
} else {
|
|
380
|
+
try {
|
|
381
|
+
playing.node.stop(swapTime);
|
|
382
|
+
} catch {
|
|
383
|
+
// Already stopped.
|
|
384
|
+
}
|
|
385
|
+
playing.node.onended = () => playing.node.disconnect();
|
|
386
|
+
}
|
|
387
|
+
}
|
|
388
|
+
this.#nodes = kept;
|
|
389
|
+
for (const clips of unplayed.values()) {
|
|
390
|
+
for (const clip of clips) this.#schedule(clip, fromMs);
|
|
391
|
+
}
|
|
392
|
+
}
|
|
393
|
+
|
|
394
|
+
/**
|
|
395
|
+
* Start a node for the part of `clip` from `fromMs` on, in the video's time, if
|
|
396
|
+
* its file is decoded and there's anything left to play.
|
|
397
|
+
*/
|
|
398
|
+
#schedule(clip: PlacedSoundClip, fromMs: number): void {
|
|
399
|
+
const buffer = this.#decoded.get(clip.source);
|
|
400
|
+
const anchor = this.#anchor;
|
|
401
|
+
if (!buffer || !anchor) return;
|
|
402
|
+
let { startMs, trimMs, lengthMs } = clip;
|
|
403
|
+
if (trimMs < 0) {
|
|
404
|
+
// Nothing to play before the file starts: start later instead.
|
|
405
|
+
startMs -= trimMs;
|
|
406
|
+
lengthMs += trimMs;
|
|
407
|
+
trimMs = 0;
|
|
408
|
+
}
|
|
409
|
+
const endMs = Math.min(
|
|
410
|
+
startMs + lengthMs,
|
|
411
|
+
startMs + buffer.duration * 1000 - trimMs,
|
|
412
|
+
this.#options.root().duration,
|
|
413
|
+
);
|
|
414
|
+
// Nothing before the video starts, either, and nothing already played.
|
|
415
|
+
const beginMs = Math.max(startMs, fromMs, 0);
|
|
416
|
+
if (endMs - beginMs < 0.001) return;
|
|
417
|
+
const node = this.#options.context.createBufferSource();
|
|
418
|
+
node.buffer = buffer; // Shared, not copied.
|
|
419
|
+
node.playbackRate.value = anchor.rate;
|
|
420
|
+
node.connect(this.#options.destination);
|
|
421
|
+
// Only `when` depends on the speed. The offset and the duration are in the
|
|
422
|
+
// file's own time.
|
|
423
|
+
node.start(
|
|
424
|
+
anchor.contextTime + (beginMs - anchor.mediaMs) / 1000 / anchor.rate,
|
|
425
|
+
(trimMs + beginMs - startMs) / 1000,
|
|
426
|
+
(endMs - beginMs) / 1000,
|
|
427
|
+
);
|
|
428
|
+
this.#nodes.push({
|
|
429
|
+
node,
|
|
430
|
+
key: this.#keyOf(clip),
|
|
431
|
+
anchorVersion: this.#anchorVersion,
|
|
432
|
+
});
|
|
433
|
+
}
|
|
434
|
+
}
|
package/dev/video-clip-panel.ts
CHANGED
|
@@ -485,7 +485,7 @@ export function buildVideoClipPanel(
|
|
|
485
485
|
return;
|
|
486
486
|
}
|
|
487
487
|
if (!isRealTime(speed)) {
|
|
488
|
-
//
|
|
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;
|
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The chirp that starts a voice recording, and the code that finds it in the recording.
|
|
3
|
+
*
|
|
4
|
+
* The chirp is a sweep: a tone that slides smoothly from one pitch to another. Lining a sweep up
|
|
5
|
+
* with its recording only works at one exact position, so it can be found to a small fraction of a
|
|
6
|
+
* millisecond, even with a train going by. A plain beep's start is fuzzy.
|
|
7
|
+
*
|
|
8
|
+
* Copied from riemann-surfaces-3d's src/recording/calibration-sounds.ts (9bbe2f9), with only the
|
|
9
|
+
* Start sound, and quieter. See development-plans/voice-recording.md.
|
|
10
|
+
* @module
|
|
11
|
+
*/
|
|
12
|
+
|
|
13
|
+
/** One sweep, from one frequency to another, in Hz. */
|
|
14
|
+
type Sweep = { from: number; to: number; seconds: number };
|
|
15
|
+
|
|
16
|
+
/** Riemann's Start sound: a rising sweep. */
|
|
17
|
+
const CHIRP: Sweep = { from: 400, to: 4000, seconds: 0.2 };
|
|
18
|
+
|
|
19
|
+
/**
|
|
20
|
+
* About −28 dBFS. Riemann's was 0.3, about −10 dBFS, and it reached a MacBook Air's mic at almost 5
|
|
21
|
+
* times full scale. It was found easily (matches 0.37–0.75), so 17 dB quieter should still work.
|
|
22
|
+
*/
|
|
23
|
+
const AMPLITUDE = 0.04;
|
|
24
|
+
/** Fade in and out over this long, so there are no clicks. */
|
|
25
|
+
const FADE_SECONDS = 0.006;
|
|
26
|
+
|
|
27
|
+
/** The chirp's samples, at this sample rate. */
|
|
28
|
+
export function chirpSamples(sampleRate: number): Float32Array<ArrayBuffer> {
|
|
29
|
+
return sweepSamples(CHIRP, sampleRate);
|
|
30
|
+
}
|
|
31
|
+
|
|
32
|
+
/** An exponential sweep: every octave gets the same amount of time, so it sounds even. */
|
|
33
|
+
function sweepSamples({ from, to, seconds }: Sweep, sampleRate: number) {
|
|
34
|
+
const count = Math.round(seconds * sampleRate);
|
|
35
|
+
const samples = new Float32Array(count);
|
|
36
|
+
const k = Math.log(to / from);
|
|
37
|
+
for (let i = 0; i < count; i++) {
|
|
38
|
+
const t = i / sampleRate;
|
|
39
|
+
const phase = (2 * Math.PI * from * seconds * (Math.exp((t * k) / seconds) - 1)) / k;
|
|
40
|
+
samples[i] = AMPLITUDE * Math.sin(phase);
|
|
41
|
+
}
|
|
42
|
+
const fade = Math.min(count / 2, Math.round(FADE_SECONDS * sampleRate));
|
|
43
|
+
for (let i = 0; i < fade; i++) {
|
|
44
|
+
const gain = 0.5 - 0.5 * Math.cos((Math.PI * i) / fade);
|
|
45
|
+
samples[i] *= gain;
|
|
46
|
+
samples[count - 1 - i] *= gain;
|
|
47
|
+
}
|
|
48
|
+
return samples;
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
export type Found = {
|
|
52
|
+
/** Where the sound starts in the recording, in samples. Not a whole number: it's interpolated. */
|
|
53
|
+
position: number;
|
|
54
|
+
/** How well it matched, 0 to 1. Above about 0.1 means it really is there. Noise alone scores about 0.03. */
|
|
55
|
+
match: number;
|
|
56
|
+
/** The loudest sample in the match, as dBFS. */
|
|
57
|
+
peakDb: number;
|
|
58
|
+
};
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Find a sound in a recording, starting somewhere from `from` to `to` (sample indexes). It searches
|
|
62
|
+
* coarsely first, at a quarter of the sample rate, then exactly around the best spot.
|
|
63
|
+
*/
|
|
64
|
+
export function findSound(
|
|
65
|
+
recording: Float32Array,
|
|
66
|
+
sound: Float32Array,
|
|
67
|
+
from: number,
|
|
68
|
+
to: number,
|
|
69
|
+
): Found {
|
|
70
|
+
const first = Math.max(0, Math.floor(from));
|
|
71
|
+
const last = Math.min(recording.length - sound.length, Math.ceil(to));
|
|
72
|
+
if (last < first) {
|
|
73
|
+
return { position: NaN, match: 0, peakDb: -Infinity };
|
|
74
|
+
}
|
|
75
|
+
const soundEnergy = energy(sound, 0, sound.length, 1);
|
|
76
|
+
const score = (lag: number, step: number) => {
|
|
77
|
+
let sum = 0;
|
|
78
|
+
for (let i = 0; i < sound.length; i += step) {
|
|
79
|
+
sum += sound[i] * recording[lag + i];
|
|
80
|
+
}
|
|
81
|
+
const norm = Math.sqrt(energy(recording, lag, sound.length, step) * (soundEnergy / step));
|
|
82
|
+
return norm > 0 ? sum / norm : 0;
|
|
83
|
+
};
|
|
84
|
+
// Coarse: every 4th lag, every 4th sample.
|
|
85
|
+
let best = first;
|
|
86
|
+
let bestScore = -Infinity;
|
|
87
|
+
for (let lag = first; lag <= last; lag += 4) {
|
|
88
|
+
const s = score(lag, 4);
|
|
89
|
+
if (s > bestScore) {
|
|
90
|
+
bestScore = s;
|
|
91
|
+
best = lag;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
// Exact: every lag near the best one, every sample.
|
|
95
|
+
const exact = new Map<number, number>();
|
|
96
|
+
for (let lag = Math.max(first, best - 6); lag <= Math.min(last, best + 6); lag++) {
|
|
97
|
+
exact.set(lag, score(lag, 1));
|
|
98
|
+
}
|
|
99
|
+
for (const [lag, s] of exact) {
|
|
100
|
+
if (s > (exact.get(best) ?? -Infinity)) {
|
|
101
|
+
best = lag;
|
|
102
|
+
}
|
|
103
|
+
}
|
|
104
|
+
// Between samples: fit a parabola through the best score and its neighbors.
|
|
105
|
+
const here = exact.get(best) ?? 0;
|
|
106
|
+
const before = exact.get(best - 1);
|
|
107
|
+
const after = exact.get(best + 1);
|
|
108
|
+
let position = best;
|
|
109
|
+
if (before !== undefined && after !== undefined) {
|
|
110
|
+
const curve = before - 2 * here + after;
|
|
111
|
+
if (curve < 0) {
|
|
112
|
+
position += (0.5 * (before - after)) / curve;
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
let peak = 0;
|
|
116
|
+
for (let i = best; i < best + sound.length; i++) {
|
|
117
|
+
peak = Math.max(peak, Math.abs(recording[i]));
|
|
118
|
+
}
|
|
119
|
+
return { position, match: Math.max(0, here), peakDb: 20 * Math.log10(peak || 1e-12) };
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function energy(samples: Float32Array, start: number, length: number, step: number) {
|
|
123
|
+
let sum = 0;
|
|
124
|
+
for (let i = 0; i < length; i += step) {
|
|
125
|
+
const v = samples[start + i];
|
|
126
|
+
sum += v * v;
|
|
127
|
+
}
|
|
128
|
+
return sum;
|
|
129
|
+
}
|
|
@@ -0,0 +1,84 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The folder where voice recordings are saved, remembered between visits. The browser can keep the
|
|
3
|
+
* folder's handle in IndexedDB. In each new session it asks for permission again, and that has to
|
|
4
|
+
* happen during a click.
|
|
5
|
+
*
|
|
6
|
+
* Copied from riemann-surfaces-3d's src/recording/folder.ts (9bbe2f9), with its own database name.
|
|
7
|
+
* See development-plans/voice-recording.md.
|
|
8
|
+
* @module
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
/** Permission methods that Chrome has but TypeScript's DOM types don't include yet. */
|
|
12
|
+
type WithPermission = FileSystemDirectoryHandle & {
|
|
13
|
+
queryPermission?(options: { mode: "readwrite" }): Promise<PermissionState>;
|
|
14
|
+
requestPermission?(options: { mode: "readwrite" }): Promise<PermissionState>;
|
|
15
|
+
};
|
|
16
|
+
|
|
17
|
+
const DATABASE = "canvas-recorder-voice";
|
|
18
|
+
const STORE = "folders";
|
|
19
|
+
const KEY = "takes";
|
|
20
|
+
|
|
21
|
+
function inStore<T>(
|
|
22
|
+
mode: IDBTransactionMode,
|
|
23
|
+
run: (store: IDBObjectStore) => IDBRequest<T>,
|
|
24
|
+
): Promise<T> {
|
|
25
|
+
return new Promise((resolve, reject) => {
|
|
26
|
+
const open = indexedDB.open(DATABASE, 1);
|
|
27
|
+
open.onupgradeneeded = () => open.result.createObjectStore(STORE);
|
|
28
|
+
open.onerror = () => reject(open.error);
|
|
29
|
+
open.onsuccess = () => {
|
|
30
|
+
const request = run(open.result.transaction(STORE, mode).objectStore(STORE));
|
|
31
|
+
request.onsuccess = () => resolve(request.result);
|
|
32
|
+
request.onerror = () => reject(request.error);
|
|
33
|
+
};
|
|
34
|
+
});
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
/** The folder chosen last time, if there is one. */
|
|
38
|
+
export async function rememberedFolder(): Promise<FileSystemDirectoryHandle | undefined> {
|
|
39
|
+
try {
|
|
40
|
+
return await inStore("readonly", (store) => store.get(KEY));
|
|
41
|
+
} catch {
|
|
42
|
+
return undefined;
|
|
43
|
+
}
|
|
44
|
+
}
|
|
45
|
+
|
|
46
|
+
/** Save recordings here from now on. */
|
|
47
|
+
export async function rememberFolder(folder: FileSystemDirectoryHandle): Promise<void> {
|
|
48
|
+
await inStore("readwrite", (store) => store.put(folder, KEY));
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
/** Ask the user for a folder. Undefined if they cancel. Call this from a click. */
|
|
52
|
+
export async function chooseFolder(): Promise<FileSystemDirectoryHandle | undefined> {
|
|
53
|
+
const picker = (
|
|
54
|
+
window as unknown as {
|
|
55
|
+
showDirectoryPicker?: (options: object) => Promise<FileSystemDirectoryHandle>;
|
|
56
|
+
}
|
|
57
|
+
).showDirectoryPicker;
|
|
58
|
+
if (!picker) {
|
|
59
|
+
throw new Error("This browser can't save into a folder. Try Chrome.");
|
|
60
|
+
}
|
|
61
|
+
try {
|
|
62
|
+
const folder = await picker({ id: "voice-recordings", mode: "readwrite" });
|
|
63
|
+
await rememberFolder(folder);
|
|
64
|
+
return folder;
|
|
65
|
+
} catch (error) {
|
|
66
|
+
if (error instanceof DOMException && error.name == "AbortError") {
|
|
67
|
+
return undefined;
|
|
68
|
+
}
|
|
69
|
+
throw error;
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/** 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> {
|
|
75
|
+
const handle = folder as WithPermission;
|
|
76
|
+
// Folders that don't need permission, like the browser's private storage, don't have these.
|
|
77
|
+
if (!handle.queryPermission || !handle.requestPermission) {
|
|
78
|
+
return true;
|
|
79
|
+
}
|
|
80
|
+
if ((await handle.queryPermission({ mode: "readwrite" })) == "granted") {
|
|
81
|
+
return true;
|
|
82
|
+
}
|
|
83
|
+
return ask && (await handle.requestPermission({ mode: "readwrite" })) == "granted";
|
|
84
|
+
}
|