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.
- package/LICENSE +21 -0
- package/README.md +139 -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 +163 -0
- package/lib/image/mark.js +1240 -0
- package/lib/index.d.ts +3 -0
- package/lib/index.js +3 -0
- package/lib/video/index.d.ts +50 -0
- package/lib/video/index.js +79 -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,140 @@
|
|
|
1
|
-
#
|
|
1
|
+
# /apertaluce/
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
<p align="center">
|
|
4
|
+
<a href="https://www.npmjs.com/package/apertaluce"><img src="https://img.shields.io/npm/v/apertaluce?style=flat-square&label=npm&color=111111" alt="npm" /></a>
|
|
5
|
+
<a href="LICENSE"><img src="https://img.shields.io/badge/license-MIT-111111?style=flat-square" alt="MIT" /></a>
|
|
6
|
+
<a href="https://nodejs.org"><img src="https://img.shields.io/badge/node-20+-111111?style=flat-square" alt="node 20+" /></a>
|
|
7
|
+
<a href="package.json"><img src="https://img.shields.io/badge/dependencies-0-111111?style=flat-square" alt="0 dependencies" /></a>
|
|
8
|
+
</p>
|
|
9
|
+
|
|
10
|
+
---
|
|
11
|
+
|
|
12
|
+
```
|
|
13
|
+
.------------------------------------------------------------------------.
|
|
14
|
+
| .--. __ __ .--. |
|
|
15
|
+
| | | ____ _____ ___ _____/ /_____ _/ /_ __________ | | |
|
|
16
|
+
| '--' / __ `/ __ \/ _ \/ ___/ __/ __ `/ / / / / ___/ _ \ '--' |
|
|
17
|
+
| / /_/ / /_/ / __/ / / /_/ /_/ / / /_/ / /__/ __/ |
|
|
18
|
+
| [+] \__,_/ .___/\___/_/ \__/\__,_/_/\__,_/\___/\___/ [+] |
|
|
19
|
+
| /_/ |
|
|
20
|
+
| .--. .--. |
|
|
21
|
+
| | | I n v i s i b l e M a r k s | | |
|
|
22
|
+
| '--' '--' |
|
|
23
|
+
'------------------------------------------------------------------------'
|
|
24
|
+
```
|
|
25
|
+
|
|
26
|
+
<p align="center">
|
|
27
|
+
<a href="docs/MEASURED.md">measured</a>
|
|
28
|
+
·
|
|
29
|
+
<a href="https://www.npmjs.com/package/apertaluce">npm</a>
|
|
30
|
+
</p>
|
|
31
|
+
|
|
32
|
+
Invisible marks for pictures, sound and video. Keyed, survive re-encoding and editing. No dependencies, no codecs, runs anywhere JavaScript does.
|
|
33
|
+
|
|
34
|
+
## Install
|
|
35
|
+
|
|
36
|
+
```bash
|
|
37
|
+
npm install apertaluce
|
|
38
|
+
```
|
|
39
|
+
|
|
40
|
+
Node 20+, Bun, Deno, browsers, edge runtimes. ESM with types.
|
|
41
|
+
|
|
42
|
+
```ts
|
|
43
|
+
import { derivePixelKey, embedPixelMark, detectPixelMark } from 'apertaluce/image';
|
|
44
|
+
import { deriveAudioKey, embedAudioMark, detectAudioMark } from 'apertaluce/audio';
|
|
45
|
+
import { frameMarkOverlayPgm, detectFrameMark } from 'apertaluce/video';
|
|
46
|
+
|
|
47
|
+
const pixels = await derivePixelKey(secret);
|
|
48
|
+
embedPixelMark(rgba, pixels); // in place
|
|
49
|
+
detectPixelMark(suspect, pixels).detected;
|
|
50
|
+
|
|
51
|
+
const sound = await deriveAudioKey(secret);
|
|
52
|
+
embedAudioMark([left, right], 44_100, sound); // in place
|
|
53
|
+
detectAudioMark(samples, 48_000, sound).detected;
|
|
54
|
+
|
|
55
|
+
const overlay = frameMarkOverlayPgm(1280, 720, pixels); // blend onto every frame's luma
|
|
56
|
+
detectFrameMark(frames, pixels).detected; // a dozen frames of the suspect
|
|
57
|
+
```
|
|
58
|
+
|
|
59
|
+
A mark says one thing: this was marked with this key. No payload. Reading or forging it needs the key. Decoding and encoding stay with the host: the library takes pixels and samples.
|
|
60
|
+
|
|
61
|
+
## Marks
|
|
62
|
+
|
|
63
|
+
| Mark | |
|
|
64
|
+
| ------- | -------------------------------------------------------------------------------------------- |
|
|
65
|
+
| Picture | Keyed tile, faint on flat colour and strong in texture; crop, rotation, mirroring, JPEG |
|
|
66
|
+
| Video | The same tile on every frame; H.264/HEVC/VP9 re-encodes, reduction, crop, screen recording |
|
|
67
|
+
| Sound | Keyed sequence under the sound; MP3/AAC/Opus, resampling, trimming, noise, mixing, echo |
|
|
68
|
+
| Sound | Keyed balance of neighbouring bands; another tempo, another speed (partly, see Limits) |
|
|
69
|
+
|
|
70
|
+
## API
|
|
71
|
+
|
|
72
|
+
`apertaluce/image`:
|
|
73
|
+
|
|
74
|
+
| Function | |
|
|
75
|
+
| ----------------------------------------------- | ------------------------------------------------------ |
|
|
76
|
+
| `derivePixelKey(secret, id?)` | Key from a secret of 128 bits or more |
|
|
77
|
+
| `embedPixelMark(image, key, options?)` | Marks RGBA pixels in place; returns the PSNR |
|
|
78
|
+
| `detectPixelMark(image, key, options?)` | `detected`, `score`, rotation, mirroring |
|
|
79
|
+
| `pixelMarkPlane(width, height, key, tiles?)` | The mark alone, for pipelines that add it themselves |
|
|
80
|
+
| `pictureFingerprint(image)` | 256-bit perceptual fingerprint, 64 hex digits |
|
|
81
|
+
| `fingerprintDistance(a, b)` | Bits two fingerprints differ in |
|
|
82
|
+
|
|
83
|
+
`apertaluce/audio`:
|
|
84
|
+
|
|
85
|
+
| Function | |
|
|
86
|
+
| ----------------------------------------------- | ------------------------------------------------------ |
|
|
87
|
+
| `deriveAudioKey(secret, id?)` | Key from a secret of 128 bits or more |
|
|
88
|
+
| `embedAudioMark(channels, rate, key, options?)` | Marks Float32 samples in place; returns sound over mark |
|
|
89
|
+
| `createAudioMarker(key, rate, options?)` | Streaming: `process(chunk)`, `flush()`, `delay` |
|
|
90
|
+
| `detectAudioMark(channels, rate, key, options?)`| `detected`, `score`, `layer`, tempo and pitch |
|
|
91
|
+
| `resample(samples, from, to)` | Windowed-sinc rate conversion |
|
|
92
|
+
|
|
93
|
+
`apertaluce/video`:
|
|
94
|
+
|
|
95
|
+
| Function | |
|
|
96
|
+
| ----------------------------------------------- | ------------------------------------------------------ |
|
|
97
|
+
| `frameMarkOverlay(width, height, key, options?)`| Grey plane, 128 = leave the pixel |
|
|
98
|
+
| `frameMarkOverlayPgm(...)` | The same as a PGM file for ffmpeg |
|
|
99
|
+
| `detectFrameMark(frames, key, options?)` | Reads the mean of the frames, then single frames |
|
|
100
|
+
|
|
101
|
+
```bash
|
|
102
|
+
# One overlay for the whole video; only the luma plane meets it.
|
|
103
|
+
ffmpeg -i in.mp4 -loop 1 -i overlay.pgm -filter_complex \
|
|
104
|
+
"[0:v]format=yuv420p,extractplanes=y+u+v[y][u][v];[1:v]format=gray[o];[y][o]blend=all_mode=grainmerge:shortest=1[m];[m][u][v]mergeplanes=0x001020:yuv420p" out.mp4
|
|
105
|
+
```
|
|
106
|
+
|
|
107
|
+
Options: `strength` (picture, sound), `balance: false` (sound: skip the second layer and its 0.2 s delay), `search: false` (sound: skip the tempo and pitch search), `amplitude` and `tilesPerShortSide` (video).
|
|
108
|
+
|
|
109
|
+
## Measured
|
|
110
|
+
|
|
111
|
+
Full tables in [docs/MEASURED.md](docs/MEASURED.md). Found / tried, 2026-12-01:
|
|
112
|
+
|
|
113
|
+
| Mark | Hosts | Held | Unmarked |
|
|
114
|
+
| ---------------- | ----------------- | -------------------------------------------------------------- | -------- |
|
|
115
|
+
| Picture | 60 pictures | Rotation, mirror, scale, JPEG 50, quarter crop (51/60) | 0/3,204 |
|
|
116
|
+
| Video | 10 clips | CRF 38, 240p, HEVC, VP9, quarter crop, screen recording | 0/30 |
|
|
117
|
+
| Sound, sequence | 4 speech pieces | MP3 32, Opus 12, telephone band, 1 s excerpt, noise at 10 dB | 0/12 |
|
|
118
|
+
| Sound, balance | 3 speech pieces | 10% faster with pitch kept, 5% faster | 0/9 |
|
|
119
|
+
|
|
120
|
+
## Limits
|
|
121
|
+
|
|
122
|
+
- Nobody has listened to marked sound or watched marked video under controlled conditions. The levels come from masking rules and the numbers above.
|
|
123
|
+
- Sound 1% faster, 25% faster, or shifted in pitch alone is not recognised.
|
|
124
|
+
- The sound bench covers speech. Music has not been measured.
|
|
125
|
+
- Under about a second of sound, or about 200 pixels of picture, there is too little mark to read.
|
|
126
|
+
- Whoever holds the key can mark anything. The mark proves the key was used, not who used it.
|
|
127
|
+
|
|
128
|
+
## Develop
|
|
129
|
+
|
|
130
|
+
```bash
|
|
131
|
+
npm run tsc && npm test
|
|
132
|
+
node bench/audio.ts --dir <folder of audio or video> # needs ffmpeg
|
|
133
|
+
node bench/video.ts --dir <folder of videos>
|
|
134
|
+
```
|
|
135
|
+
|
|
136
|
+
Release: `gh workflow run release.yml -R lofcz/apertaluce -f release_type=minor`. First publish of a new package name: `npm run bootstrap:publish` (npm login, publish, trusted publisher).
|
|
137
|
+
|
|
138
|
+
## License
|
|
139
|
+
|
|
140
|
+
MIT
|
|
@@ -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";
|