apertaluce 0.0.0-stage → 0.2.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.
@@ -0,0 +1,83 @@
1
+ import { type BalanceKey } from "./balance.ts";
2
+ /** Bump when the sequence layout changes; old keys keep detecting old sound. */
3
+ export declare const AUDIO_MARK_SCHEME = 1;
4
+ /**
5
+ * Level of the mark under the sound's smoothed spectrum, as an amplitude ratio:
6
+ * 0.05 is 26 dB below, about where a tone stops masking noise in its own
7
+ * critical band.
8
+ */
9
+ export declare const AUDIO_MARK_LEVEL = 0.05;
10
+ export interface AudioKey {
11
+ /** One period of the unit-variance sequence, {@link OVERSAMPLING} times finer than {@link RATE}. */
12
+ table: Float32Array;
13
+ /** conj(FFT) of one period at {@link RATE}. */
14
+ spectrum: Float64Array;
15
+ /** The grid of the second layer (balance.ts). */
16
+ balance: BalanceKey;
17
+ id: string;
18
+ }
19
+ /** Derives the sequence of a key. `secret` is any byte string with at least 128 bits of entropy. */
20
+ export declare function deriveAudioKey(secret: Uint8Array | string, id?: string): Promise<AudioKey>;
21
+ export interface AudioMarkOptions {
22
+ /** Multiplies the level of the sequence; 1 is the tuned default. */
23
+ strength?: number;
24
+ /** `false` leaves out the second layer (balance.ts) and its delay of about a fifth of a second. */
25
+ balance?: boolean;
26
+ }
27
+ export interface AudioMarker {
28
+ /** Takes the next samples of one channel and returns marked samples, {@link delay} samples behind. */
29
+ process(input: Float32Array): Float32Array;
30
+ /** Returns the samples still held back. Call once, at the end. */
31
+ flush(): Float32Array;
32
+ /** Samples the output runs behind the input. */
33
+ readonly delay: number;
34
+ }
35
+ /**
36
+ * A streaming embedder for one channel. The sound passes through untouched and
37
+ * the mark is added to it; samples come out one frame late. Channels of one
38
+ * recording get their own marker with the same key, which keeps the mark in a
39
+ * mono mix-down.
40
+ */
41
+ export declare function createAudioMarker(key: AudioKey, sampleRate: number, options?: AudioMarkOptions): AudioMarker;
42
+ /** Adds the mark to whole channels in place. Returns the level of the sound over the level of the mark, in dB. */
43
+ export declare function embedAudioMark(channels: Float32Array | Float32Array[], sampleRate: number, key: AudioKey, options?: AudioMarkOptions): {
44
+ snr: number;
45
+ };
46
+ export interface AudioMarkResult {
47
+ detected: boolean;
48
+ /** Peak of the fold/key correlation in standard deviations of its own surface. */
49
+ score: number;
50
+ /** The score a sound must reach: higher for a stretch picked out of a longer sound. */
51
+ cut: number;
52
+ /** Seconds of sound the best score was read from, and where they start. */
53
+ seconds: number;
54
+ start: number;
55
+ /** Which layer answered: the sequence (exact copies), or the band balance (copies at another tempo or pitch). */
56
+ layer: "sequence" | "balance" | "none";
57
+ /** Read from the band balance: how much faster the copy plays, and its pitch shift in semitones. */
58
+ tempo?: number;
59
+ pitch?: number;
60
+ /** The best agreement of the band balance, whatever layer answered. */
61
+ balanceScore?: number;
62
+ keyId: string;
63
+ }
64
+ /**
65
+ * Decision cuts in standard deviations of the correlation surface, which has
66
+ * one value per shift of the sequence (32,768 of them). A stretch picked out
67
+ * of a longer sound is one of several looks, so its cut is higher.
68
+ */
69
+ export declare const AUDIO_CUT = 6.5;
70
+ export declare const AUDIO_STRETCH_CUT = 7;
71
+ /** Cuts of the band balance: read as it is (256 looks), and searched over tempo and pitch (about half a million). */
72
+ export declare const BALANCE_CUT = 7;
73
+ export declare const BALANCE_SEARCH_CUT = 8.5;
74
+ export interface AudioDetectOptions {
75
+ /** `false` skips the search over tempo and pitch, which costs a few seconds on sound that carries no mark. */
76
+ search?: boolean;
77
+ }
78
+ /**
79
+ * Looks for the mark of `key` in a sound (one channel, or several that are
80
+ * mixed down). Reads the whole sound, and a long sound also in stretches of
81
+ * about eight seconds, so a marked passage inside other material is found.
82
+ */
83
+ export declare function detectAudioMark(channels: Float32Array | Float32Array[], sampleRate: number, key: AudioKey, options?: AudioDetectOptions): AudioMarkResult;
@@ -0,0 +1,458 @@
1
+ /**
2
+ * Inaudible mark for sound: one keyed, band-limited noise sequence repeated
3
+ * end to end and added under the sound, shaped to follow the sound's own
4
+ * spectrum from moment to moment so the ear's masking hides it.
5
+ *
6
+ * Why a repeated sequence: a copy that was trimmed, padded or cut into another
7
+ * file has lost its own start, so the detector cannot line anything up with
8
+ * the file. A periodic sequence needs no start: the detector folds the suspect
9
+ * at the period and correlates the fold with the key sequence over every
10
+ * cyclic shift at once. A cut is a shift.
11
+ *
12
+ * The sequence has a flat spectrum inside its band, so its correlation with
13
+ * itself is one sharp point. The detector first divides the sound by its own
14
+ * smoothed spectrum, which turns the mark back into the flat sequence and
15
+ * gives the quiet stretches between the sound's own partials (where the mark
16
+ * is strongest next to the sound) the most say.
17
+ *
18
+ * The sequence is derived from a secret key, so reading or forging the mark
19
+ * needs the key; the mark carries one bit (ours / not ours) per key. This
20
+ * module works on samples: decoding and encoding are the host's business.
21
+ */
22
+ import { fft } from "../fft.js";
23
+ import { BALANCE_RATE, createBalanceStage, deriveBalanceKey, readBalance, searchBalance } from "./balance.js";
24
+ import { resample } from "./resample.js";
25
+ /** Bump when the sequence layout changes; old keys keep detecting old sound. */
26
+ export const AUDIO_MARK_SCHEME = 1;
27
+ /** Rate the sequence is defined at and the detector works at. */
28
+ const RATE = 16_000;
29
+ /** One period of the sequence in samples at {@link RATE}: 2.048 s. */
30
+ const PERIOD = 32_768;
31
+ /** The key table holds the sequence this many times finer, for sounds at other rates. */
32
+ const OVERSAMPLING = 4;
33
+ /** Band of the sequence in Hz. Below: hum and rumble, where little masks it. Above: what low-bitrate codecs throw away. */
34
+ const BAND_LO = 500;
35
+ const BAND_HI = 6_000;
36
+ const BAND_EDGE = 120;
37
+ /**
38
+ * Level of the mark under the sound's smoothed spectrum, as an amplitude ratio:
39
+ * 0.05 is 26 dB below, about where a tone stops masking noise in its own
40
+ * critical band.
41
+ */
42
+ export const AUDIO_MARK_LEVEL = 0.05;
43
+ function sfc32(a, b, c, d) {
44
+ return () => {
45
+ a |= 0;
46
+ b |= 0;
47
+ c |= 0;
48
+ d |= 0;
49
+ const t = (((a + b) | 0) + d) | 0;
50
+ d = (d + 1) | 0;
51
+ a = b ^ (b >>> 9);
52
+ b = (c + (c << 3)) | 0;
53
+ c = (c << 21) | (c >>> 11);
54
+ c = (c + t) | 0;
55
+ return (t >>> 0) / 4294967296;
56
+ };
57
+ }
58
+ /** Weight of the band at `hz`, with raised-cosine edges. */
59
+ function bandWeight(hz) {
60
+ if (hz <= BAND_LO - BAND_EDGE || hz >= BAND_HI + BAND_EDGE)
61
+ return 0;
62
+ if (hz < BAND_LO)
63
+ return 0.5 - 0.5 * Math.cos((Math.PI * (hz - (BAND_LO - BAND_EDGE))) / BAND_EDGE);
64
+ if (hz > BAND_HI)
65
+ return 0.5 + 0.5 * Math.cos((Math.PI * (hz - BAND_HI)) / BAND_EDGE);
66
+ return 1;
67
+ }
68
+ /** Derives the sequence of a key. `secret` is any byte string with at least 128 bits of entropy. */
69
+ export async function deriveAudioKey(secret, id = "k1") {
70
+ const bytes = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
71
+ const label = new TextEncoder().encode(`audio-mark/${AUDIO_MARK_SCHEME}/`);
72
+ const input = new Uint8Array(label.length + bytes.length);
73
+ input.set(label);
74
+ input.set(bytes, label.length);
75
+ const digest = new Uint32Array(await crypto.subtle.digest("SHA-256", input));
76
+ const random = sfc32(digest[0], digest[1], digest[2], digest[3]);
77
+ for (let i = 0; i < 16; i++)
78
+ random();
79
+ // Every frequency of the band at the same strength with a random phase.
80
+ const fine = PERIOD * OVERSAMPLING;
81
+ const coarse = new Float64Array(2 * PERIOD);
82
+ const dense = new Float64Array(2 * fine);
83
+ let energy = 0;
84
+ for (let k = 1; k < PERIOD / 2; k++) {
85
+ const weight = bandWeight((k * RATE) / PERIOD);
86
+ if (weight === 0)
87
+ continue;
88
+ const phase = 2 * Math.PI * random();
89
+ const re = weight * Math.cos(phase);
90
+ const im = weight * Math.sin(phase);
91
+ coarse[2 * k] = dense[2 * k] = re;
92
+ coarse[2 * k + 1] = dense[2 * k + 1] = im;
93
+ coarse[2 * (PERIOD - k)] = dense[2 * (fine - k)] = re;
94
+ coarse[2 * (PERIOD - k) + 1] = dense[2 * (fine - k) + 1] = -im;
95
+ energy += 2 * weight * weight;
96
+ }
97
+ // Unit variance in time: mean square of the inverse transform is energy / PERIOD².
98
+ const norm = PERIOD / Math.sqrt(energy);
99
+ fft(dense, fine, true);
100
+ const table = new Float32Array(fine);
101
+ for (let i = 0; i < fine; i++)
102
+ table[i] = dense[2 * i] * OVERSAMPLING * norm;
103
+ const spectrum = new Float64Array(2 * PERIOD);
104
+ for (let k = 0; k < PERIOD; k++) {
105
+ spectrum[2 * k] = coarse[2 * k] * norm;
106
+ spectrum[2 * k + 1] = -coarse[2 * k + 1] * norm;
107
+ }
108
+ return { table, spectrum, balance: deriveBalanceKey(random), id };
109
+ }
110
+ /** The sequence at `position` samples of {@link RATE} (any real number), by cubic interpolation in the fine table. */
111
+ function sequenceAt(table, position) {
112
+ const length = table.length;
113
+ let x = (position * OVERSAMPLING) % length;
114
+ if (x < 0)
115
+ x += length;
116
+ const i = Math.floor(x);
117
+ const t = x - i;
118
+ const p0 = table[(i - 1 + length) % length];
119
+ const p1 = table[i];
120
+ const p2 = table[(i + 1) % length];
121
+ const p3 = table[(i + 2) % length];
122
+ return p1 + 0.5 * t * (p2 - p0 + t * (2 * p0 - 5 * p1 + 4 * p2 - p3 + t * (3 * (p1 - p2) + p3 - p0)));
123
+ }
124
+ const analyses = new Map();
125
+ /** Frames of about 24–32 ms: short enough that the mark does not run ahead of an attack, long enough to resolve partials. */
126
+ function analysisFor(rate) {
127
+ let cached = analyses.get(rate);
128
+ if (cached)
129
+ return cached;
130
+ let size = 256;
131
+ while (size < 0.024 * rate)
132
+ size *= 2;
133
+ const hop = size / 4;
134
+ const window = new Float64Array(size);
135
+ // Root of a Hann window: applied on the way in and on the way out, four overlapping frames sum to 2.
136
+ for (let i = 0; i < size; i++)
137
+ window[i] = Math.sin((Math.PI * i) / size);
138
+ const bin = rate / size;
139
+ const first = Math.max(1, Math.ceil((BAND_LO - BAND_EDGE) / bin));
140
+ const last = Math.min(size / 2 - 1, Math.floor((BAND_HI + BAND_EDGE) / bin));
141
+ const weight = new Float64Array(size / 2);
142
+ const from = new Int32Array(size / 2);
143
+ const to = new Int32Array(size / 2);
144
+ for (let k = 1; k < size / 2; k++) {
145
+ const hz = k * bin;
146
+ weight[k] = bandWeight(hz);
147
+ const half = Math.max(50, 0.1 * hz) / bin;
148
+ from[k] = Math.max(1, Math.round(k - half));
149
+ to[k] = Math.min(size / 2 - 1, Math.round(k + half));
150
+ }
151
+ cached = { size, hop, window, first, last, weight, from, to };
152
+ analyses.set(rate, cached);
153
+ return cached;
154
+ }
155
+ /** Smoothed power per band bin from one frame's spectrum; `prefix` is scratch of size/2 + 1. */
156
+ function smoothedPower(spectrum, analysis, prefix, out) {
157
+ const half = analysis.size / 2;
158
+ prefix[0] = 0;
159
+ for (let k = 0; k < half; k++)
160
+ prefix[k + 1] = prefix[k] + spectrum[2 * k] ** 2 + spectrum[2 * k + 1] ** 2;
161
+ for (let k = analysis.first; k <= analysis.last; k++) {
162
+ const a = analysis.from[k];
163
+ const b = analysis.to[k];
164
+ out[k] = (prefix[b + 1] - prefix[a]) / (b - a + 1);
165
+ }
166
+ }
167
+ /**
168
+ * A streaming embedder for one channel. The sound passes through untouched and
169
+ * the mark is added to it; samples come out one frame late. Channels of one
170
+ * recording get their own marker with the same key, which keeps the mark in a
171
+ * mono mix-down.
172
+ */
173
+ export function createAudioMarker(key, sampleRate, options = {}) {
174
+ const sequence = createSequenceStage(key, sampleRate, options);
175
+ if (options.balance === false)
176
+ return sequence;
177
+ // The band balance is set first; the sequence is laid over the result.
178
+ const balance = createBalanceStage(key.balance, sampleRate);
179
+ return {
180
+ delay: balance.delay + sequence.delay,
181
+ process: (input) => sequence.process(balance.process(input)),
182
+ flush() {
183
+ const head = sequence.process(balance.flush());
184
+ const tail = sequence.flush();
185
+ const out = new Float32Array(head.length + tail.length);
186
+ out.set(head);
187
+ out.set(tail, head.length);
188
+ return out;
189
+ },
190
+ };
191
+ }
192
+ function createSequenceStage(key, sampleRate, options) {
193
+ const analysis = analysisFor(sampleRate);
194
+ const { size, hop, window, first, last, weight } = analysis;
195
+ const level = AUDIO_MARK_LEVEL * (options.strength ?? 1);
196
+ const step = RATE / sampleRate;
197
+ const delay = size - hop;
198
+ const frame = new Float32Array(size);
199
+ const overlap = new Float64Array(size);
200
+ const host = new Float64Array(2 * size);
201
+ const sequence = new Float64Array(2 * size);
202
+ const scratch = new Float64Array(2 * size);
203
+ const prefix = new Float64Array(size / 2 + 1);
204
+ const power = new Float64Array(size / 2);
205
+ const previous = new Float64Array(size / 2);
206
+ const carry = new Float32Array(hop);
207
+ let carried = 0;
208
+ /** Index in the input of frame[0]; the stream starts with `delay` samples of silence. */
209
+ let start = -delay - hop;
210
+ let toSkip = delay;
211
+ let received = 0;
212
+ let emitted = 0;
213
+ function advance(next, out) {
214
+ frame.copyWithin(0, hop);
215
+ frame.set(next, size - hop);
216
+ start += hop;
217
+ let loud = 0;
218
+ for (let i = 0; i < size; i++) {
219
+ const value = frame[i] * window[i];
220
+ host[2 * i] = value;
221
+ host[2 * i + 1] = 0;
222
+ loud += value * value;
223
+ sequence[2 * i] = sequenceAt(key.table, (start + i) * step) * window[i];
224
+ sequence[2 * i + 1] = 0;
225
+ }
226
+ if (loud > 0) {
227
+ fft(host, size, false, scratch);
228
+ fft(sequence, size, false, scratch);
229
+ smoothedPower(host, analysis, prefix, power);
230
+ let reference = 0;
231
+ for (let k = first; k <= last; k++)
232
+ reference += sequence[2 * k] ** 2 + sequence[2 * k + 1] ** 2;
233
+ reference /= last - first + 1;
234
+ host.fill(0);
235
+ for (let k = first; k <= last; k++) {
236
+ const gain = level * Math.sqrt(power[k] / reference) * weight[k];
237
+ // An attack is not met at full level at once: the mark may double per hop, so it does not run ahead of the sound.
238
+ const used = Math.min(gain, 2 * previous[k]);
239
+ previous[k] = gain;
240
+ const re = used * sequence[2 * k];
241
+ const im = used * sequence[2 * k + 1];
242
+ host[2 * k] = re;
243
+ host[2 * k + 1] = im;
244
+ host[2 * (size - k)] = re;
245
+ host[2 * (size - k) + 1] = -im;
246
+ }
247
+ fft(host, size, true, scratch);
248
+ for (let i = 0; i < size; i++)
249
+ overlap[i] += host[2 * i] * window[i] * 0.5;
250
+ }
251
+ else {
252
+ previous.fill(0);
253
+ }
254
+ // The oldest hop of the frame is now complete.
255
+ for (let i = 0; i < hop; i++) {
256
+ if (toSkip > 0)
257
+ toSkip--;
258
+ else if (emitted < received) {
259
+ out.push(frame[i] + overlap[i]);
260
+ emitted++;
261
+ }
262
+ }
263
+ overlap.copyWithin(0, hop);
264
+ overlap.fill(0, size - hop);
265
+ }
266
+ function feed(input) {
267
+ const out = [];
268
+ let offset = 0;
269
+ while (offset < input.length) {
270
+ const take = Math.min(hop - carried, input.length - offset);
271
+ carry.set(input.subarray(offset, offset + take), carried);
272
+ carried += take;
273
+ offset += take;
274
+ if (carried === hop) {
275
+ advance(carry, out);
276
+ carried = 0;
277
+ }
278
+ }
279
+ return Float32Array.from(out);
280
+ }
281
+ return {
282
+ delay,
283
+ process(input) {
284
+ received += input.length;
285
+ return feed(input);
286
+ },
287
+ flush() {
288
+ const missing = received - emitted;
289
+ if (missing <= 0)
290
+ return new Float32Array(0);
291
+ // Silence pushes the held samples out.
292
+ const pad = new Float32Array(delay + hop - carried + hop);
293
+ return feed(pad).subarray(0, missing);
294
+ },
295
+ };
296
+ }
297
+ /** Adds the mark to whole channels in place. Returns the level of the sound over the level of the mark, in dB. */
298
+ export function embedAudioMark(channels, sampleRate, key, options = {}) {
299
+ let signal = 0;
300
+ let change = 0;
301
+ for (const channel of Array.isArray(channels) ? channels : [channels]) {
302
+ const marker = createAudioMarker(key, sampleRate, options);
303
+ const head = marker.process(channel);
304
+ const tail = marker.flush();
305
+ for (let i = 0; i < channel.length; i++) {
306
+ const marked = i < head.length ? head[i] : tail[i - head.length];
307
+ signal += channel[i] ** 2;
308
+ change += (marked - channel[i]) ** 2;
309
+ channel[i] = marked;
310
+ }
311
+ }
312
+ return { snr: change > 0 ? 10 * Math.log10(signal / change) : Infinity };
313
+ }
314
+ /**
315
+ * Decision cuts in standard deviations of the correlation surface, which has
316
+ * one value per shift of the sequence (32,768 of them). A stretch picked out
317
+ * of a longer sound is one of several looks, so its cut is higher.
318
+ */
319
+ export const AUDIO_CUT = 6.5;
320
+ export const AUDIO_STRETCH_CUT = 7;
321
+ /** Cuts of the band balance: read as it is (256 looks), and searched over tempo and pitch (about half a million). */
322
+ export const BALANCE_CUT = 7;
323
+ export const BALANCE_SEARCH_CUT = 8.5;
324
+ /** Periods per stretch when a long sound is also read piece by piece. */
325
+ const STRETCH = 4;
326
+ /** How far the divisor may fall under the smoothed level: keeps near-empty bins from shouting. */
327
+ const FLOOR = 0.3;
328
+ /** The sound divided by its smoothed spectrum, band-limited, at {@link RATE}. */
329
+ function whiten(samples, floor) {
330
+ const analysis = analysisFor(RATE);
331
+ const { size, hop, window, first, last, weight } = analysis;
332
+ const out = new Float32Array(samples.length);
333
+ const frame = new Float64Array(2 * size);
334
+ const scratch = new Float64Array(2 * size);
335
+ const prefix = new Float64Array(size / 2 + 1);
336
+ const power = new Float64Array(size / 2);
337
+ for (let start = -(size - hop); start < samples.length; start += hop) {
338
+ let loud = 0;
339
+ for (let i = 0; i < size; i++) {
340
+ const index = start + i;
341
+ const value = index >= 0 && index < samples.length ? samples[index] * window[i] : 0;
342
+ frame[2 * i] = value;
343
+ frame[2 * i + 1] = 0;
344
+ loud += value * value;
345
+ }
346
+ if (loud === 0)
347
+ continue;
348
+ fft(frame, size, false, scratch);
349
+ smoothedPower(frame, analysis, prefix, power);
350
+ for (let k = 0; k < size; k++) {
351
+ const bin = k <= size / 2 ? k : size - k;
352
+ if (bin < first || bin > last || power[bin] <= 0) {
353
+ frame[2 * k] = frame[2 * k + 1] = 0;
354
+ continue;
355
+ }
356
+ // Each bin by its own strength, never by less than `floor` of the level around it.
357
+ const own = frame[2 * k] ** 2 + frame[2 * k + 1] ** 2;
358
+ const gain = (weight[bin] * Math.sqrt(power[bin])) / (own + floor * floor * power[bin]);
359
+ frame[2 * k] *= gain;
360
+ frame[2 * k + 1] *= gain;
361
+ }
362
+ fft(frame, size, true, scratch);
363
+ for (let i = 0; i < size; i++) {
364
+ const index = start + i;
365
+ if (index >= 0 && index < samples.length)
366
+ out[index] += frame[2 * i] * window[i] * 0.5;
367
+ }
368
+ }
369
+ return out;
370
+ }
371
+ /** Peak of the correlation of one fold with the key sequence, in standard deviations of the surface. */
372
+ function correlate(fold, key, grid, scratch) {
373
+ for (let i = 0; i < PERIOD; i++) {
374
+ grid[2 * i] = fold[i];
375
+ grid[2 * i + 1] = 0;
376
+ }
377
+ fft(grid, PERIOD, false, scratch);
378
+ for (let k = 0; k < PERIOD; k++) {
379
+ const re = grid[2 * k] * key.spectrum[2 * k] - grid[2 * k + 1] * key.spectrum[2 * k + 1];
380
+ const im = grid[2 * k] * key.spectrum[2 * k + 1] + grid[2 * k + 1] * key.spectrum[2 * k];
381
+ grid[2 * k] = re;
382
+ grid[2 * k + 1] = im;
383
+ }
384
+ fft(grid, PERIOD, true, scratch);
385
+ let sum = 0;
386
+ let squares = 0;
387
+ let peak = -Infinity;
388
+ let shift = 0;
389
+ for (let i = 0; i < PERIOD; i++) {
390
+ const value = grid[2 * i];
391
+ sum += value;
392
+ squares += value * value;
393
+ if (value > peak) {
394
+ peak = value;
395
+ shift = i;
396
+ }
397
+ }
398
+ const mean = sum / PERIOD;
399
+ const deviation = Math.sqrt(Math.max(1e-30, squares / PERIOD - mean * mean));
400
+ return { score: (peak - mean) / deviation, shift };
401
+ }
402
+ /**
403
+ * Looks for the mark of `key` in a sound (one channel, or several that are
404
+ * mixed down). Reads the whole sound, and a long sound also in stretches of
405
+ * about eight seconds, so a marked passage inside other material is found.
406
+ */
407
+ export function detectAudioMark(channels, sampleRate, key, options = {}) {
408
+ let mono;
409
+ if (Array.isArray(channels)) {
410
+ mono = new Float32Array(channels[0]?.length ?? 0);
411
+ for (const channel of channels)
412
+ for (let i = 0; i < mono.length; i++)
413
+ mono[i] += (channel[i] ?? 0) / channels.length;
414
+ }
415
+ else
416
+ mono = channels;
417
+ const plain = resample(mono, sampleRate, RATE);
418
+ const sequence = detectSequence(whiten(plain, options.floor ?? FLOOR), key);
419
+ if (sequence.detected || plain.length < 2 * BALANCE_RATE)
420
+ return sequence;
421
+ let reading = readBalance(plain, key.balance);
422
+ let cut = BALANCE_CUT;
423
+ if (reading.score < cut && options.search !== false) {
424
+ reading = searchBalance(plain, key.balance);
425
+ cut = BALANCE_SEARCH_CUT;
426
+ }
427
+ if (reading.score < cut)
428
+ return { ...sequence, balanceScore: reading.score };
429
+ return { detected: true, score: reading.score, cut, seconds: plain.length / RATE, start: 0, layer: "balance", tempo: reading.tempo, pitch: 12 * reading.pitch, balanceScore: reading.score, keyId: key.id };
430
+ }
431
+ function detectSequence(sound, key) {
432
+ const none = { detected: false, score: 0, cut: AUDIO_CUT, seconds: sound.length / RATE, start: 0, layer: "none", keyId: key.id };
433
+ if (sound.length < RATE / 4)
434
+ return none;
435
+ const blocks = Math.ceil(sound.length / PERIOD);
436
+ const grid = new Float64Array(2 * PERIOD);
437
+ const scratch = new Float64Array(2 * PERIOD);
438
+ const whole = new Float64Array(PERIOD);
439
+ for (let i = 0; i < sound.length; i++)
440
+ whole[i % PERIOD] += sound[i];
441
+ const full = correlate(whole, key, grid, scratch);
442
+ let best = { ...none, score: full.score, detected: full.score >= AUDIO_CUT, layer: full.score >= AUDIO_CUT ? "sequence" : "none" };
443
+ if (best.detected || blocks < STRETCH + 2)
444
+ return best;
445
+ const fold = new Float64Array(PERIOD);
446
+ for (let block = 0; block + STRETCH <= blocks; block += STRETCH / 2) {
447
+ fold.fill(0);
448
+ const from = block * PERIOD;
449
+ const to = Math.min(sound.length, from + STRETCH * PERIOD);
450
+ for (let i = from; i < to; i++)
451
+ fold[i % PERIOD] += sound[i];
452
+ const stretch = correlate(fold, key, grid, scratch);
453
+ if (stretch.score >= AUDIO_STRETCH_CUT && stretch.score > best.score) {
454
+ best = { detected: true, score: stretch.score, cut: AUDIO_STRETCH_CUT, seconds: (to - from) / RATE, start: from / RATE, layer: "sequence", keyId: key.id };
455
+ }
456
+ }
457
+ return best;
458
+ }
@@ -0,0 +1,6 @@
1
+ /**
2
+ * Sample-rate conversion by a Kaiser-windowed sinc, for bringing any sound to
3
+ * the rate the mark is read at. Output sample `n` sits at exactly
4
+ * `n * from / to` input samples, so nothing drifts over a long file.
5
+ */
6
+ export declare function resample(input: Float32Array, from: number, to: number): Float32Array;
@@ -0,0 +1,77 @@
1
+ /**
2
+ * Sample-rate conversion by a Kaiser-windowed sinc, for bringing any sound to
3
+ * the rate the mark is read at. Output sample `n` sits at exactly
4
+ * `n * from / to` input samples, so nothing drifts over a long file.
5
+ */
6
+ const ZERO_CROSSINGS = 14;
7
+ const PHASES = 512;
8
+ const BETA = 9;
9
+ function besselI0(x) {
10
+ let sum = 1;
11
+ let term = 1;
12
+ for (let k = 1; k < 32; k++) {
13
+ term *= (x / (2 * k)) ** 2;
14
+ sum += term;
15
+ if (term < 1e-12 * sum)
16
+ break;
17
+ }
18
+ return sum;
19
+ }
20
+ const tables = new Map();
21
+ function kernel(from, to) {
22
+ const id = `${from}:${to}`;
23
+ let cached = tables.get(id);
24
+ if (cached)
25
+ return cached;
26
+ // Cut-off in cycles per input sample, a little under the lower Nyquist.
27
+ const cutoff = (0.46 * Math.min(from, to)) / from;
28
+ const half = Math.ceil(ZERO_CROSSINGS / (2 * cutoff));
29
+ const taps = 2 * half;
30
+ const table = new Float32Array(PHASES * taps);
31
+ const norm = besselI0(BETA);
32
+ for (let phase = 0; phase < PHASES; phase++) {
33
+ let sum = 0;
34
+ for (let tap = 0; tap < taps; tap++) {
35
+ const distance = tap - half + 1 - phase / PHASES;
36
+ const x = 2 * cutoff * distance;
37
+ const sinc = Math.abs(x) < 1e-9 ? 1 : Math.sin(Math.PI * x) / (Math.PI * x);
38
+ const span = distance / half;
39
+ const window = Math.abs(span) >= 1 ? 0 : besselI0(BETA * Math.sqrt(1 - span * span)) / norm;
40
+ const value = 2 * cutoff * sinc * window;
41
+ table[phase * taps + tap] = value;
42
+ sum += value;
43
+ }
44
+ // Unity gain at every phase, so a steady level stays steady.
45
+ for (let tap = 0; tap < taps; tap++)
46
+ table[phase * taps + tap] /= sum;
47
+ }
48
+ cached = { taps, half, table };
49
+ tables.set(id, cached);
50
+ return cached;
51
+ }
52
+ export function resample(input, from, to) {
53
+ if (from === to)
54
+ return input;
55
+ const { taps, half, table } = kernel(from, to);
56
+ const ratio = from / to;
57
+ const length = Math.floor(input.length / ratio);
58
+ const output = new Float32Array(length);
59
+ for (let n = 0; n < length; n++) {
60
+ const position = n * ratio;
61
+ let index = Math.floor(position);
62
+ let phase = Math.round((position - index) * PHASES);
63
+ if (phase === PHASES) {
64
+ phase = 0;
65
+ index++;
66
+ }
67
+ const first = index - half + 1;
68
+ const row = phase * taps;
69
+ let sum = 0;
70
+ const from0 = Math.max(0, -first);
71
+ const to0 = Math.min(taps, input.length - first);
72
+ for (let tap = from0; tap < to0; tap++)
73
+ sum += input[first + tap] * table[row + tap];
74
+ output[n] = sum;
75
+ }
76
+ return output;
77
+ }
package/lib/fft.d.ts ADDED
@@ -0,0 +1,10 @@
1
+ /**
2
+ * Radix-2 complex FFT for the small grids of the marks (one picture tile, one sound frame).
3
+ * Interleaved re/im in a Float64Array; sizes are powers of two.
4
+ */
5
+ /** In-place 1-D transform of `n` interleaved complex values. */
6
+ export declare function fft(data: Float64Array, n: number, inverse?: boolean, scratch?: Float64Array): void;
7
+ /** In-place 2-D transform of an `n`×`n` interleaved complex grid. */
8
+ export declare function fft2d(data: Float64Array, n: number, inverse?: boolean): void;
9
+ /** Real grid → interleaved complex grid. */
10
+ export declare function toComplex(real: ArrayLike<number>, n: number): Float64Array;