apertaluce 0.0.0-stage → 0.1.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/LICENSE +21 -0
- package/README.md +89 -2
- package/lib/audio/balance.d.ts +38 -0
- package/lib/audio/balance.js +455 -0
- package/lib/audio/index.d.ts +2 -0
- package/lib/audio/index.js +2 -0
- package/lib/audio/mark.d.ts +83 -0
- package/lib/audio/mark.js +458 -0
- package/lib/audio/resample.d.ts +6 -0
- package/lib/audio/resample.js +77 -0
- package/lib/fft.d.ts +10 -0
- package/lib/fft.js +82 -0
- package/lib/image/fingerprint.d.ts +21 -0
- package/lib/image/fingerprint.js +93 -0
- package/lib/image/index.d.ts +2 -0
- package/lib/image/index.js +2 -0
- package/lib/image/mark.d.ts +154 -0
- package/lib/image/mark.js +995 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +3 -0
- package/lib/video/index.d.ts +47 -0
- package/lib/video/index.js +76 -0
- package/package.json +59 -4
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 lofcz
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,90 @@
|
|
|
1
|
-
#
|
|
1
|
+
# apertaluce
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Keyed, invisible marks for pictures, sound and video that survive re-encoding and editing.
|
|
4
|
+
Pure TypeScript, no dependencies; runs in Node, Bun, Deno, browsers and edge runtimes.
|
|
5
|
+
|
|
6
|
+
A mark says one thing: this content was marked with this key. It carries no payload. Reading
|
|
7
|
+
or forging it needs the key. The library works on raw pixels and samples and never touches a
|
|
8
|
+
codec: decoding and encoding stay with the host.
|
|
9
|
+
|
|
10
|
+
```ts
|
|
11
|
+
import { derivePixelKey, embedPixelMark, detectPixelMark } from "apertaluce/image";
|
|
12
|
+
import { deriveAudioKey, createAudioMarker, embedAudioMark, detectAudioMark } from "apertaluce/audio";
|
|
13
|
+
import { frameMarkOverlayPgm, detectFrameMark } from "apertaluce/video";
|
|
14
|
+
|
|
15
|
+
const pixels = await derivePixelKey(secret);
|
|
16
|
+
embedPixelMark(rgba, pixels); // in place
|
|
17
|
+
detectPixelMark(suspectRgba, pixels).detected;
|
|
18
|
+
|
|
19
|
+
const sounds = await deriveAudioKey(secret);
|
|
20
|
+
embedAudioMark([left, right], 44_100, sounds); // in place; or createAudioMarker() for a stream
|
|
21
|
+
detectAudioMark(suspectSamples, 48_000, sounds).detected;
|
|
22
|
+
|
|
23
|
+
// Video: blend one grey plane onto the luma of every frame (ffmpeg: blend=all_mode=grainmerge),
|
|
24
|
+
// then read a dozen frames of the suspect.
|
|
25
|
+
const overlay = frameMarkOverlayPgm(1280, 720, pixels);
|
|
26
|
+
detectFrameMark(frames, pixels).detected;
|
|
27
|
+
```
|
|
28
|
+
|
|
29
|
+
## How it works
|
|
30
|
+
|
|
31
|
+
**Pictures.** One keyed, band-limited noise tile is repeated across the picture and added to
|
|
32
|
+
its luminance. The detector folds the suspect at a candidate tile period and correlates the
|
|
33
|
+
fold with the key tile over every shift at once, so scale is the period and a crop is a
|
|
34
|
+
shift. A few sinusoids in the tile show up as sharp points in the suspect's spectrum; from
|
|
35
|
+
them the detector reads rotation, mirroring and stretch.
|
|
36
|
+
|
|
37
|
+
**Video.** The same tile at the same place in every frame. The mean of several frames keeps
|
|
38
|
+
the mark and blurs the moving picture away.
|
|
39
|
+
|
|
40
|
+
**Sound.** Two layers. A keyed noise sequence, repeated every two seconds, is added under the
|
|
41
|
+
sound and shaped to follow its spectrum; the detector divides the sound by its own smoothed
|
|
42
|
+
spectrum, folds at the period and correlates. A second layer nudges the level difference of
|
|
43
|
+
neighbouring bands onto a keyed grid; it is read from copies whose waveform no longer lines
|
|
44
|
+
up (another tempo, another speed).
|
|
45
|
+
|
|
46
|
+
## Measured
|
|
47
|
+
|
|
48
|
+
Benches are in `bench/` and go through the ffmpeg command line. Scores are in standard
|
|
49
|
+
deviations of the detector's own correlation surface; "found" is the count over the cut.
|
|
50
|
+
|
|
51
|
+
**Sound, sequence layer** (`bench/audio.ts`, 2026-12-01: four 20-second pieces of recorded
|
|
52
|
+
speech, 44.1 kHz; sound over mark 30.8 dB, median). Found in 4 of 4 after each of: 16-bit
|
|
53
|
+
WAV; MP3 128, 64 and 32 kbit/s; AAC 96 and 48; Opus 64, 24 and 12; Vorbis q2; MP3 → AAC →
|
|
54
|
+
MP3; resampling to 48, 22.05, 16 and 8 kHz; telephone band; 20 dB quieter; clipped; noise
|
|
55
|
+
30, 20 and 10 dB under the sound; another recording mixed in at the same level and 10 dB
|
|
56
|
+
louder; excerpts of 10, 5, 3, 2 and 1 second (the 1-second excerpts scored 6.8 at the
|
|
57
|
+
lowest, against a cut of 6.5); bass and treble; echo; dynamic compression; band-limited with
|
|
58
|
+
echo, noise and MP3 64. Unmarked pieces and marked pieces read with another key: 0 of 12,
|
|
59
|
+
highest score 4.65.
|
|
60
|
+
|
|
61
|
+
**Sound, band balance** (same bench, three pieces of 20 seconds, both layers on; sound over
|
|
62
|
+
mark 27.8 dB): 10% faster with pitch kept, 3 of 3; 5% faster (resampled), 3 of 3. Not
|
|
63
|
+
found: 1% faster, 25% faster, one semitone higher with tempo kept (0 of 3 each). Unmarked
|
|
64
|
+
or another key: highest 5.02 against a cut of 8.5.
|
|
65
|
+
|
|
66
|
+
**Video** (`bench/video.ts`, 2026-12-01: ten 8-second clips of 800×500, overlay amplitude 3,
|
|
67
|
+
first encode H.264 CRF 23, twelve frames read). Found in 10 of 10 after each of: H.264 CRF
|
|
68
|
+
28, 33 and 38; 500 kbit/s; 480p, 360p and 240p; HEVC CRF 30; VP9 CRF 36; 12 frames per
|
|
69
|
+
second; 1.25× speed; crop to 70%; a quarter of the frame; mirrored; turned a quarter; turned
|
|
70
|
+
7°; a 0.6× screen recording inside a desktop; brighter with more contrast; 360p at 300
|
|
71
|
+
kbit/s. At amplitude 2 the quarter-frame crop was found in 9 of 10, the rest in 10 of 10.
|
|
72
|
+
Unmarked clips and another key: 0 of 30, highest score 5.64 against a cut of 7.5.
|
|
73
|
+
|
|
74
|
+
**Pictures**: measured in the application this code came from, on 30 flat and 30 textured
|
|
75
|
+
pictures; the bench has not moved here yet.
|
|
76
|
+
|
|
77
|
+
## Limits
|
|
78
|
+
|
|
79
|
+
- Nobody has listened to marked sound or watched marked video under controlled conditions:
|
|
80
|
+
the levels come from masking rules and the numbers above, not from a listening test.
|
|
81
|
+
- Sound whose speed changed by 1%, by 25%, or whose pitch alone changed is not recognised.
|
|
82
|
+
- The sound bench covers speech; music has not been measured.
|
|
83
|
+
- A sound shorter than about a second, or a video frame smaller than about 200 pixels, holds
|
|
84
|
+
too little of a mark to read.
|
|
85
|
+
- Whoever holds the key can mark anything. The mark proves the key was used, not who used it.
|
|
86
|
+
|
|
87
|
+
## Releasing
|
|
88
|
+
|
|
89
|
+
`gh workflow run release.yml -R lofcz/apertaluce -f release_type=patch`. The first publish of
|
|
90
|
+
the package name and its trusted publisher: `npm run bootstrap:publish` (interactive).
|
|
@@ -0,0 +1,38 @@
|
|
|
1
|
+
/** Rate the detector measures at. */
|
|
2
|
+
export declare const BALANCE_RATE = 16000;
|
|
3
|
+
export interface BalanceKey {
|
|
4
|
+
/** Per pair and cell of the pattern: where the grid sits, in dB and as a unit vector at 2π·dither/LATTICE. */
|
|
5
|
+
dither: Float32Array;
|
|
6
|
+
cos: Float32Array;
|
|
7
|
+
sin: Float32Array;
|
|
8
|
+
}
|
|
9
|
+
export declare function deriveBalanceKey(random: () => number): BalanceKey;
|
|
10
|
+
export interface Stage {
|
|
11
|
+
process(input: Float32Array): Float32Array;
|
|
12
|
+
flush(): Float32Array;
|
|
13
|
+
/** The most samples the output can run behind the input. */
|
|
14
|
+
readonly delay: number;
|
|
15
|
+
}
|
|
16
|
+
/**
|
|
17
|
+
* Streaming embedder of this layer for one channel. The sound passes through
|
|
18
|
+
* and only the change is added, so where no band is moved the samples are
|
|
19
|
+
* untouched. A cell is decided once all of it has been heard, which is where
|
|
20
|
+
* the delay comes from.
|
|
21
|
+
*/
|
|
22
|
+
export declare function createBalanceStage(key: BalanceKey, rate: number): Stage;
|
|
23
|
+
export interface BalanceReading {
|
|
24
|
+
/** Agreement with the grid in standard deviations of what unmarked sound gives. */
|
|
25
|
+
score: number;
|
|
26
|
+
/** How much faster than the original the copy plays (1: as recorded). */
|
|
27
|
+
tempo: number;
|
|
28
|
+
/** How far the copy is shifted in pitch, in octaves. */
|
|
29
|
+
pitch: number;
|
|
30
|
+
}
|
|
31
|
+
/** Reads the layer from a sound at {@link BALANCE_RATE} as it is: same tempo, same pitch. */
|
|
32
|
+
export declare function readBalance(sound: Float32Array, key: BalanceKey): BalanceReading;
|
|
33
|
+
/**
|
|
34
|
+
* Reads the layer from a copy that may play at another tempo, at another
|
|
35
|
+
* pitch, or both together (a recording played at another speed). Costs a few
|
|
36
|
+
* seconds of processor time.
|
|
37
|
+
*/
|
|
38
|
+
export declare function searchBalance(sound: Float32Array, key: BalanceKey): BalanceReading;
|
|
@@ -0,0 +1,455 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* The second layer of the sound mark, for copies whose waveform no longer
|
|
3
|
+
* lines up with the original: played faster or slower, shifted in pitch,
|
|
4
|
+
* stretched, or recorded again through a loudspeaker.
|
|
5
|
+
*
|
|
6
|
+
* It lives in how loud neighbouring bands are next to each other. Time is cut
|
|
7
|
+
* into cells and the spectrum into bands; in every cell, bands are taken two by
|
|
8
|
+
* two, and the level difference of each two is nudged onto a keyed grid of
|
|
9
|
+
* allowed values (a fraction of a decibel either way). A detector that knows
|
|
10
|
+
* the grid measures the same differences and sees them all sitting on it;
|
|
11
|
+
* without the key they look like any other sound's.
|
|
12
|
+
*
|
|
13
|
+
* Two bands of one moment are smeared, delayed and filtered together by
|
|
14
|
+
* whatever a copy goes through, so their difference survives where the
|
|
15
|
+
* difference of two moments does not (measured: bench/audio.ts). A tempo
|
|
16
|
+
* change moves the cells and a pitch change moves the bands; the detector
|
|
17
|
+
* tries the cell and band grids of each.
|
|
18
|
+
*/
|
|
19
|
+
import { fft } from "../fft.js";
|
|
20
|
+
/** Rate the detector measures at. */
|
|
21
|
+
export const BALANCE_RATE = 16_000;
|
|
22
|
+
/** A frame of 64 ms every 8 ms; 16 steps make a cell. */
|
|
23
|
+
const FRAME_SECONDS = 0.064;
|
|
24
|
+
const STEP_SECONDS = 0.008;
|
|
25
|
+
const STEPS_PER_CELL = 16;
|
|
26
|
+
const CELL_SECONDS = STEP_SECONDS * STEPS_PER_CELL;
|
|
27
|
+
/** Frames whose centre lies in this part of a cell are the ones measured: they hold nothing of the cells beside it. */
|
|
28
|
+
const MEASURED_FROM = 4;
|
|
29
|
+
const MEASURED_TO = 12;
|
|
30
|
+
const BANDS_PER_OCTAVE = 8;
|
|
31
|
+
const BAND_LO = 500;
|
|
32
|
+
/** 28 bands of an eighth of an octave: 500 Hz to 5.66 kHz. */
|
|
33
|
+
const BANDS = 28;
|
|
34
|
+
const PAIRS = BANDS / 2;
|
|
35
|
+
/** Spacing of the grid of allowed level differences, in dB: a band moves by at most a quarter of it. */
|
|
36
|
+
const LATTICE = 3;
|
|
37
|
+
/** The grid repeats after this many cells (8.2 s). */
|
|
38
|
+
const PATTERN_CELLS = 64;
|
|
39
|
+
/** A band quieter than this next to the loudest band heard so far is left alone and not read. */
|
|
40
|
+
const FLOOR = 1e-5;
|
|
41
|
+
/** Differences larger than this are mostly one band against silence: not read. */
|
|
42
|
+
const NEAR_DB = 18;
|
|
43
|
+
/** The gains overshoot by this factor: the cells beside a cell blur what a frame at its edge sees. */
|
|
44
|
+
const REACH = 1.0;
|
|
45
|
+
export function deriveBalanceKey(random) {
|
|
46
|
+
const count = PAIRS * PATTERN_CELLS;
|
|
47
|
+
const dither = new Float32Array(count);
|
|
48
|
+
const cos = new Float32Array(count);
|
|
49
|
+
const sin = new Float32Array(count);
|
|
50
|
+
for (let i = 0; i < count; i++) {
|
|
51
|
+
dither[i] = random() * LATTICE;
|
|
52
|
+
cos[i] = Math.cos((2 * Math.PI * dither[i]) / LATTICE);
|
|
53
|
+
sin[i] = Math.sin((2 * Math.PI * dither[i]) / LATTICE);
|
|
54
|
+
}
|
|
55
|
+
return { dither, cos, sin };
|
|
56
|
+
}
|
|
57
|
+
const bandMaps = new Map();
|
|
58
|
+
/** `shift` moves the whole band grid by that many octaves (a copy shifted in pitch). */
|
|
59
|
+
function bandMap(binHz, bins, shift) {
|
|
60
|
+
const id = `${binHz}:${bins}:${shift.toFixed(5)}`;
|
|
61
|
+
let cached = bandMaps.get(id);
|
|
62
|
+
if (cached)
|
|
63
|
+
return cached;
|
|
64
|
+
const first = new Int32Array(BANDS);
|
|
65
|
+
const weights = [];
|
|
66
|
+
for (let band = 0; band < BANDS; band++) {
|
|
67
|
+
const lo = (BAND_LO * 2 ** (band / BANDS_PER_OCTAVE + shift)) / binHz;
|
|
68
|
+
const hi = (BAND_LO * 2 ** ((band + 1) / BANDS_PER_OCTAVE + shift)) / binHz;
|
|
69
|
+
const from = Math.max(0, Math.floor(lo + 0.5));
|
|
70
|
+
const to = Math.min(bins - 1, Math.floor(hi + 0.5));
|
|
71
|
+
first[band] = from;
|
|
72
|
+
const row = new Float32Array(Math.max(0, to - from + 1));
|
|
73
|
+
for (let k = from; k <= to; k++)
|
|
74
|
+
row[k - from] = Math.max(0, Math.min(k + 0.5, hi) - Math.max(k - 0.5, lo));
|
|
75
|
+
weights.push(row);
|
|
76
|
+
}
|
|
77
|
+
cached = { first, weights };
|
|
78
|
+
bandMaps.set(id, cached);
|
|
79
|
+
return cached;
|
|
80
|
+
}
|
|
81
|
+
function hann(length) {
|
|
82
|
+
const window = new Float64Array(length);
|
|
83
|
+
for (let i = 0; i < length; i++)
|
|
84
|
+
window[i] = 0.5 - 0.5 * Math.cos((2 * Math.PI * (i + 0.5)) / length);
|
|
85
|
+
return window;
|
|
86
|
+
}
|
|
87
|
+
/**
|
|
88
|
+
* Streaming embedder of this layer for one channel. The sound passes through
|
|
89
|
+
* and only the change is added, so where no band is moved the samples are
|
|
90
|
+
* untouched. A cell is decided once all of it has been heard, which is where
|
|
91
|
+
* the delay comes from.
|
|
92
|
+
*/
|
|
93
|
+
export function createBalanceStage(key, rate) {
|
|
94
|
+
const length = 2 * Math.round((FRAME_SECONDS * rate) / 2);
|
|
95
|
+
let size = 256;
|
|
96
|
+
while (size < length)
|
|
97
|
+
size *= 2;
|
|
98
|
+
const binHz = rate / size;
|
|
99
|
+
const window = hann(length);
|
|
100
|
+
const map = bandMap(binHz, size / 2, 0);
|
|
101
|
+
const kMin = Math.max(1, Math.floor(BAND_LO / binHz) - 1);
|
|
102
|
+
const kMax = Math.min(size / 2 - 1, Math.ceil((BAND_LO * 2 ** (BANDS / BANDS_PER_OCTAVE)) / binHz) + 1);
|
|
103
|
+
const width = kMax - kMin + 1;
|
|
104
|
+
// Sum of the squared windows of overlapping frames.
|
|
105
|
+
const overlapGain = 1 / ((0.375 * length) / (STEP_SECONDS * rate));
|
|
106
|
+
const frameStart = (index) => Math.round(index * STEP_SECONDS * rate) - length / 2;
|
|
107
|
+
// Per bin: its band, the band it fades into near an edge (-1: none, the gain fades to 1), and how far.
|
|
108
|
+
const binBand = new Int32Array(width).fill(-1);
|
|
109
|
+
const binOther = new Int32Array(width).fill(-1);
|
|
110
|
+
const binMix = new Float32Array(width);
|
|
111
|
+
for (let k = kMin; k <= kMax; k++) {
|
|
112
|
+
const position = Math.log2((k * binHz) / BAND_LO) * BANDS_PER_OCTAVE;
|
|
113
|
+
const band = Math.floor(position);
|
|
114
|
+
const inside = position - band;
|
|
115
|
+
const i = k - kMin;
|
|
116
|
+
if (band < 0 || band >= BANDS)
|
|
117
|
+
continue;
|
|
118
|
+
binBand[i] = band;
|
|
119
|
+
if (inside < 0.15) {
|
|
120
|
+
binOther[i] = band - 1;
|
|
121
|
+
binMix[i] = 0.5 - inside / 0.3;
|
|
122
|
+
}
|
|
123
|
+
else if (inside > 0.85) {
|
|
124
|
+
binOther[i] = band + 1 < BANDS ? band + 1 : -1;
|
|
125
|
+
binMix[i] = (inside - 0.85) / 0.3;
|
|
126
|
+
}
|
|
127
|
+
else
|
|
128
|
+
binMix[i] = 0;
|
|
129
|
+
}
|
|
130
|
+
const buffer = new Float64Array(2 * size);
|
|
131
|
+
const scratch = new Float64Array(2 * size);
|
|
132
|
+
const spectra = new Float64Array(STEPS_PER_CELL * 2 * width);
|
|
133
|
+
const energy = new Float64Array(BANDS);
|
|
134
|
+
const gain = new Float64Array(BANDS);
|
|
135
|
+
let held = new Float32Array(Math.max(1 << 15, 8 * size));
|
|
136
|
+
let delta = new Float64Array(held.length);
|
|
137
|
+
/** Index in the input of held[0]; the stream starts half a frame before the first sample. */
|
|
138
|
+
let origin = -length / 2;
|
|
139
|
+
let count = length / 2;
|
|
140
|
+
let frame = 0;
|
|
141
|
+
let loudest = 0;
|
|
142
|
+
let received = 0;
|
|
143
|
+
let emitted = 0;
|
|
144
|
+
function decide(cell) {
|
|
145
|
+
let moved = false;
|
|
146
|
+
for (let band = 0; band < BANDS; band++)
|
|
147
|
+
loudest = Math.max(loudest, energy[band]);
|
|
148
|
+
const slot = cell % PATTERN_CELLS;
|
|
149
|
+
for (let pair = 0; pair < PAIRS; pair++) {
|
|
150
|
+
const a = energy[2 * pair];
|
|
151
|
+
const b = energy[2 * pair + 1];
|
|
152
|
+
gain[2 * pair] = gain[2 * pair + 1] = 1;
|
|
153
|
+
if (Math.min(a, b) <= FLOOR * loudest)
|
|
154
|
+
continue;
|
|
155
|
+
const difference = 10 * Math.log10(a / b);
|
|
156
|
+
const dither = key.dither[pair * PATTERN_CELLS + slot];
|
|
157
|
+
const target = LATTICE * Math.round((difference - dither) / LATTICE) + dither;
|
|
158
|
+
const move = (target - difference) * REACH;
|
|
159
|
+
// Half the move up in one band, half down in the other.
|
|
160
|
+
gain[2 * pair] = 10 ** (move / 40);
|
|
161
|
+
gain[2 * pair + 1] = 10 ** (-move / 40);
|
|
162
|
+
moved = true;
|
|
163
|
+
}
|
|
164
|
+
return moved;
|
|
165
|
+
}
|
|
166
|
+
function apply(cell) {
|
|
167
|
+
for (let step = 0; step < STEPS_PER_CELL; step++) {
|
|
168
|
+
const start = frameStart(cell * STEPS_PER_CELL + step) - origin;
|
|
169
|
+
buffer.fill(0);
|
|
170
|
+
const row = step * 2 * width;
|
|
171
|
+
for (let i = 0; i < width; i++) {
|
|
172
|
+
const band = binBand[i];
|
|
173
|
+
if (band < 0)
|
|
174
|
+
continue;
|
|
175
|
+
const other = binOther[i];
|
|
176
|
+
const mix = binMix[i];
|
|
177
|
+
const factor = gain[band] * (1 - mix) + (other < 0 ? 1 : gain[other]) * mix - 1;
|
|
178
|
+
if (factor === 0)
|
|
179
|
+
continue;
|
|
180
|
+
const k = kMin + i;
|
|
181
|
+
const re = spectra[row + 2 * i] * factor;
|
|
182
|
+
const im = spectra[row + 2 * i + 1] * factor;
|
|
183
|
+
buffer[2 * k] = re;
|
|
184
|
+
buffer[2 * k + 1] = im;
|
|
185
|
+
buffer[2 * (size - k)] = re;
|
|
186
|
+
buffer[2 * (size - k) + 1] = -im;
|
|
187
|
+
}
|
|
188
|
+
fft(buffer, size, true, scratch);
|
|
189
|
+
for (let n = 0; n < length; n++)
|
|
190
|
+
delta[start + n] += buffer[2 * n] * window[n] * overlapGain;
|
|
191
|
+
}
|
|
192
|
+
}
|
|
193
|
+
function run(out) {
|
|
194
|
+
for (;;) {
|
|
195
|
+
const start = frameStart(frame) - origin;
|
|
196
|
+
if (start + length > count)
|
|
197
|
+
return;
|
|
198
|
+
const step = frame % STEPS_PER_CELL;
|
|
199
|
+
if (step === 0)
|
|
200
|
+
energy.fill(0);
|
|
201
|
+
buffer.fill(0);
|
|
202
|
+
for (let n = 0; n < length; n++)
|
|
203
|
+
buffer[2 * n] = held[start + n] * window[n];
|
|
204
|
+
fft(buffer, size, false, scratch);
|
|
205
|
+
spectra.set(buffer.subarray(2 * kMin, 2 * (kMax + 1)), step * 2 * width);
|
|
206
|
+
if (step >= MEASURED_FROM && step < MEASURED_TO) {
|
|
207
|
+
for (let band = 0; band < BANDS; band++) {
|
|
208
|
+
const weights = map.weights[band];
|
|
209
|
+
const first = map.first[band];
|
|
210
|
+
let sum = 0;
|
|
211
|
+
for (let j = 0; j < weights.length; j++)
|
|
212
|
+
sum += weights[j] * (buffer[2 * (first + j)] ** 2 + buffer[2 * (first + j) + 1] ** 2);
|
|
213
|
+
energy[band] += sum;
|
|
214
|
+
}
|
|
215
|
+
}
|
|
216
|
+
frame++;
|
|
217
|
+
if (step !== STEPS_PER_CELL - 1)
|
|
218
|
+
continue;
|
|
219
|
+
const cell = (frame - 1 - step) / STEPS_PER_CELL;
|
|
220
|
+
if (decide(cell))
|
|
221
|
+
apply(cell);
|
|
222
|
+
// Everything before the next cell's first frame is final.
|
|
223
|
+
const final = Math.min(frameStart(frame) - origin, count);
|
|
224
|
+
emit(final, out);
|
|
225
|
+
// Drop what was emitted; the next cell's frames start at `final`.
|
|
226
|
+
held.copyWithin(0, final, count);
|
|
227
|
+
delta.copyWithin(0, final, count);
|
|
228
|
+
delta.fill(0, count - final, count);
|
|
229
|
+
origin += final;
|
|
230
|
+
count -= final;
|
|
231
|
+
}
|
|
232
|
+
}
|
|
233
|
+
function emit(until, out) {
|
|
234
|
+
for (let i = 0; i < until; i++) {
|
|
235
|
+
const index = origin + i;
|
|
236
|
+
if (index < emitted || index >= received)
|
|
237
|
+
continue;
|
|
238
|
+
out.push(held[i] + delta[i]);
|
|
239
|
+
emitted++;
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
function feed(input) {
|
|
243
|
+
if (count + input.length > held.length) {
|
|
244
|
+
const grown = new Float32Array(Math.max(2 * held.length, count + input.length + size));
|
|
245
|
+
grown.set(held.subarray(0, count));
|
|
246
|
+
const grownDelta = new Float64Array(grown.length);
|
|
247
|
+
grownDelta.set(delta.subarray(0, count));
|
|
248
|
+
held = grown;
|
|
249
|
+
delta = grownDelta;
|
|
250
|
+
}
|
|
251
|
+
held.set(input, count);
|
|
252
|
+
count += input.length;
|
|
253
|
+
const out = [];
|
|
254
|
+
run(out);
|
|
255
|
+
return Float32Array.from(out);
|
|
256
|
+
}
|
|
257
|
+
const delay = Math.ceil(CELL_SECONDS * rate) + length;
|
|
258
|
+
return {
|
|
259
|
+
delay,
|
|
260
|
+
process(input) {
|
|
261
|
+
received += input.length;
|
|
262
|
+
return feed(input);
|
|
263
|
+
},
|
|
264
|
+
flush() {
|
|
265
|
+
const parts = [];
|
|
266
|
+
let total = 0;
|
|
267
|
+
// Silence pushes the last cell through.
|
|
268
|
+
for (let guard = 0; emitted < received && guard < 4; guard++) {
|
|
269
|
+
const part = feed(new Float32Array(delay));
|
|
270
|
+
parts.push(part);
|
|
271
|
+
total += part.length;
|
|
272
|
+
}
|
|
273
|
+
const out = new Float32Array(total);
|
|
274
|
+
let offset = 0;
|
|
275
|
+
for (const part of parts) {
|
|
276
|
+
out.set(part, offset);
|
|
277
|
+
offset += part.length;
|
|
278
|
+
}
|
|
279
|
+
return out;
|
|
280
|
+
},
|
|
281
|
+
};
|
|
282
|
+
}
|
|
283
|
+
function spectrogram(sound) {
|
|
284
|
+
const size = FRAME_SECONDS * BALANCE_RATE;
|
|
285
|
+
const hop = STEP_SECONDS * BALANCE_RATE;
|
|
286
|
+
const bins = size / 2;
|
|
287
|
+
const window = hann(size);
|
|
288
|
+
const frames = Math.floor(sound.length / hop) + 1;
|
|
289
|
+
const power = new Float32Array(frames * bins);
|
|
290
|
+
const buffer = new Float64Array(2 * size);
|
|
291
|
+
const scratch = new Float64Array(2 * size);
|
|
292
|
+
for (let frame = 0; frame < frames; frame++) {
|
|
293
|
+
const start = frame * hop - size / 2;
|
|
294
|
+
let loud = false;
|
|
295
|
+
for (let n = 0; n < size; n++) {
|
|
296
|
+
const index = start + n;
|
|
297
|
+
const value = index >= 0 && index < sound.length ? sound[index] * window[n] : 0;
|
|
298
|
+
buffer[2 * n] = value;
|
|
299
|
+
buffer[2 * n + 1] = 0;
|
|
300
|
+
if (value !== 0)
|
|
301
|
+
loud = true;
|
|
302
|
+
}
|
|
303
|
+
if (!loud)
|
|
304
|
+
continue;
|
|
305
|
+
fft(buffer, size, false, scratch);
|
|
306
|
+
const row = frame * bins;
|
|
307
|
+
for (let k = 0; k < bins; k++)
|
|
308
|
+
power[row + k] = buffer[2 * k] ** 2 + buffer[2 * k + 1] ** 2;
|
|
309
|
+
}
|
|
310
|
+
return { frames, bins, power };
|
|
311
|
+
}
|
|
312
|
+
/** Band energies per frame for a band grid moved by `shift` octaves. */
|
|
313
|
+
function bandEnergies(spectrum, shift) {
|
|
314
|
+
const map = bandMap(BALANCE_RATE / (2 * spectrum.bins), spectrum.bins, shift);
|
|
315
|
+
const out = new Float32Array(spectrum.frames * BANDS);
|
|
316
|
+
for (let frame = 0; frame < spectrum.frames; frame++) {
|
|
317
|
+
const row = frame * spectrum.bins;
|
|
318
|
+
for (let band = 0; band < BANDS; band++) {
|
|
319
|
+
const weights = map.weights[band];
|
|
320
|
+
const first = map.first[band];
|
|
321
|
+
let sum = 0;
|
|
322
|
+
for (let j = 0; j < weights.length; j++)
|
|
323
|
+
sum += weights[j] * spectrum.power[row + first + j];
|
|
324
|
+
out[frame * BANDS + band] = sum;
|
|
325
|
+
}
|
|
326
|
+
}
|
|
327
|
+
return out;
|
|
328
|
+
}
|
|
329
|
+
/**
|
|
330
|
+
* Agreement of one reading of the sound with the grid: the frames are put into
|
|
331
|
+
* cells as if the copy played `tempo` times faster and started `offset`
|
|
332
|
+
* seconds into a cell, and the best start within the pattern is taken.
|
|
333
|
+
*/
|
|
334
|
+
function agreement(energies, frames, key, tempo, offset, work) {
|
|
335
|
+
const cellCount = Math.floor((frames * STEP_SECONDS * tempo + offset) / CELL_SECONDS) + 1;
|
|
336
|
+
if (work.cells.length < cellCount * BANDS)
|
|
337
|
+
work.cells = new Float64Array(2 * cellCount * BANDS);
|
|
338
|
+
const cells = work.cells;
|
|
339
|
+
cells.fill(0, 0, cellCount * BANDS);
|
|
340
|
+
const perStep = (STEP_SECONDS * tempo) / CELL_SECONDS;
|
|
341
|
+
const lead = offset / CELL_SECONDS;
|
|
342
|
+
for (let frame = 0; frame < frames; frame++) {
|
|
343
|
+
const position = frame * perStep + lead;
|
|
344
|
+
const cell = Math.floor(position);
|
|
345
|
+
const inside = position - cell;
|
|
346
|
+
if (inside < MEASURED_FROM / STEPS_PER_CELL || inside >= MEASURED_TO / STEPS_PER_CELL)
|
|
347
|
+
continue;
|
|
348
|
+
const from = frame * BANDS;
|
|
349
|
+
const to = cell * BANDS;
|
|
350
|
+
for (let band = 0; band < BANDS; band++)
|
|
351
|
+
cells[to + band] += energies[from + band];
|
|
352
|
+
}
|
|
353
|
+
let loudest = 0;
|
|
354
|
+
for (let i = 0; i < cellCount * BANDS; i++)
|
|
355
|
+
if (cells[i] > loudest)
|
|
356
|
+
loudest = cells[i];
|
|
357
|
+
if (loudest === 0)
|
|
358
|
+
return 0;
|
|
359
|
+
const { foldCos, foldSin } = work;
|
|
360
|
+
foldCos.fill(0);
|
|
361
|
+
foldSin.fill(0);
|
|
362
|
+
let pairs = 0;
|
|
363
|
+
const floor = FLOOR * loudest;
|
|
364
|
+
for (let cell = 0; cell < cellCount; cell++) {
|
|
365
|
+
const slot = cell % PATTERN_CELLS;
|
|
366
|
+
for (let pair = 0; pair < PAIRS; pair++) {
|
|
367
|
+
const a = cells[cell * BANDS + 2 * pair];
|
|
368
|
+
const b = cells[cell * BANDS + 2 * pair + 1];
|
|
369
|
+
if (a <= floor || b <= floor)
|
|
370
|
+
continue;
|
|
371
|
+
const difference = 10 * Math.log10(a / b);
|
|
372
|
+
if (difference > NEAR_DB || difference < -NEAR_DB)
|
|
373
|
+
continue;
|
|
374
|
+
const angle = (2 * Math.PI * difference) / LATTICE;
|
|
375
|
+
foldCos[pair * PATTERN_CELLS + slot] += Math.cos(angle);
|
|
376
|
+
foldSin[pair * PATTERN_CELLS + slot] += Math.sin(angle);
|
|
377
|
+
pairs++;
|
|
378
|
+
}
|
|
379
|
+
}
|
|
380
|
+
if (pairs < 40)
|
|
381
|
+
return 0;
|
|
382
|
+
let best = -Infinity;
|
|
383
|
+
for (let shift = 0; shift < PATTERN_CELLS; shift++) {
|
|
384
|
+
let sum = 0;
|
|
385
|
+
for (let pair = 0; pair < PAIRS; pair++) {
|
|
386
|
+
const row = pair * PATTERN_CELLS;
|
|
387
|
+
for (let slot = 0; slot < PATTERN_CELLS; slot++) {
|
|
388
|
+
const at = row + ((slot + shift) % PATTERN_CELLS);
|
|
389
|
+
sum += foldCos[row + slot] * key.cos[at] + foldSin[row + slot] * key.sin[at];
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
if (sum > best)
|
|
393
|
+
best = sum;
|
|
394
|
+
}
|
|
395
|
+
return best / Math.sqrt(pairs / 2);
|
|
396
|
+
}
|
|
397
|
+
/** Offsets tried within a cell, in seconds: the measured half of a cell forgives a quarter of a cell. */
|
|
398
|
+
const OFFSETS = [0, 0.032, 0.064, 0.096];
|
|
399
|
+
/** The search reads at most this much sound: more would need finer tempo steps for no better answer. */
|
|
400
|
+
const SEARCH_SECONDS = 24;
|
|
401
|
+
/** Tempo steps of the search, as a ratio: the drift over SEARCH_SECONDS stays under an eighth of a cell. */
|
|
402
|
+
const TEMPO_STEP = 1 + (CELL_SECONDS / 8 / SEARCH_SECONDS) * 2;
|
|
403
|
+
const TEMPO_MIN = 0.5;
|
|
404
|
+
const TEMPO_MAX = 2;
|
|
405
|
+
/** Pitch steps of the search, in octaves: a quarter of a band. */
|
|
406
|
+
const PITCH_STEP = 1 / (4 * BANDS_PER_OCTAVE);
|
|
407
|
+
const PITCH_MAX = 1;
|
|
408
|
+
/** Reads the layer from a sound at {@link BALANCE_RATE} as it is: same tempo, same pitch. */
|
|
409
|
+
export function readBalance(sound, key) {
|
|
410
|
+
const spectrum = spectrogram(sound);
|
|
411
|
+
const energies = bandEnergies(spectrum, 0);
|
|
412
|
+
const work = { cells: new Float64Array(0), foldCos: new Float64Array(PAIRS * PATTERN_CELLS), foldSin: new Float64Array(PAIRS * PATTERN_CELLS) };
|
|
413
|
+
let score = 0;
|
|
414
|
+
for (const offset of OFFSETS)
|
|
415
|
+
score = Math.max(score, agreement(energies, spectrum.frames, key, 1, offset, work));
|
|
416
|
+
return { score, tempo: 1, pitch: 0 };
|
|
417
|
+
}
|
|
418
|
+
/**
|
|
419
|
+
* Reads the layer from a copy that may play at another tempo, at another
|
|
420
|
+
* pitch, or both together (a recording played at another speed). Costs a few
|
|
421
|
+
* seconds of processor time.
|
|
422
|
+
*/
|
|
423
|
+
export function searchBalance(sound, key) {
|
|
424
|
+
const piece = sound.length > SEARCH_SECONDS * BALANCE_RATE ? sound.subarray(0, SEARCH_SECONDS * BALANCE_RATE) : sound;
|
|
425
|
+
const spectrum = spectrogram(piece);
|
|
426
|
+
const work = { cells: new Float64Array(0), foldCos: new Float64Array(PAIRS * PATTERN_CELLS), foldSin: new Float64Array(PAIRS * PATTERN_CELLS) };
|
|
427
|
+
const shifted = new Map();
|
|
428
|
+
const energiesAt = (pitch) => {
|
|
429
|
+
const step = Math.round(pitch / PITCH_STEP);
|
|
430
|
+
let energies = shifted.get(step);
|
|
431
|
+
if (!energies) {
|
|
432
|
+
energies = bandEnergies(spectrum, step * PITCH_STEP);
|
|
433
|
+
shifted.set(step, energies);
|
|
434
|
+
}
|
|
435
|
+
return energies;
|
|
436
|
+
};
|
|
437
|
+
let best = { score: 0, tempo: 1, pitch: 0 };
|
|
438
|
+
const consider = (tempo, pitch) => {
|
|
439
|
+
const energies = energiesAt(pitch);
|
|
440
|
+
for (const offset of OFFSETS) {
|
|
441
|
+
const score = agreement(energies, spectrum.frames, key, tempo, offset, work);
|
|
442
|
+
if (score > best.score)
|
|
443
|
+
best = { score, tempo, pitch: Math.round(pitch / PITCH_STEP) * PITCH_STEP };
|
|
444
|
+
}
|
|
445
|
+
};
|
|
446
|
+
// Pitch alone.
|
|
447
|
+
for (let pitch = -PITCH_MAX; pitch <= PITCH_MAX + 1e-9; pitch += PITCH_STEP)
|
|
448
|
+
consider(1, pitch);
|
|
449
|
+
for (let tempo = TEMPO_MIN; tempo <= TEMPO_MAX; tempo *= TEMPO_STEP) {
|
|
450
|
+
// Tempo alone, then tempo and pitch moving together.
|
|
451
|
+
consider(tempo, 0);
|
|
452
|
+
consider(tempo, Math.log2(tempo));
|
|
453
|
+
}
|
|
454
|
+
return best;
|
|
455
|
+
}
|
|
@@ -0,0 +1,2 @@
|
|
|
1
|
+
export { AUDIO_CUT, AUDIO_MARK_LEVEL, AUDIO_MARK_SCHEME, AUDIO_STRETCH_CUT, BALANCE_CUT, BALANCE_SEARCH_CUT, createAudioMarker, deriveAudioKey, detectAudioMark, embedAudioMark, type AudioDetectOptions, type AudioKey, type AudioMarker, type AudioMarkOptions, type AudioMarkResult, } from "./mark.ts";
|
|
2
|
+
export { resample } from "./resample.ts";
|