apertaluce 0.1.0 → 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/README.md +118 -68
- package/lib/image/fingerprint.d.ts +1 -1
- package/lib/image/fingerprint.js +1 -1
- package/lib/image/mark.d.ts +18 -9
- package/lib/image/mark.js +347 -102
- package/lib/video/index.d.ts +5 -2
- package/lib/video/index.js +5 -2
- package/package.json +1 -1
package/README.md
CHANGED
|
@@ -1,90 +1,140 @@
|
|
|
1
|
-
# apertaluce
|
|
1
|
+
# /apertaluce/
|
|
2
2
|
|
|
3
|
-
|
|
4
|
-
|
|
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>
|
|
5
9
|
|
|
6
|
-
|
|
7
|
-
|
|
8
|
-
|
|
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.
|
|
9
41
|
|
|
10
42
|
```ts
|
|
11
|
-
import { derivePixelKey, embedPixelMark, detectPixelMark } from
|
|
12
|
-
import { deriveAudioKey,
|
|
13
|
-
import { frameMarkOverlayPgm, detectFrameMark } from
|
|
43
|
+
import { derivePixelKey, embedPixelMark, detectPixelMark } from 'apertaluce/image';
|
|
44
|
+
import { deriveAudioKey, embedAudioMark, detectAudioMark } from 'apertaluce/audio';
|
|
45
|
+
import { frameMarkOverlayPgm, detectFrameMark } from 'apertaluce/video';
|
|
14
46
|
|
|
15
47
|
const pixels = await derivePixelKey(secret);
|
|
16
|
-
embedPixelMark(rgba, pixels);
|
|
17
|
-
detectPixelMark(
|
|
48
|
+
embedPixelMark(rgba, pixels); // in place
|
|
49
|
+
detectPixelMark(suspect, pixels).detected;
|
|
18
50
|
|
|
19
|
-
const
|
|
20
|
-
embedAudioMark([left, right], 44_100,
|
|
21
|
-
detectAudioMark(
|
|
51
|
+
const sound = await deriveAudioKey(secret);
|
|
52
|
+
embedAudioMark([left, right], 44_100, sound); // in place
|
|
53
|
+
detectAudioMark(samples, 48_000, sound).detected;
|
|
22
54
|
|
|
23
|
-
|
|
24
|
-
|
|
25
|
-
const overlay = frameMarkOverlayPgm(1280, 720, pixels);
|
|
26
|
-
detectFrameMark(frames, pixels).detected;
|
|
55
|
+
const overlay = frameMarkOverlayPgm(1280, 720, pixels); // blend onto every frame's luma
|
|
56
|
+
detectFrameMark(frames, pixels).detected; // a dozen frames of the suspect
|
|
27
57
|
```
|
|
28
58
|
|
|
29
|
-
|
|
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
|
|
30
71
|
|
|
31
|
-
|
|
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.
|
|
72
|
+
`apertaluce/image`:
|
|
36
73
|
|
|
37
|
-
|
|
38
|
-
|
|
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 |
|
|
39
82
|
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
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).
|
|
45
108
|
|
|
46
109
|
## Measured
|
|
47
110
|
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
|
|
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.
|
|
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 |
|
|
76
119
|
|
|
77
120
|
## Limits
|
|
78
121
|
|
|
79
|
-
- Nobody has listened to marked sound or watched marked video under controlled conditions
|
|
80
|
-
|
|
81
|
-
-
|
|
82
|
-
-
|
|
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.
|
|
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.
|
|
85
126
|
- Whoever holds the key can mark anything. The mark proves the key was used, not who used it.
|
|
86
127
|
|
|
87
|
-
##
|
|
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
|
|
88
139
|
|
|
89
|
-
|
|
90
|
-
the package name and its trusted publisher: `npm run bootstrap:publish` (interactive).
|
|
140
|
+
MIT
|
|
@@ -16,6 +16,6 @@ export declare function pictureFingerprint(image: RgbaImage): string | null;
|
|
|
16
16
|
export declare function fingerprintDistance(a: string, b: string): number;
|
|
17
17
|
/**
|
|
18
18
|
* Two pictures within this many bits are the same picture. Measured in
|
|
19
|
-
*
|
|
19
|
+
* the application this came from, on 477 pictures: 2 of 113,526 pairs of different pictures within it.
|
|
20
20
|
*/
|
|
21
21
|
export declare const FINGERPRINT_MATCH_BITS = 40;
|
package/lib/image/fingerprint.js
CHANGED
|
@@ -88,6 +88,6 @@ export function fingerprintDistance(a, b) {
|
|
|
88
88
|
}
|
|
89
89
|
/**
|
|
90
90
|
* Two pictures within this many bits are the same picture. Measured in
|
|
91
|
-
*
|
|
91
|
+
* the application this came from, on 477 pictures: 2 of 113,526 pairs of different pictures within it.
|
|
92
92
|
*/
|
|
93
93
|
export const FINGERPRINT_MATCH_BITS = 40;
|
package/lib/image/mark.d.ts
CHANGED
|
@@ -4,12 +4,15 @@ export interface RgbaImage {
|
|
|
4
4
|
height: number;
|
|
5
5
|
}
|
|
6
6
|
/** Bump when the tile layout changes; old keys keep detecting old pictures. */
|
|
7
|
-
export declare const PIXEL_MARK_SCHEME =
|
|
7
|
+
export declare const PIXEL_MARK_SCHEME = 2;
|
|
8
8
|
/** Tiles across the picture's shorter side at embed time. */
|
|
9
9
|
export declare const TILES_PER_SHORT_SIDE = 4;
|
|
10
10
|
export interface PixelKey {
|
|
11
|
-
/**
|
|
11
|
+
/** The detector's reference: the coarse and the fine tile added up, TILE×TILE. */
|
|
12
12
|
tile: Float32Array;
|
|
13
|
+
/** The coarse and the fine part, each of unit variance (the embedder scales them separately). */
|
|
14
|
+
coarse: Float32Array;
|
|
15
|
+
fine: Float32Array;
|
|
13
16
|
/** Tile frequencies (cycles per tile) of the synchronisation peaks. */
|
|
14
17
|
sync: Array<[number, number]>;
|
|
15
18
|
/** conj(FFT(tile)) restricted to the band, per fold size. */
|
|
@@ -55,14 +58,14 @@ export interface PixelMarkResult {
|
|
|
55
58
|
* test looks at 9 shifts of a handful of hypotheses; the search looks at every
|
|
56
59
|
* shift of the grids the synchronisation peaks propose, so its cut is higher.
|
|
57
60
|
*
|
|
58
|
-
* Measured
|
|
59
|
-
*
|
|
60
|
-
*
|
|
61
|
-
*
|
|
62
|
-
*
|
|
61
|
+
* Measured (docs/MEASURED.md) on 1,083 scores of unmarked pictures (as they are
|
|
62
|
+
* and inside a page): no detection, highest score 6.78, 99 % under 6.0. An
|
|
63
|
+
* exponential fit to the top tenth of those scores puts the chance of an
|
|
64
|
+
* unmarked picture passing 8 at about 1 in ten million per key (an
|
|
65
|
+
* extrapolation, not a count; the two highest scores sit above the fit).
|
|
63
66
|
*/
|
|
64
67
|
export declare const ALIGNED_CUT = 6.5;
|
|
65
|
-
export declare const SEARCH_CUT =
|
|
68
|
+
export declare const SEARCH_CUT = 8;
|
|
66
69
|
interface Whitened {
|
|
67
70
|
values: Float32Array;
|
|
68
71
|
width: number;
|
|
@@ -82,6 +85,8 @@ interface FoldScratch {
|
|
|
82
85
|
im: Float64Array;
|
|
83
86
|
re2: Float64Array;
|
|
84
87
|
im2: Float64Array;
|
|
88
|
+
sums: Float64Array;
|
|
89
|
+
energies: Float64Array;
|
|
85
90
|
colBin: Int32Array;
|
|
86
91
|
}
|
|
87
92
|
declare function foldScratch(width: number): FoldScratch;
|
|
@@ -138,7 +143,11 @@ declare function searchAnyGrids(spectrum: Spectrum, key: PixelKey, minPeriod: nu
|
|
|
138
143
|
declare function fitGrid(spectrum: Spectrum, sync: Array<[number, number]>, start: GridCandidate): GridCandidate | null;
|
|
139
144
|
/** Folds along a candidate grid and correlates with the key, the tile upright and turned by a half-turn. */
|
|
140
145
|
declare function verifyGrid(w: Whitened, key: PixelKey, scratch: FoldScratch, grid: GridCandidate): PeakSearchResult;
|
|
141
|
-
declare function searchByPeaks(w: Whitened
|
|
146
|
+
declare function searchByPeaks(w: Whitened & {
|
|
147
|
+
factor: number;
|
|
148
|
+
}, key: PixelKey, scratch: FoldScratch, sharp?: Whitened & {
|
|
149
|
+
factor: number;
|
|
150
|
+
}): PeakSearchResult | null;
|
|
142
151
|
/** For the robustness bench and tests only. */
|
|
143
152
|
export declare const __internals: {
|
|
144
153
|
searchByPeaks: typeof searchByPeaks;
|
package/lib/image/mark.js
CHANGED
|
@@ -23,20 +23,26 @@
|
|
|
23
23
|
*/
|
|
24
24
|
import { fft2d, toComplex } from "../fft.js";
|
|
25
25
|
/** Bump when the tile layout changes; old keys keep detecting old pictures. */
|
|
26
|
-
export const PIXEL_MARK_SCHEME =
|
|
26
|
+
export const PIXEL_MARK_SCHEME = 2;
|
|
27
27
|
/** Canonical tile resolution (cells per side). */
|
|
28
28
|
const TILE = 128;
|
|
29
29
|
/** Tiles across the picture's shorter side at embed time. */
|
|
30
30
|
export const TILES_PER_SHORT_SIDE = 4;
|
|
31
|
-
/**
|
|
31
|
+
/**
|
|
32
|
+
* The pattern has two parts, by cycles per tile. The coarse part (`BAND_LO` to `BAND_SPLIT`) is
|
|
33
|
+
* what a reduced copy keeps, but nothing in a picture hides a coarse pattern, so it is written
|
|
34
|
+
* faintly. The fine part (`BAND_SPLIT` to `BAND_HI`) has the grain of texture and is written only
|
|
35
|
+
* into texture, where it is as strong as the texture allows.
|
|
36
|
+
*/
|
|
32
37
|
const BAND_LO = 3;
|
|
33
|
-
const
|
|
38
|
+
const BAND_SPLIT = 26;
|
|
39
|
+
const BAND_HI = 48;
|
|
34
40
|
/** Synchronisation peaks per tile, and the standard deviation of each next to the unit-variance noise (0.225² ≈ 5% of its energy per peak). */
|
|
35
41
|
const SYNC_PEAKS = 8;
|
|
36
42
|
const SYNC_AMPLITUDE = 0.225;
|
|
37
43
|
/**
|
|
38
44
|
* Their radii in cycles per tile: low enough to survive a reduction to a third, high enough to stay
|
|
39
|
-
* clear of picture structure. Measured on textured illustrations (
|
|
45
|
+
* clear of picture structure. Measured on textured illustrations (docs/MEASURED.md): at
|
|
40
46
|
* 6–13.5 a quarter-area crop was found in 2 of 10, at 10–18 in 9 of 10; flat pictures do not care.
|
|
41
47
|
*/
|
|
42
48
|
const SYNC_RADIUS_MIN = 10;
|
|
@@ -75,34 +81,45 @@ export async function derivePixelKey(secret, id = "k1") {
|
|
|
75
81
|
const random = sfc32(digest[0], digest[1], digest[2], digest[3]);
|
|
76
82
|
for (let i = 0; i < 16; i++)
|
|
77
83
|
random();
|
|
78
|
-
// White Gaussian noise, band-passed in the frequency domain.
|
|
79
|
-
const
|
|
84
|
+
// White Gaussian noise, band-passed in the frequency domain into the two parts.
|
|
85
|
+
const white = new Float64Array(2 * TILE * TILE);
|
|
80
86
|
for (let i = 0; i < TILE * TILE; i++) {
|
|
81
87
|
const u = Math.max(random(), 1e-12);
|
|
82
|
-
|
|
83
|
-
}
|
|
84
|
-
fft2d(
|
|
85
|
-
|
|
86
|
-
const
|
|
87
|
-
for (let
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
88
|
+
white[2 * i] = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * random());
|
|
89
|
+
}
|
|
90
|
+
fft2d(white, TILE);
|
|
91
|
+
const part = (lo, hi, slope) => {
|
|
92
|
+
const grid = white.slice();
|
|
93
|
+
for (let v = 0; v < TILE; v++) {
|
|
94
|
+
const fv = v <= TILE / 2 ? v : v - TILE;
|
|
95
|
+
for (let u = 0; u < TILE; u++) {
|
|
96
|
+
const fu = u <= TILE / 2 ? u : u - TILE;
|
|
97
|
+
const radius = Math.hypot(fu, fv);
|
|
98
|
+
// Coarse part: amplitude falls as 1/r, so every octave carries the same energy and the
|
|
99
|
+
// rings that survive a small thumbnail hold a fair share of the mark (measured on 256 px
|
|
100
|
+
// JPEG thumbnails: 8/8 found, against 7/8 with 1/sqrt(r)). Fine part: flat.
|
|
101
|
+
const w = bandWeight(radius, lo, hi) / Math.max(1, radius) ** slope;
|
|
102
|
+
grid[2 * (v * TILE + u)] *= w;
|
|
103
|
+
grid[2 * (v * TILE + u) + 1] *= w;
|
|
104
|
+
}
|
|
105
|
+
}
|
|
106
|
+
fft2d(grid, TILE, true);
|
|
107
|
+
const out = new Float32Array(TILE * TILE);
|
|
108
|
+
for (let i = 0; i < TILE * TILE; i++)
|
|
109
|
+
out[i] = grid[2 * i];
|
|
110
|
+
return out;
|
|
111
|
+
};
|
|
112
|
+
const unit = (values) => {
|
|
113
|
+
let sumSq = 0;
|
|
114
|
+
for (let i = 0; i < values.length; i++)
|
|
115
|
+
sumSq += values[i] ** 2;
|
|
116
|
+
const norm = 1 / Math.sqrt(sumSq / values.length);
|
|
117
|
+
for (let i = 0; i < values.length; i++)
|
|
118
|
+
values[i] *= norm;
|
|
119
|
+
return values;
|
|
120
|
+
};
|
|
121
|
+
const coarse = unit(part(BAND_LO, BAND_SPLIT, 1));
|
|
122
|
+
const fine = unit(part(BAND_SPLIT + 3, BAND_HI, 0));
|
|
106
123
|
// Synchronisation peaks: directions spread over the half-turn (the other half is their mirror
|
|
107
124
|
// image in a real picture's spectrum), every radius different, so one rotation and one scale
|
|
108
125
|
// fit the constellation, and its mirror image fits only a mirrored picture.
|
|
@@ -119,20 +136,23 @@ export async function derivePixelKey(secret, id = "k1") {
|
|
|
119
136
|
break;
|
|
120
137
|
}
|
|
121
138
|
}
|
|
139
|
+
// Both parts carry the peaks, so a turned copy is found from flat ground and from texture alike.
|
|
122
140
|
for (const [u, v] of sync) {
|
|
123
141
|
const phase = 2 * Math.PI * random();
|
|
124
142
|
for (let y = 0; y < TILE; y++) {
|
|
125
|
-
for (let x = 0; x < TILE; x++)
|
|
126
|
-
|
|
143
|
+
for (let x = 0; x < TILE; x++) {
|
|
144
|
+
const wave = SYNC_AMPLITUDE * Math.SQRT2 * Math.cos((2 * Math.PI * (u * x + v * y)) / TILE + phase);
|
|
145
|
+
coarse[y * TILE + x] += wave;
|
|
146
|
+
fine[y * TILE + x] += wave;
|
|
147
|
+
}
|
|
127
148
|
}
|
|
128
149
|
}
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
return { tile, sync, spectra: new Map(), id };
|
|
150
|
+
unit(coarse);
|
|
151
|
+
unit(fine);
|
|
152
|
+
const tile = new Float32Array(TILE * TILE);
|
|
153
|
+
for (let i = 0; i < tile.length; i++)
|
|
154
|
+
tile[i] = coarse[i] + fine[i];
|
|
155
|
+
return { tile, coarse, fine, sync, spectra: new Map(), id };
|
|
136
156
|
}
|
|
137
157
|
/** conj(FFT) of the key tile sampled on an `n`×`n` fold grid, limited to frequencies up to `maxRadius`. */
|
|
138
158
|
function keySpectrum(key, n) {
|
|
@@ -204,11 +224,104 @@ function boxBlur(src, width, height, radius) {
|
|
|
204
224
|
}
|
|
205
225
|
return out;
|
|
206
226
|
}
|
|
207
|
-
/**
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
227
|
+
/**
|
|
228
|
+
* How strong each part of the mark is at each place (grey levels, standard
|
|
229
|
+
* deviation), from what the picture itself hides there.
|
|
230
|
+
*
|
|
231
|
+
* The coarse part stays a fraction of a grey level everywhere and is written
|
|
232
|
+
* by dithering: what lands in the file is single-level grain, never a visible
|
|
233
|
+
* blotch or step on flat colour. The fine part is written only where the
|
|
234
|
+
* picture has fine detail of its own, `FINE_SLOPE` grey levels of mark per
|
|
235
|
+
* grey level of detail: noise two fifths as strong as the texture it sits in
|
|
236
|
+
* raises that texture's contrast by about 8 %, under what the eye tells apart.
|
|
237
|
+
* A line or an edge is not texture: the detail is taken as the lowest of its
|
|
238
|
+
* neighbourhood, so flat ground beside a line, and the inside of a drawn
|
|
239
|
+
* shape, stay flat.
|
|
240
|
+
*/
|
|
241
|
+
const COARSE_FLOOR = 0.3;
|
|
242
|
+
const COARSE_SLOPE = 0.05;
|
|
243
|
+
const COARSE_CEIL = 0.8;
|
|
244
|
+
const FINE_SLOPE = 0.4;
|
|
245
|
+
const FINE_CEIL = 4;
|
|
246
|
+
/** Detail under this (grey levels) is sensor grain or compression residue, not texture. */
|
|
247
|
+
const DETAIL_FREE = 0.8;
|
|
248
|
+
/** Lowest value within `radius` cells, separable. */
|
|
249
|
+
function minFilter(src, width, height, radius) {
|
|
250
|
+
const tmp = new Float32Array(src.length);
|
|
251
|
+
const out = new Float32Array(src.length);
|
|
252
|
+
for (let y = 0; y < height; y++) {
|
|
253
|
+
const row = y * width;
|
|
254
|
+
for (let x = 0; x < width; x++) {
|
|
255
|
+
let low = Infinity;
|
|
256
|
+
const to = Math.min(width - 1, x + radius);
|
|
257
|
+
for (let k = Math.max(0, x - radius); k <= to; k++)
|
|
258
|
+
if (src[row + k] < low)
|
|
259
|
+
low = src[row + k];
|
|
260
|
+
tmp[row + x] = low;
|
|
261
|
+
}
|
|
262
|
+
}
|
|
263
|
+
for (let y = 0; y < height; y++) {
|
|
264
|
+
const from = Math.max(0, y - radius);
|
|
265
|
+
const to = Math.min(height - 1, y + radius);
|
|
266
|
+
for (let x = 0; x < width; x++) {
|
|
267
|
+
let low = Infinity;
|
|
268
|
+
for (let k = from; k <= to; k++)
|
|
269
|
+
if (tmp[k * width + x] < low)
|
|
270
|
+
low = tmp[k * width + x];
|
|
271
|
+
out[y * width + x] = low;
|
|
272
|
+
}
|
|
273
|
+
}
|
|
274
|
+
return out;
|
|
275
|
+
}
|
|
276
|
+
/**
|
|
277
|
+
* The amplitude map on a grid `factor` times coarser than the picture (the map
|
|
278
|
+
* is smooth; the embedder reads it bilinearly).
|
|
279
|
+
*/
|
|
280
|
+
function amplitudeMap(image, factor) {
|
|
281
|
+
const { data, width, height } = image;
|
|
282
|
+
const mw = Math.ceil(width / factor);
|
|
283
|
+
const mh = Math.ceil(height / factor);
|
|
284
|
+
const mean = new Float32Array(mw * mh);
|
|
285
|
+
// Detail finer than a cell: mean absolute deviation inside it.
|
|
286
|
+
const fine = new Float32Array(mw * mh);
|
|
287
|
+
const cell = new Float32Array(factor * factor);
|
|
288
|
+
for (let my = 0; my < mh; my++) {
|
|
289
|
+
const yEnd = Math.min(height, (my + 1) * factor);
|
|
290
|
+
for (let mx = 0; mx < mw; mx++) {
|
|
291
|
+
const xEnd = Math.min(width, (mx + 1) * factor);
|
|
292
|
+
let sum = 0;
|
|
293
|
+
let n = 0;
|
|
294
|
+
for (let y = my * factor; y < yEnd; y++) {
|
|
295
|
+
let p = 4 * (y * width + mx * factor);
|
|
296
|
+
for (let x = mx * factor; x < xEnd; x++, p += 4) {
|
|
297
|
+
const v = 0.299 * data[p] + 0.587 * data[p + 1] + 0.114 * data[p + 2];
|
|
298
|
+
cell[n++] = v;
|
|
299
|
+
sum += v;
|
|
300
|
+
}
|
|
301
|
+
}
|
|
302
|
+
const m = sum / n;
|
|
303
|
+
let deviation = 0;
|
|
304
|
+
for (let k = 0; k < n; k++)
|
|
305
|
+
deviation += Math.abs(cell[k] - m);
|
|
306
|
+
mean[my * mw + mx] = m;
|
|
307
|
+
fine[my * mw + mx] = deviation / n;
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// Detail of the two finest octaves only: what has the grain of the fine part and can hide it.
|
|
311
|
+
const smooth = boxBlur(mean, mw, mh, 1);
|
|
312
|
+
for (let i = 0; i < fine.length; i++)
|
|
313
|
+
fine[i] = fine[i] + Math.abs(mean[i] - smooth[i]);
|
|
314
|
+
// A line answers within two cells of itself; the lowest value within four cells is then that of
|
|
315
|
+
// the flat ground beside it. Texture has no flat ground that near, and keeps its value.
|
|
316
|
+
const hidden = boxBlur(minFilter(boxBlur(fine, mw, mh, 1), mw, mh, 4), mw, mh, 2);
|
|
317
|
+
const coarse = new Float32Array(hidden.length);
|
|
318
|
+
for (let i = 0; i < hidden.length; i++) {
|
|
319
|
+
const detail = Math.max(0, hidden[i] - DETAIL_FREE);
|
|
320
|
+
coarse[i] = Math.min(COARSE_CEIL, COARSE_FLOOR + COARSE_SLOPE * detail);
|
|
321
|
+
hidden[i] = Math.min(FINE_CEIL, FINE_SLOPE * detail);
|
|
322
|
+
}
|
|
323
|
+
return { coarse, fine: hidden, width: mw, height: mh };
|
|
324
|
+
}
|
|
212
325
|
/**
|
|
213
326
|
* Adds the mark to `image` in place. Fully transparent pixels are left alone.
|
|
214
327
|
* Returns the PSNR of the change over the touched pixels.
|
|
@@ -217,55 +330,80 @@ export function embedPixelMark(image, key, options = {}) {
|
|
|
217
330
|
const { data, width, height } = image;
|
|
218
331
|
const short = Math.min(width, height);
|
|
219
332
|
const strength = options.strength ?? 1;
|
|
220
|
-
const
|
|
221
|
-
const
|
|
222
|
-
const smooth = boxBlur(y, width, height, 2 * scale);
|
|
223
|
-
const detail = new Float32Array(y.length);
|
|
224
|
-
for (let i = 0; i < y.length; i++)
|
|
225
|
-
detail[i] = Math.abs(y[i] - smooth[i]);
|
|
226
|
-
const activity = boxBlur(detail, width, height, 3 * scale);
|
|
333
|
+
const factor = Math.max(1, Math.round(short / 512));
|
|
334
|
+
const amplitude = amplitudeMap(image, factor);
|
|
227
335
|
// Tile phase per column / row: the period is short / TILES_PER_SHORT_SIDE pixels.
|
|
228
336
|
const cellsPerPixel = (TILES_PER_SHORT_SIDE * TILE) / short;
|
|
229
337
|
const x0 = new Int32Array(width);
|
|
230
338
|
const xw = new Float32Array(width);
|
|
339
|
+
// Where each column reads the amplitude map.
|
|
340
|
+
const ax = new Int32Array(width);
|
|
341
|
+
const aw = new Float32Array(width);
|
|
231
342
|
for (let x = 0; x < width; x++) {
|
|
232
343
|
const pos = (x * cellsPerPixel) % TILE;
|
|
233
344
|
x0[x] = Math.floor(pos);
|
|
234
345
|
xw[x] = pos - x0[x];
|
|
346
|
+
const at = Math.min(amplitude.width - 1, Math.max(0, (x + 0.5) / factor - 0.5));
|
|
347
|
+
ax[x] = Math.min(amplitude.width - 2, Math.floor(at));
|
|
348
|
+
aw[x] = amplitude.width > 1 ? at - ax[x] : 0;
|
|
349
|
+
if (amplitude.width === 1)
|
|
350
|
+
ax[x] = 0;
|
|
235
351
|
}
|
|
352
|
+
const coarseRow = new Float32Array(TILE + 1);
|
|
353
|
+
const fineRow = new Float32Array(TILE + 1);
|
|
354
|
+
const coarseAmp = new Float32Array(amplitude.width + 1);
|
|
355
|
+
const fineAmp = new Float32Array(amplitude.width + 1);
|
|
236
356
|
let squared = 0;
|
|
237
357
|
let touched = 0;
|
|
358
|
+
// The dither: one draw per pixel, the same for every run on the same picture.
|
|
359
|
+
let seed = (width * 73856093) ^ (height * 19349663);
|
|
238
360
|
for (let py = 0; py < height; py++) {
|
|
239
361
|
const pos = (py * cellsPerPixel) % TILE;
|
|
240
362
|
const y0 = Math.floor(pos);
|
|
241
363
|
const wy = pos - y0;
|
|
242
364
|
const rowA = y0 * TILE;
|
|
243
365
|
const rowB = ((y0 + 1) % TILE) * TILE;
|
|
244
|
-
for (let
|
|
245
|
-
|
|
246
|
-
|
|
366
|
+
for (let c = 0; c < TILE; c++) {
|
|
367
|
+
coarseRow[c] = key.coarse[rowA + c] * (1 - wy) + key.coarse[rowB + c] * wy;
|
|
368
|
+
fineRow[c] = key.fine[rowA + c] * (1 - wy) + key.fine[rowB + c] * wy;
|
|
369
|
+
}
|
|
370
|
+
coarseRow[TILE] = coarseRow[0];
|
|
371
|
+
fineRow[TILE] = fineRow[0];
|
|
372
|
+
const at = Math.min(amplitude.height - 1, Math.max(0, (py + 0.5) / factor - 0.5));
|
|
373
|
+
const ay = Math.min(Math.max(0, amplitude.height - 2), Math.floor(at));
|
|
374
|
+
const wa = amplitude.height > 1 ? at - ay : 0;
|
|
375
|
+
const mapA = ay * amplitude.width;
|
|
376
|
+
const mapB = Math.min(amplitude.height - 1, ay + 1) * amplitude.width;
|
|
377
|
+
for (let c = 0; c < amplitude.width; c++) {
|
|
378
|
+
coarseAmp[c] = strength * (amplitude.coarse[mapA + c] * (1 - wa) + amplitude.coarse[mapB + c] * wa);
|
|
379
|
+
fineAmp[c] = strength * (amplitude.fine[mapA + c] * (1 - wa) + amplitude.fine[mapB + c] * wa);
|
|
380
|
+
}
|
|
381
|
+
coarseAmp[amplitude.width] = coarseAmp[amplitude.width - 1];
|
|
382
|
+
fineAmp[amplitude.width] = fineAmp[amplitude.width - 1];
|
|
383
|
+
let p = 4 * py * width;
|
|
384
|
+
for (let px = 0; px < width; px++, p += 4) {
|
|
385
|
+
seed = (Math.imul(seed, 1664525) + 1013904223) | 0;
|
|
247
386
|
if (data[p + 3] === 0)
|
|
248
387
|
continue;
|
|
388
|
+
touched++;
|
|
249
389
|
const cx = x0[px];
|
|
250
|
-
const cx1 = (cx + 1) % TILE;
|
|
251
390
|
const wx = xw[px];
|
|
252
|
-
const
|
|
253
|
-
const
|
|
254
|
-
const
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
391
|
+
const ac = ax[px];
|
|
392
|
+
const wa2 = aw[px];
|
|
393
|
+
const change = (coarseAmp[ac] * (1 - wa2) + coarseAmp[ac + 1] * wa2) * (coarseRow[cx] * (1 - wx) + coarseRow[cx + 1] * wx) +
|
|
394
|
+
(fineAmp[ac] * (1 - wa2) + fineAmp[ac + 1] * wa2) * (fineRow[cx] * (1 - wx) + fineRow[cx + 1] * wx);
|
|
395
|
+
// Dithered rounding: the mean change is the wanted one even where that is a fraction of a level.
|
|
396
|
+
const delta = Math.floor(change + (seed >>> 8) / 16777216);
|
|
397
|
+
if (delta === 0)
|
|
259
398
|
continue;
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
|
|
265
|
-
|
|
266
|
-
|
|
267
|
-
|
|
268
|
-
touched++;
|
|
399
|
+
const r = data[p] + delta;
|
|
400
|
+
const g = data[p + 1] + delta;
|
|
401
|
+
const b = data[p + 2] + delta;
|
|
402
|
+
const before = data[p + 1];
|
|
403
|
+
data[p] = r < 0 ? 0 : r > 255 ? 255 : r;
|
|
404
|
+
data[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
|
|
405
|
+
data[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
|
|
406
|
+
squared += (data[p + 1] - before) ** 2;
|
|
269
407
|
}
|
|
270
408
|
}
|
|
271
409
|
const mse = touched ? squared / touched : 0;
|
|
@@ -298,8 +436,8 @@ export function pixelMarkPlane(width, height, key, tilesPerShortSide = TILES_PER
|
|
|
298
436
|
const cx = x0[px];
|
|
299
437
|
const cx1 = (cx + 1) % TILE;
|
|
300
438
|
const wx = xw[px];
|
|
301
|
-
const top = key.
|
|
302
|
-
const bottom = key.
|
|
439
|
+
const top = key.coarse[rowA + cx] * (1 - wx) + key.coarse[rowA + cx1] * wx;
|
|
440
|
+
const bottom = key.coarse[rowB + cx] * (1 - wx) + key.coarse[rowB + cx1] * wx;
|
|
303
441
|
plane[py * width + px] = top * (1 - wy) + bottom * wy;
|
|
304
442
|
}
|
|
305
443
|
}
|
|
@@ -310,14 +448,16 @@ export function pixelMarkPlane(width, height, key, tilesPerShortSide = TILES_PER
|
|
|
310
448
|
* test looks at 9 shifts of a handful of hypotheses; the search looks at every
|
|
311
449
|
* shift of the grids the synchronisation peaks propose, so its cut is higher.
|
|
312
450
|
*
|
|
313
|
-
* Measured
|
|
314
|
-
*
|
|
315
|
-
*
|
|
316
|
-
*
|
|
317
|
-
*
|
|
451
|
+
* Measured (docs/MEASURED.md) on 1,083 scores of unmarked pictures (as they are
|
|
452
|
+
* and inside a page): no detection, highest score 6.78, 99 % under 6.0. An
|
|
453
|
+
* exponential fit to the top tenth of those scores puts the chance of an
|
|
454
|
+
* unmarked picture passing 8 at about 1 in ten million per key (an
|
|
455
|
+
* extrapolation, not a count; the two highest scores sit above the fit).
|
|
318
456
|
*/
|
|
319
457
|
export const ALIGNED_CUT = 6.5;
|
|
320
|
-
export const SEARCH_CUT =
|
|
458
|
+
export const SEARCH_CUT = 8;
|
|
459
|
+
/** Shorter sides (pixels) pictures are generated in; used when a copy is an unscaled piece of one. */
|
|
460
|
+
const USUAL_SHORT_SIDES = [512, 720, 768, 832, 864, 896, 1024, 1080, 1152, 1280, 1344, 1536, 2048];
|
|
321
461
|
/** Aspect ratios pictures are generated in; used when a copy was stretched. */
|
|
322
462
|
const KNOWN_ASPECTS = [1, 3 / 2, 2 / 3, 4 / 3, 3 / 4, 16 / 9, 9 / 16, 5 / 4, 4 / 5, 21 / 9, 2, 1 / 2, 3, 1 / 3];
|
|
323
463
|
/** Luminance, reduced by an integer factor, high-passed and normalised by local contrast. */
|
|
@@ -365,7 +505,7 @@ function whiten(image, maxShort) {
|
|
|
365
505
|
* noise from rings that hold no mark any more, so each fold is scored per
|
|
366
506
|
* band and the best band counts.
|
|
367
507
|
*/
|
|
368
|
-
const NESTED_BANDS = [7, 11, 17, BAND_HI + 2];
|
|
508
|
+
const NESTED_BANDS = [7, 11, 17, BAND_SPLIT + 2, BAND_HI + 2];
|
|
369
509
|
const bandPlans = new WeakMap();
|
|
370
510
|
function bandPlan(key, n) {
|
|
371
511
|
let plans = bandPlans.get(key);
|
|
@@ -391,14 +531,30 @@ function bandPlan(key, n) {
|
|
|
391
531
|
}
|
|
392
532
|
bins.sort((p, q) => p.r - q.r);
|
|
393
533
|
const edges = NESTED_BANDS.filter((edge, at) => edge < n / 2 || at === 0 || NESTED_BANDS[at - 1] < n / 2 - 1);
|
|
534
|
+
const fineFrom = bins.findIndex((b) => b.r > BAND_SPLIT + 2);
|
|
394
535
|
const plan = {
|
|
536
|
+
ranges: [],
|
|
395
537
|
index: Int32Array.from(bins, (b) => b.i),
|
|
396
538
|
fu: Int16Array.from(bins, (b) => b.fu),
|
|
397
539
|
fv: Int16Array.from(bins, (b) => b.fv),
|
|
398
540
|
ends: edges.map((edge) => bins.filter((b) => b.r <= edge).length).filter((end, at, all) => end > 0 && end !== all[at - 1]),
|
|
399
|
-
keyRe: Float64Array
|
|
400
|
-
keyIm: Float64Array
|
|
541
|
+
keyRe: new Float64Array(bins.length),
|
|
542
|
+
keyIm: new Float64Array(bins.length),
|
|
401
543
|
};
|
|
544
|
+
// A fold bin gathers the pixels of one cell, so what it holds sits half a cell further on than
|
|
545
|
+
// the tile sample of that cell. Half a cell is a sixth of a wave at the fine end of the band:
|
|
546
|
+
// the reference is moved to meet it.
|
|
547
|
+
bins.forEach((b, k) => {
|
|
548
|
+
const angle = (-Math.PI * (b.fu + b.fv)) / TILE;
|
|
549
|
+
const re = spectrum[2 * b.i];
|
|
550
|
+
const im = spectrum[2 * b.i + 1];
|
|
551
|
+
plan.keyRe[k] = re * Math.cos(angle) - im * Math.sin(angle);
|
|
552
|
+
plan.keyIm[k] = re * Math.sin(angle) + im * Math.cos(angle);
|
|
553
|
+
});
|
|
554
|
+
plan.ranges = plan.ends.map((end) => [0, end]);
|
|
555
|
+
// In a textured picture the coarse rings hold almost no mark; read with them, the fine part drowns.
|
|
556
|
+
if (fineFrom > 0 && bins.length - fineFrom > 200)
|
|
557
|
+
plan.ranges.push([fineFrom, bins.length]);
|
|
402
558
|
plans.set(n, plan);
|
|
403
559
|
return plan;
|
|
404
560
|
}
|
|
@@ -472,6 +628,8 @@ function foldScratch(width) {
|
|
|
472
628
|
im: new Float64Array(cells),
|
|
473
629
|
re2: new Float64Array(cells),
|
|
474
630
|
im2: new Float64Array(cells),
|
|
631
|
+
sums: new Float64Array(cells + 1),
|
|
632
|
+
energies: new Float64Array(cells + 1),
|
|
475
633
|
colBin: new Int32Array(width),
|
|
476
634
|
};
|
|
477
635
|
}
|
|
@@ -487,21 +645,25 @@ function scoreNearZero(plan, scratch, n) {
|
|
|
487
645
|
let bestShift = [0, 0];
|
|
488
646
|
for (let dy = -1; dy <= 1; dy++) {
|
|
489
647
|
for (let dx = -1; dx <= 1; dx++) {
|
|
648
|
+
// Running sums over the bins in order; a range is a difference of two of them.
|
|
649
|
+
const sums = scratch.sums;
|
|
650
|
+
const energies = scratch.energies;
|
|
490
651
|
let sum = 0;
|
|
491
652
|
let energy = 0;
|
|
492
|
-
|
|
493
|
-
for (
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
sum += re[k] * Math.cos(angle) - im[k] * Math.sin(angle);
|
|
500
|
-
}
|
|
501
|
-
energy += re[k] * re[k] + im[k] * im[k];
|
|
653
|
+
sums[0] = energies[0] = 0;
|
|
654
|
+
for (let k = 0; k < plan.index.length; k++) {
|
|
655
|
+
if (dx === 0 && dy === 0)
|
|
656
|
+
sum += re[k];
|
|
657
|
+
else {
|
|
658
|
+
const angle = (2 * Math.PI * (plan.fu[k] * dx + plan.fv[k] * dy)) / n;
|
|
659
|
+
sum += re[k] * Math.cos(angle) - im[k] * Math.sin(angle);
|
|
502
660
|
}
|
|
503
|
-
|
|
504
|
-
|
|
661
|
+
energy += re[k] * re[k] + im[k] * im[k];
|
|
662
|
+
sums[k + 1] = sum;
|
|
663
|
+
energies[k + 1] = energy;
|
|
664
|
+
}
|
|
665
|
+
for (const [from, to] of plan.ranges) {
|
|
666
|
+
const score = (sums[to] - sums[from]) / Math.sqrt(energies[to] - energies[from] + 1e-30);
|
|
505
667
|
if (score > best) {
|
|
506
668
|
best = score;
|
|
507
669
|
bestShift = [dx, dy];
|
|
@@ -533,11 +695,12 @@ function scoreAllShifts(plan, scratch, n, bands, halfTurn) {
|
|
|
533
695
|
}
|
|
534
696
|
let bestScore = -Infinity;
|
|
535
697
|
let bestShift = [0, 0];
|
|
536
|
-
|
|
537
|
-
|
|
698
|
+
let bestRange = [0, 0];
|
|
699
|
+
const ranges = bands >= plan.ends.length ? plan.ranges : plan.ranges.slice(0, bands);
|
|
700
|
+
for (const [from, end] of ranges) {
|
|
538
701
|
surface.fill(0, 0, 2 * n * n);
|
|
539
702
|
let energy = 0;
|
|
540
|
-
for (let k =
|
|
703
|
+
for (let k = from; k < end; k++) {
|
|
541
704
|
surface[2 * plan.index[k]] = re[k];
|
|
542
705
|
surface[2 * plan.index[k] + 1] = im[k];
|
|
543
706
|
energy += re[k] * re[k] + im[k] * im[k];
|
|
@@ -557,6 +720,31 @@ function scoreAllShifts(plan, scratch, n, bands, halfTurn) {
|
|
|
557
720
|
if (score > bestScore) {
|
|
558
721
|
bestScore = score;
|
|
559
722
|
bestShift = [at % n, Math.floor(at / n)];
|
|
723
|
+
bestRange = [from, end];
|
|
724
|
+
}
|
|
725
|
+
}
|
|
726
|
+
// The surface is known at whole bins; the true offset falls between them, and half a bin is a
|
|
727
|
+
// sixth of a wave at the fine end of the band. Around the peak the correlation is summed
|
|
728
|
+
// directly at quarter-bin steps.
|
|
729
|
+
const [from, end] = bestRange;
|
|
730
|
+
let energy = 0;
|
|
731
|
+
for (let k = from; k < end; k++)
|
|
732
|
+
energy += re[k] * re[k] + im[k] * im[k];
|
|
733
|
+
const norm = 1 / Math.sqrt(energy + 1e-30);
|
|
734
|
+
const [sx, sy] = bestShift;
|
|
735
|
+
for (let dy = -0.5; dy <= 0.5; dy += 0.25) {
|
|
736
|
+
for (let dx = -0.5; dx <= 0.5; dx += 0.25) {
|
|
737
|
+
if (dx === 0 && dy === 0)
|
|
738
|
+
continue;
|
|
739
|
+
let sum = 0;
|
|
740
|
+
for (let k = from; k < end; k++) {
|
|
741
|
+
const angle = (2 * Math.PI * (plan.fu[k] * (sx + dx) + plan.fv[k] * (sy + dy))) / n;
|
|
742
|
+
sum += re[k] * Math.cos(angle) - im[k] * Math.sin(angle);
|
|
743
|
+
}
|
|
744
|
+
if (sum * norm > bestScore) {
|
|
745
|
+
bestScore = sum * norm;
|
|
746
|
+
bestShift = [sx + dx, sy + dy];
|
|
747
|
+
}
|
|
560
748
|
}
|
|
561
749
|
}
|
|
562
750
|
return { score: bestScore, shift: bestShift };
|
|
@@ -591,10 +779,30 @@ export function detectPixelMark(image, key, options = {}) {
|
|
|
591
779
|
}
|
|
592
780
|
if (options.alignedOnly)
|
|
593
781
|
return { ...none, score: Math.max(0, aligned.score) };
|
|
782
|
+
// 1b. A piece cut out of a picture of a usual size and not scaled: the period is the picture's,
|
|
783
|
+
// only the offset is unknown. The fine part of the mark is read in full, which the next two
|
|
784
|
+
// steps (grids found to about a bin) cannot always do.
|
|
785
|
+
let cut = { score: -Infinity, period: 0 };
|
|
786
|
+
for (const short of USUAL_SHORT_SIDES) {
|
|
787
|
+
const period = short / TILES_PER_SHORT_SIDE / w.factor;
|
|
788
|
+
if (period < 96 || period > 2 * Math.max(w.width, w.height))
|
|
789
|
+
continue;
|
|
790
|
+
const plan = bandPlan(key, 128);
|
|
791
|
+
crossSpectrum(w, plan, [1 / period, 0], [0, 1 / period], 128, scratch);
|
|
792
|
+
const peak = scoreAllShifts(plan, scratch, 128, plan.ranges.length, false);
|
|
793
|
+
if (peak.score > cut.score)
|
|
794
|
+
cut = { score: peak.score, period: period * w.factor };
|
|
795
|
+
}
|
|
796
|
+
if (cut.score >= SEARCH_CUT) {
|
|
797
|
+
return { detected: true, score: cut.score, mode: "search", period: [cut.period, cut.period], rotation: 0, mirrored: false, keyId: key.id };
|
|
798
|
+
}
|
|
594
799
|
// 2. Unknown geometry (crop, screen capture, rotation, mirror, stretch): the
|
|
595
800
|
// synchronisation peaks give the tile grid, the fold along it gives the verdict.
|
|
596
801
|
const coarse = whiten(image, 448);
|
|
597
|
-
|
|
802
|
+
// The peaks are looked for in a reduced picture; the grid they give is then checked on one
|
|
803
|
+
// sharp enough to still hold the fine part of the mark.
|
|
804
|
+
const sharp = w.factor === 1 ? w : whiten(image, 1100);
|
|
805
|
+
const found = searchByPeaks(coarse, key, scratch, sharp.factor < coarse.factor ? sharp : coarse);
|
|
598
806
|
if (found && found.score >= SEARCH_CUT) {
|
|
599
807
|
return {
|
|
600
808
|
detected: true,
|
|
@@ -607,7 +815,7 @@ export function detectPixelMark(image, key, options = {}) {
|
|
|
607
815
|
};
|
|
608
816
|
}
|
|
609
817
|
if (options.fast)
|
|
610
|
-
return { ...none, score: Math.max(0, aligned.score, found?.score ?? 0) };
|
|
818
|
+
return { ...none, score: Math.max(0, aligned.score, cut.score, found?.score ?? 0) };
|
|
611
819
|
// 3. Too weak for the peaks (a small or heavily recompressed crop that was not
|
|
612
820
|
// turned): scan the period on the lowest rings, which gather the whole mark.
|
|
613
821
|
const plan32 = bandPlan(key, 32);
|
|
@@ -641,7 +849,7 @@ export function detectPixelMark(image, key, options = {}) {
|
|
|
641
849
|
if (scanned.score >= SEARCH_CUT) {
|
|
642
850
|
return { detected: true, score: scanned.score, mode: "search", period: [scanned.period, scanned.period], rotation: 0, mirrored: false, keyId: key.id };
|
|
643
851
|
}
|
|
644
|
-
return { ...none, score: Math.max(0, aligned.score, found?.score ?? 0, scanned.score) };
|
|
852
|
+
return { ...none, score: Math.max(0, aligned.score, cut.score, found?.score ?? 0, scanned.score) };
|
|
645
853
|
}
|
|
646
854
|
/** Fourier power of the whitened picture, zero-padded so a peak spans a few bins, flattened over radius. */
|
|
647
855
|
function peakSpectrum(w) {
|
|
@@ -965,7 +1173,35 @@ function verifyGrid(w, key, scratch, grid) {
|
|
|
965
1173
|
mirrored: grid.fu[0] * grid.fv[1] - grid.fu[1] * grid.fv[0] < 0,
|
|
966
1174
|
};
|
|
967
1175
|
}
|
|
968
|
-
|
|
1176
|
+
/** A grid is worth refining from this score: above what most unmarked pictures reach on any grid. */
|
|
1177
|
+
const REFINE_FROM = 4.5;
|
|
1178
|
+
function refineGrid(w, key, scratch, start, first) {
|
|
1179
|
+
let best = first;
|
|
1180
|
+
let grid = start;
|
|
1181
|
+
for (const [scaleStep, angleStep] of [[0.003, 0.0025], [0.001, 0.0008]]) {
|
|
1182
|
+
let improved = true;
|
|
1183
|
+
for (let round = 0; round < 3 && improved; round++) {
|
|
1184
|
+
improved = false;
|
|
1185
|
+
for (const [ds, da] of [[scaleStep, 0], [-scaleStep, 0], [0, angleStep], [0, -angleStep]]) {
|
|
1186
|
+
const c = Math.cos(da) * (1 + ds);
|
|
1187
|
+
const s = Math.sin(da) * (1 + ds);
|
|
1188
|
+
const trial = {
|
|
1189
|
+
score: grid.score,
|
|
1190
|
+
fu: [grid.fu[0] * c - grid.fu[1] * s, grid.fu[0] * s + grid.fu[1] * c],
|
|
1191
|
+
fv: [grid.fv[0] * c - grid.fv[1] * s, grid.fv[0] * s + grid.fv[1] * c],
|
|
1192
|
+
};
|
|
1193
|
+
const result = verifyGrid(w, key, scratch, trial);
|
|
1194
|
+
if (result.score > best.score) {
|
|
1195
|
+
best = result;
|
|
1196
|
+
grid = trial;
|
|
1197
|
+
improved = true;
|
|
1198
|
+
}
|
|
1199
|
+
}
|
|
1200
|
+
}
|
|
1201
|
+
}
|
|
1202
|
+
return best;
|
|
1203
|
+
}
|
|
1204
|
+
function searchByPeaks(w, key, scratch, sharp = w) {
|
|
969
1205
|
if (key.sync.length < SYNC_PEAKS - 1)
|
|
970
1206
|
return null;
|
|
971
1207
|
const spectrum = peakSpectrum(w);
|
|
@@ -976,7 +1212,16 @@ function searchByPeaks(w, key, scratch) {
|
|
|
976
1212
|
for (const candidate of candidates) {
|
|
977
1213
|
const fitted = fitGrid(spectrum, key.sync, candidate);
|
|
978
1214
|
for (const grid of fitted ? [fitted] : [candidate]) {
|
|
979
|
-
|
|
1215
|
+
// Cycles per pixel of the reduced picture, in pixels of the sharp one.
|
|
1216
|
+
const ratio = sharp.factor / w.factor;
|
|
1217
|
+
const onSharp = { score: grid.score, fu: [grid.fu[0] * ratio, grid.fu[1] * ratio], fv: [grid.fv[0] * ratio, grid.fv[1] * ratio] };
|
|
1218
|
+
let result = verifyGrid(sharp, key, scratch, onSharp);
|
|
1219
|
+
// The peaks give the grid to about a bin of the spectrum; the fine part of the mark only
|
|
1220
|
+
// adds up when the grid is right to a fraction of a percent. A grid that already shows the
|
|
1221
|
+
// mark faintly is nudged in scale and angle to where it shows best.
|
|
1222
|
+
if (result.score >= REFINE_FROM)
|
|
1223
|
+
result = refineGrid(sharp, key, scratch, onSharp, result);
|
|
1224
|
+
result.period = [result.period[0] / ratio, result.period[1] / ratio];
|
|
980
1225
|
result.sync = constellationScore(spectrum, key.sync, grid.fu, grid.fv);
|
|
981
1226
|
if (!best || result.score > best.score)
|
|
982
1227
|
best = result;
|
package/lib/video/index.d.ts
CHANGED
|
@@ -20,8 +20,11 @@ export interface FrameOverlayOptions {
|
|
|
20
20
|
/** Tiles across the frame's shorter side. */
|
|
21
21
|
tilesPerShortSide?: number;
|
|
22
22
|
}
|
|
23
|
-
/**
|
|
24
|
-
|
|
23
|
+
/**
|
|
24
|
+
* Tuned on H.264 re-encodes (bench/video.ts). At 3 the pattern showed as a film over flat
|
|
25
|
+
* areas of the frame; 2 is the lowest amplitude the bench was run at.
|
|
26
|
+
*/
|
|
27
|
+
export declare const FRAME_MARK_AMPLITUDE = 2;
|
|
25
28
|
export declare const FRAME_MARK_TILES = 4;
|
|
26
29
|
/**
|
|
27
30
|
* One 8-bit grey plane, `width`×`height`, where 128 means "leave the pixel"
|
package/lib/video/index.js
CHANGED
|
@@ -11,8 +11,11 @@
|
|
|
11
11
|
* encode video: frames come from and go to whatever codec the host uses.
|
|
12
12
|
*/
|
|
13
13
|
import { detectPixelMark, pixelMarkPlane } from "../image/mark.js";
|
|
14
|
-
/**
|
|
15
|
-
|
|
14
|
+
/**
|
|
15
|
+
* Tuned on H.264 re-encodes (bench/video.ts). At 3 the pattern showed as a film over flat
|
|
16
|
+
* areas of the frame; 2 is the lowest amplitude the bench was run at.
|
|
17
|
+
*/
|
|
18
|
+
export const FRAME_MARK_AMPLITUDE = 2;
|
|
16
19
|
export const FRAME_MARK_TILES = 4;
|
|
17
20
|
/**
|
|
18
21
|
* One 8-bit grey plane, `width`×`height`, where 128 means "leave the pixel"
|
package/package.json
CHANGED