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.
@@ -0,0 +1,995 @@
1
+ /**
2
+ * Imperceptible pixel mark for pictures: one keyed, band-limited
3
+ * noise tile repeated across the picture and added to its luminance at about
4
+ * one grey level (more where texture hides it).
5
+ *
6
+ * Why a repeated tile: a copy that was scaled, cropped or pasted into a larger
7
+ * screen capture no longer has the picture's own frame, so the detector cannot
8
+ * line anything up with the picture edges. A periodic pattern needs no frame:
9
+ * the detector folds the suspect at a candidate period and correlates the fold
10
+ * with the key tile over every cyclic shift at once. Scale is the period,
11
+ * a crop is a shift.
12
+ *
13
+ * Rotation and mirroring move the tile grid itself. For those the tile also
14
+ * holds a few plain sinusoids (the synchronisation peaks): in the suspect's
15
+ * Fourier magnitude they are sharp points, untouched by crops and shifts, that
16
+ * turn and scale with the picture. The detector finds the constellation, reads
17
+ * off rotation, scale, mirror and stretch, and folds along the recovered grid.
18
+ * This is the long-established tiled spread-spectrum design with a Fourier
19
+ * synchronisation signal; nothing in it is learned.
20
+ *
21
+ * The tile is derived from a secret key, so reading or forging the mark needs
22
+ * the key; the mark carries one bit (ours / not ours) per key.
23
+ */
24
+ import { fft2d, toComplex } from "../fft.js";
25
+ /** Bump when the tile layout changes; old keys keep detecting old pictures. */
26
+ export const PIXEL_MARK_SCHEME = 1;
27
+ /** Canonical tile resolution (cells per side). */
28
+ const TILE = 128;
29
+ /** Tiles across the picture's shorter side at embed time. */
30
+ export const TILES_PER_SHORT_SIDE = 4;
31
+ /** Pattern band in cycles per tile. Below: picture content dominates and the eye sees it. Above: thumbnails erase it. */
32
+ const BAND_LO = 3;
33
+ const BAND_HI = 26;
34
+ /** 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
+ const SYNC_PEAKS = 8;
36
+ const SYNC_AMPLITUDE = 0.225;
37
+ /**
38
+ * 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 (bench/image.ts): at
40
+ * 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
+ */
42
+ const SYNC_RADIUS_MIN = 10;
43
+ const SYNC_RADIUS_MAX = 18;
44
+ function sfc32(a, b, c, d) {
45
+ return () => {
46
+ a |= 0;
47
+ b |= 0;
48
+ c |= 0;
49
+ d |= 0;
50
+ const t = (((a + b) | 0) + d) | 0;
51
+ d = (d + 1) | 0;
52
+ a = b ^ (b >>> 9);
53
+ b = (c + (c << 3)) | 0;
54
+ c = (c << 21) | (c >>> 11);
55
+ c = (c + t) | 0;
56
+ return (t >>> 0) / 4294967296;
57
+ };
58
+ }
59
+ /** Radial weight of the pattern band (smooth edges, so resampling does not ring). */
60
+ function bandWeight(radius, lo, hi) {
61
+ if (radius < lo - 1 || radius > hi + 2)
62
+ return 0;
63
+ const rise = Math.min(1, Math.max(0, radius - (lo - 1)));
64
+ const fall = Math.min(1, Math.max(0, (hi + 2 - radius) / 2));
65
+ return rise * fall;
66
+ }
67
+ /** Derives the tile of a key. `secret` is any byte string with at least 128 bits of entropy. */
68
+ export async function derivePixelKey(secret, id = "k1") {
69
+ const bytes = typeof secret === "string" ? new TextEncoder().encode(secret) : secret;
70
+ const label = new TextEncoder().encode(`pixel-mark/${PIXEL_MARK_SCHEME}/`);
71
+ const input = new Uint8Array(label.length + bytes.length);
72
+ input.set(label);
73
+ input.set(bytes, label.length);
74
+ const digest = new Uint32Array(await crypto.subtle.digest("SHA-256", input));
75
+ const random = sfc32(digest[0], digest[1], digest[2], digest[3]);
76
+ for (let i = 0; i < 16; i++)
77
+ random();
78
+ // White Gaussian noise, band-passed in the frequency domain.
79
+ const grid = new Float64Array(2 * TILE * TILE);
80
+ for (let i = 0; i < TILE * TILE; i++) {
81
+ const u = Math.max(random(), 1e-12);
82
+ grid[2 * i] = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * random());
83
+ }
84
+ fft2d(grid, TILE);
85
+ for (let v = 0; v < TILE; v++) {
86
+ const fv = v <= TILE / 2 ? v : v - TILE;
87
+ for (let u = 0; u < TILE; u++) {
88
+ const fu = u <= TILE / 2 ? u : u - TILE;
89
+ const radius = Math.hypot(fu, fv);
90
+ // Amplitude falls as 1/r: every octave carries the same energy, so the rings
91
+ // that survive a small thumbnail hold a fair share of the mark. Measured on
92
+ // 256 px JPEG thumbnails (robustness-bench): 8/8 found, against 7/8 with 1/sqrt(r).
93
+ const w = bandWeight(radius, BAND_LO, BAND_HI) / Math.max(1, radius);
94
+ grid[2 * (v * TILE + u)] *= w;
95
+ grid[2 * (v * TILE + u) + 1] *= w;
96
+ }
97
+ }
98
+ fft2d(grid, TILE, true);
99
+ const tile = new Float32Array(TILE * TILE);
100
+ let sumSq = 0;
101
+ for (let i = 0; i < TILE * TILE; i++)
102
+ sumSq += grid[2 * i] ** 2;
103
+ const norm = 1 / Math.sqrt(sumSq / (TILE * TILE));
104
+ for (let i = 0; i < TILE * TILE; i++)
105
+ tile[i] = grid[2 * i] * norm;
106
+ // Synchronisation peaks: directions spread over the half-turn (the other half is their mirror
107
+ // image in a real picture's spectrum), every radius different, so one rotation and one scale
108
+ // fit the constellation, and its mirror image fits only a mirrored picture.
109
+ const sync = [];
110
+ for (let i = 0; i < SYNC_PEAKS; i++) {
111
+ for (let attempt = 0; attempt < 50; attempt++) {
112
+ const angle = ((i + 0.15 + 0.7 * random()) * Math.PI) / SYNC_PEAKS;
113
+ const radius = SYNC_RADIUS_MIN + ((i * 5) % SYNC_PEAKS + random()) * ((SYNC_RADIUS_MAX - SYNC_RADIUS_MIN) / SYNC_PEAKS);
114
+ const u = Math.round(radius * Math.cos(angle));
115
+ const v = Math.round(radius * Math.sin(angle));
116
+ if (sync.some(([pu, pv]) => (pu === u && pv === v) || (pu === -u && pv === -v) || Math.abs(Math.hypot(pu, pv) - Math.hypot(u, v)) < 0.35))
117
+ continue;
118
+ sync.push([u, v]);
119
+ break;
120
+ }
121
+ }
122
+ for (const [u, v] of sync) {
123
+ const phase = 2 * Math.PI * random();
124
+ for (let y = 0; y < TILE; y++) {
125
+ for (let x = 0; x < TILE; x++)
126
+ tile[y * TILE + x] += SYNC_AMPLITUDE * Math.SQRT2 * Math.cos((2 * Math.PI * (u * x + v * y)) / TILE + phase);
127
+ }
128
+ }
129
+ sumSq = 0;
130
+ for (let i = 0; i < TILE * TILE; i++)
131
+ sumSq += tile[i] ** 2;
132
+ const renorm = 1 / Math.sqrt(sumSq / (TILE * TILE));
133
+ for (let i = 0; i < TILE * TILE; i++)
134
+ tile[i] *= renorm;
135
+ return { tile, sync, spectra: new Map(), id };
136
+ }
137
+ /** conj(FFT) of the key tile sampled on an `n`×`n` fold grid, limited to frequencies up to `maxRadius`. */
138
+ function keySpectrum(key, n) {
139
+ const cached = key.spectra.get(n);
140
+ if (cached)
141
+ return cached;
142
+ const step = TILE / n;
143
+ const sampled = new Float64Array(n * n);
144
+ for (let y = 0; y < n; y++) {
145
+ for (let x = 0; x < n; x++) {
146
+ // Box average of the canonical tile over the fold bin.
147
+ let sum = 0;
148
+ for (let dy = 0; dy < step; dy++)
149
+ for (let dx = 0; dx < step; dx++)
150
+ sum += key.tile[(y * step + dy) * TILE + x * step + dx];
151
+ sampled[y * n + x] = sum / (step * step);
152
+ }
153
+ }
154
+ const spectrum = toComplex(sampled, n);
155
+ fft2d(spectrum, n);
156
+ for (let v = 0; v < n; v++) {
157
+ const fv = v <= n / 2 ? v : v - n;
158
+ for (let u = 0; u < n; u++) {
159
+ const fu = u <= n / 2 ? u : u - n;
160
+ const i = v * n + u;
161
+ // Outside the band the tile holds rounding noise only.
162
+ if (bandWeight(Math.hypot(fu, fv), BAND_LO, BAND_HI) === 0)
163
+ spectrum[2 * i] = spectrum[2 * i + 1] = 0;
164
+ else
165
+ spectrum[2 * i + 1] = -spectrum[2 * i + 1];
166
+ }
167
+ }
168
+ key.spectra.set(n, spectrum);
169
+ return spectrum;
170
+ }
171
+ // ─── Shared image helpers ─────────────────────────────────────────────────────
172
+ function luminance(image) {
173
+ const { data, width, height } = image;
174
+ const out = new Float32Array(width * height);
175
+ for (let i = 0, p = 0; i < out.length; i++, p += 4)
176
+ out[i] = 0.299 * data[p] + 0.587 * data[p + 1] + 0.114 * data[p + 2];
177
+ return out;
178
+ }
179
+ /** Separable box blur with edge clamping; `radius` in pixels. */
180
+ function boxBlur(src, width, height, radius) {
181
+ if (radius < 1)
182
+ return src.slice();
183
+ const tmp = new Float32Array(src.length);
184
+ const out = new Float32Array(src.length);
185
+ const span = 2 * radius + 1;
186
+ for (let y = 0; y < height; y++) {
187
+ const row = y * width;
188
+ let sum = 0;
189
+ for (let k = -radius; k <= radius; k++)
190
+ sum += src[row + Math.min(width - 1, Math.max(0, k))];
191
+ for (let x = 0; x < width; x++) {
192
+ tmp[row + x] = sum / span;
193
+ sum += src[row + Math.min(width - 1, x + radius + 1)] - src[row + Math.max(0, x - radius)];
194
+ }
195
+ }
196
+ for (let x = 0; x < width; x++) {
197
+ let sum = 0;
198
+ for (let k = -radius; k <= radius; k++)
199
+ sum += tmp[Math.min(height - 1, Math.max(0, k)) * width + x];
200
+ for (let y = 0; y < height; y++) {
201
+ out[y * width + x] = sum / span;
202
+ sum += tmp[Math.min(height - 1, y + radius + 1) * width + x] - tmp[Math.max(0, y - radius) * width + x];
203
+ }
204
+ }
205
+ return out;
206
+ }
207
+ /** Amplitude (grey levels, standard deviation) on flat and on fully textured ground. */
208
+ const AMP_FLAT = 1.0;
209
+ const AMP_TEXTURE = 3.2;
210
+ /** Local activity (mean absolute high-pass, grey levels) at which the texture amplitude is reached. */
211
+ const ACTIVITY_FULL = 9;
212
+ /**
213
+ * Adds the mark to `image` in place. Fully transparent pixels are left alone.
214
+ * Returns the PSNR of the change over the touched pixels.
215
+ */
216
+ export function embedPixelMark(image, key, options = {}) {
217
+ const { data, width, height } = image;
218
+ const short = Math.min(width, height);
219
+ const strength = options.strength ?? 1;
220
+ const y = luminance(image);
221
+ const scale = Math.max(1, Math.round(short / 512));
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);
227
+ // Tile phase per column / row: the period is short / TILES_PER_SHORT_SIDE pixels.
228
+ const cellsPerPixel = (TILES_PER_SHORT_SIDE * TILE) / short;
229
+ const x0 = new Int32Array(width);
230
+ const xw = new Float32Array(width);
231
+ for (let x = 0; x < width; x++) {
232
+ const pos = (x * cellsPerPixel) % TILE;
233
+ x0[x] = Math.floor(pos);
234
+ xw[x] = pos - x0[x];
235
+ }
236
+ let squared = 0;
237
+ let touched = 0;
238
+ for (let py = 0; py < height; py++) {
239
+ const pos = (py * cellsPerPixel) % TILE;
240
+ const y0 = Math.floor(pos);
241
+ const wy = pos - y0;
242
+ const rowA = y0 * TILE;
243
+ const rowB = ((y0 + 1) % TILE) * TILE;
244
+ for (let px = 0; px < width; px++) {
245
+ const i = py * width + px;
246
+ const p = 4 * i;
247
+ if (data[p + 3] === 0)
248
+ continue;
249
+ const cx = x0[px];
250
+ const cx1 = (cx + 1) % TILE;
251
+ const wx = xw[px];
252
+ const top = key.tile[rowA + cx] * (1 - wx) + key.tile[rowA + cx1] * wx;
253
+ const bottom = key.tile[rowB + cx] * (1 - wx) + key.tile[rowB + cx1] * wx;
254
+ const pattern = top * (1 - wy) + bottom * wy;
255
+ const amp = AMP_FLAT + (AMP_TEXTURE - AMP_FLAT) * Math.min(1, activity[i] / ACTIVITY_FULL);
256
+ const delta = Math.round(strength * amp * pattern);
257
+ if (delta === 0) {
258
+ touched++;
259
+ continue;
260
+ }
261
+ for (let c = 0; c < 3; c++) {
262
+ const before = data[p + c];
263
+ const after = Math.min(255, Math.max(0, before + delta));
264
+ data[p + c] = after;
265
+ if (c === 1)
266
+ squared += (after - before) ** 2;
267
+ }
268
+ touched++;
269
+ }
270
+ }
271
+ const mse = touched ? squared / touched : 0;
272
+ return { psnr: mse > 0 ? 10 * Math.log10((255 * 255) / mse) : Infinity };
273
+ }
274
+ /**
275
+ * The mark of a `width`×`height` picture as a plane of signed grey levels with
276
+ * unit variance, at the place and scale {@link embedPixelMark} writes it. For
277
+ * pipelines that add the mark themselves (a video encoder blending one plane
278
+ * onto every frame). `tilesPerShortSide` sets the tile size; fewer, larger
279
+ * tiles survive stronger compression and reduction.
280
+ */
281
+ export function pixelMarkPlane(width, height, key, tilesPerShortSide = TILES_PER_SHORT_SIDE) {
282
+ const cellsPerPixel = (tilesPerShortSide * TILE) / Math.min(width, height);
283
+ const x0 = new Int32Array(width);
284
+ const xw = new Float32Array(width);
285
+ for (let x = 0; x < width; x++) {
286
+ const pos = (x * cellsPerPixel) % TILE;
287
+ x0[x] = Math.floor(pos);
288
+ xw[x] = pos - x0[x];
289
+ }
290
+ const plane = new Float32Array(width * height);
291
+ for (let py = 0; py < height; py++) {
292
+ const pos = (py * cellsPerPixel) % TILE;
293
+ const y0 = Math.floor(pos);
294
+ const wy = pos - y0;
295
+ const rowA = y0 * TILE;
296
+ const rowB = ((y0 + 1) % TILE) * TILE;
297
+ for (let px = 0; px < width; px++) {
298
+ const cx = x0[px];
299
+ const cx1 = (cx + 1) % TILE;
300
+ const wx = xw[px];
301
+ const top = key.tile[rowA + cx] * (1 - wx) + key.tile[rowA + cx1] * wx;
302
+ const bottom = key.tile[rowB + cx] * (1 - wx) + key.tile[rowB + cx1] * wx;
303
+ plane[py * width + px] = top * (1 - wy) + bottom * wy;
304
+ }
305
+ }
306
+ return plane;
307
+ }
308
+ /**
309
+ * Decision cuts in standard deviations of the correlation surface. The aligned
310
+ * test looks at 9 shifts of a handful of hypotheses; the search looks at every
311
+ * shift of the grids the synchronisation peaks propose, so its cut is higher.
312
+ *
313
+ * Measured with bench/image.ts --null-only on 802
314
+ * unmarked pictures (as they are and inside a page, three keys, 3,204 scores):
315
+ * no detection, highest score 6.61. An exponential fit to the top tenth of
316
+ * those scores puts the chance of an unmarked picture passing the search cut
317
+ * at about 3 in a million per key (an extrapolation, not a count).
318
+ */
319
+ export const ALIGNED_CUT = 6.5;
320
+ export const SEARCH_CUT = 7.5;
321
+ /** Aspect ratios pictures are generated in; used when a copy was stretched. */
322
+ 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
+ /** Luminance, reduced by an integer factor, high-passed and normalised by local contrast. */
324
+ function whiten(image, maxShort) {
325
+ const full = luminance(image);
326
+ const factor = Math.max(1, Math.floor(Math.min(image.width, image.height) / maxShort));
327
+ let width = image.width;
328
+ let height = image.height;
329
+ let y = full;
330
+ if (factor > 1) {
331
+ width = Math.floor(image.width / factor);
332
+ height = Math.floor(image.height / factor);
333
+ y = new Float32Array(width * height);
334
+ const area = factor * factor;
335
+ for (let py = 0; py < height; py++) {
336
+ for (let px = 0; px < width; px++) {
337
+ let sum = 0;
338
+ for (let dy = 0; dy < factor; dy++) {
339
+ const row = (py * factor + dy) * image.width + px * factor;
340
+ for (let dx = 0; dx < factor; dx++)
341
+ sum += full[row + dx];
342
+ }
343
+ y[py * width + px] = sum / area;
344
+ }
345
+ }
346
+ }
347
+ const low = boxBlur(boxBlur(y, width, height, 4), width, height, 4);
348
+ const residual = new Float32Array(y.length);
349
+ const energy = new Float32Array(y.length);
350
+ for (let i = 0; i < y.length; i++) {
351
+ residual[i] = y[i] - low[i];
352
+ energy[i] = residual[i] * residual[i];
353
+ }
354
+ const local = boxBlur(energy, width, height, 6);
355
+ const values = new Float32Array(y.length);
356
+ for (let i = 0; i < y.length; i++) {
357
+ const v = residual[i] / Math.sqrt(local[i] + 1.5);
358
+ values[i] = v > 3 ? 3 : v < -3 ? -3 : v;
359
+ }
360
+ return { values, width, height, factor };
361
+ }
362
+ /**
363
+ * Upper edges (cycles per tile) of the nested bands the correlation is read in.
364
+ * A thumbnail keeps only the lowest rings; reading the full band there adds
365
+ * noise from rings that hold no mark any more, so each fold is scored per
366
+ * band and the best band counts.
367
+ */
368
+ const NESTED_BANDS = [7, 11, 17, BAND_HI + 2];
369
+ const bandPlans = new WeakMap();
370
+ function bandPlan(key, n) {
371
+ let plans = bandPlans.get(key);
372
+ if (!plans)
373
+ bandPlans.set(key, (plans = new Map()));
374
+ const cached = plans.get(n);
375
+ if (cached)
376
+ return cached;
377
+ const spectrum = keySpectrum(key, n);
378
+ const bins = [];
379
+ for (let v = 0; v < n; v++) {
380
+ const fv = v < n / 2 ? v : v - n;
381
+ for (let u = 0; u < n; u++) {
382
+ const fu = u < n / 2 ? u : u - n;
383
+ const i = v * n + u;
384
+ // The Nyquist row and column have no mirror bin; leave them out.
385
+ if (u === n / 2 || v === n / 2)
386
+ continue;
387
+ if (spectrum[2 * i] === 0 && spectrum[2 * i + 1] === 0)
388
+ continue;
389
+ bins.push({ i, fu, fv, r: Math.hypot(fu, fv) });
390
+ }
391
+ }
392
+ bins.sort((p, q) => p.r - q.r);
393
+ const edges = NESTED_BANDS.filter((edge, at) => edge < n / 2 || at === 0 || NESTED_BANDS[at - 1] < n / 2 - 1);
394
+ const plan = {
395
+ index: Int32Array.from(bins, (b) => b.i),
396
+ fu: Int16Array.from(bins, (b) => b.fu),
397
+ fv: Int16Array.from(bins, (b) => b.fv),
398
+ ends: edges.map((edge) => bins.filter((b) => b.r <= edge).length).filter((end, at, all) => end > 0 && end !== all[at - 1]),
399
+ keyRe: Float64Array.from(bins, (b) => spectrum[2 * b.i]),
400
+ keyIm: Float64Array.from(bins, (b) => spectrum[2 * b.i + 1]),
401
+ };
402
+ plans.set(n, plan);
403
+ return plan;
404
+ }
405
+ /**
406
+ * Folds `w` along the tile axes `fu`, `fv` (cycles per pixel of the whitened
407
+ * image; an upright grid of period p is [1/p, 0], [0, 1/p]) into an n×n grid
408
+ * and returns its whitened cross-spectrum with the key at the plan's bins:
409
+ * each frequency keeps the phase difference and the key's magnitude, so a
410
+ * picture's own coloured spectrum cannot dominate the sum.
411
+ */
412
+ function crossSpectrum(w, plan, fu, fv, n, scratch) {
413
+ const { acc, count, grid, re, im } = scratch;
414
+ acc.fill(0, 0, n * n);
415
+ count.fill(0, 0, n * n);
416
+ if (fu[1] === 0 && fv[0] === 0) {
417
+ // Upright grid: the bin of a pixel is its column's bin plus its row's.
418
+ const colBin = scratch.colBin;
419
+ for (let x = 0; x < w.width; x++) {
420
+ const phase = x * fu[0];
421
+ colBin[x] = Math.min(n - 1, Math.floor((phase - Math.floor(phase)) * n));
422
+ }
423
+ for (let y = 0; y < w.height; y++) {
424
+ const phase = y * fv[1];
425
+ const rowBase = Math.min(n - 1, Math.floor((phase - Math.floor(phase)) * n)) * n;
426
+ const row = y * w.width;
427
+ for (let x = 0; x < w.width; x++) {
428
+ const bin = rowBase + colBin[x];
429
+ acc[bin] += w.values[row + x];
430
+ count[bin]++;
431
+ }
432
+ }
433
+ }
434
+ else {
435
+ for (let y = 0; y < w.height; y++) {
436
+ const row = y * w.width;
437
+ let pu = y * fu[1];
438
+ let pv = y * fv[1];
439
+ for (let x = 0; x < w.width; x++) {
440
+ const bu = Math.floor((pu - Math.floor(pu)) * n);
441
+ const bv = Math.floor((pv - Math.floor(pv)) * n);
442
+ const bin = (bv >= n ? n - 1 : bv) * n + (bu >= n ? n - 1 : bu);
443
+ acc[bin] += w.values[row + x];
444
+ count[bin]++;
445
+ pu += fu[0];
446
+ pv += fv[0];
447
+ }
448
+ }
449
+ }
450
+ for (let i = 0; i < n * n; i++) {
451
+ grid[2 * i] = count[i] ? acc[i] / Math.sqrt(count[i]) : 0;
452
+ grid[2 * i + 1] = 0;
453
+ }
454
+ fft2d(grid.subarray(0, 2 * n * n), n);
455
+ for (let k = 0; k < plan.index.length; k++) {
456
+ const i = plan.index[k];
457
+ const fr = grid[2 * i];
458
+ const fi = grid[2 * i + 1];
459
+ const norm = 1 / (Math.hypot(fr, fi) + 1e-12);
460
+ re[k] = (fr * plan.keyRe[k] - fi * plan.keyIm[k]) * norm;
461
+ im[k] = (fr * plan.keyIm[k] + fi * plan.keyRe[k]) * norm;
462
+ }
463
+ }
464
+ function foldScratch(width) {
465
+ const cells = 128 * 128;
466
+ return {
467
+ acc: new Float64Array(cells),
468
+ count: new Uint32Array(cells),
469
+ grid: new Float64Array(2 * cells),
470
+ surface: new Float64Array(2 * cells),
471
+ re: new Float64Array(cells),
472
+ im: new Float64Array(cells),
473
+ re2: new Float64Array(cells),
474
+ im2: new Float64Array(cells),
475
+ colBin: new Int32Array(width),
476
+ };
477
+ }
478
+ /**
479
+ * Score at the shifts within one bin of zero: the copy kept the picture's
480
+ * frame, so the tile grid starts at its corner. No inverse transform: the
481
+ * correlation at a shift is a direct sum over the band, and its spread over
482
+ * all shifts follows from the band's energy.
483
+ */
484
+ function scoreNearZero(plan, scratch, n) {
485
+ const { re, im } = scratch;
486
+ let best = -Infinity;
487
+ let bestShift = [0, 0];
488
+ for (let dy = -1; dy <= 1; dy++) {
489
+ for (let dx = -1; dx <= 1; dx++) {
490
+ let sum = 0;
491
+ let energy = 0;
492
+ let from = 0;
493
+ for (const end of plan.ends) {
494
+ for (let k = from; k < end; k++) {
495
+ if (dx === 0 && dy === 0)
496
+ sum += re[k];
497
+ else {
498
+ const angle = (2 * Math.PI * (plan.fu[k] * dx + plan.fv[k] * dy)) / n;
499
+ sum += re[k] * Math.cos(angle) - im[k] * Math.sin(angle);
500
+ }
501
+ energy += re[k] * re[k] + im[k] * im[k];
502
+ }
503
+ from = end;
504
+ const score = sum / Math.sqrt(energy + 1e-30);
505
+ if (score > best) {
506
+ best = score;
507
+ bestShift = [dx, dy];
508
+ }
509
+ }
510
+ }
511
+ }
512
+ return { score: best, shift: bestShift };
513
+ }
514
+ /** Score over every cyclic shift: the copy lost its frame (crop, screen capture). */
515
+ function scoreAllShifts(plan, scratch, n, bands, halfTurn) {
516
+ const { surface } = scratch;
517
+ let { re, im } = scratch;
518
+ if (halfTurn) {
519
+ // The tile turned by a half-turn has the conjugate spectrum: fold · key instead of fold · conj(key).
520
+ // re/im hold (fold · conj(key)) / |fold|; multiplying by key² / |key|² gives the other product.
521
+ const { re2, im2 } = scratch;
522
+ for (let k = 0; k < plan.index.length; k++) {
523
+ const kr = plan.keyRe[k];
524
+ const ki = -plan.keyIm[k]; // key itself (plan holds its conjugate)
525
+ const mag = kr * kr + ki * ki + 1e-30;
526
+ const sr = (kr * kr - ki * ki) / mag;
527
+ const si = (2 * kr * ki) / mag;
528
+ re2[k] = re[k] * sr - im[k] * si;
529
+ im2[k] = re[k] * si + im[k] * sr;
530
+ }
531
+ re = re2;
532
+ im = im2;
533
+ }
534
+ let bestScore = -Infinity;
535
+ let bestShift = [0, 0];
536
+ const ends = plan.ends.slice(0, bands);
537
+ for (const end of ends) {
538
+ surface.fill(0, 0, 2 * n * n);
539
+ let energy = 0;
540
+ for (let k = 0; k < end; k++) {
541
+ surface[2 * plan.index[k]] = re[k];
542
+ surface[2 * plan.index[k] + 1] = im[k];
543
+ energy += re[k] * re[k] + im[k] * im[k];
544
+ }
545
+ fft2d(surface.subarray(0, 2 * n * n), n, true);
546
+ // The inverse transform divides by n²; a surface of unit-variance noise has spread sqrt(energy) / n².
547
+ const spread = Math.sqrt(energy + 1e-30) / (n * n);
548
+ let best = -Infinity;
549
+ let at = 0;
550
+ for (let i = 0; i < n * n; i++) {
551
+ if (surface[2 * i] > best) {
552
+ best = surface[2 * i];
553
+ at = i;
554
+ }
555
+ }
556
+ const score = best / spread;
557
+ if (score > bestScore) {
558
+ bestScore = score;
559
+ bestShift = [at % n, Math.floor(at / n)];
560
+ }
561
+ }
562
+ return { score: bestScore, shift: bestShift };
563
+ }
564
+ const gridFor = (period) => (period >= 96 ? 128 : period >= 40 ? 64 : 32);
565
+ /** Looks for the mark of `key` in `image`. */
566
+ export function detectPixelMark(image, key, options = {}) {
567
+ const none = { detected: false, score: 0, mode: "none", keyId: key.id };
568
+ if (Math.min(image.width, image.height) < 48)
569
+ return none;
570
+ // 1. The copy kept the frame: the period follows from its size.
571
+ const w = whiten(image, 640);
572
+ const scratch = foldScratch(Math.max(w.width, image.width));
573
+ let aligned = { score: -Infinity, shift: [0, 0], period: [0, 0] };
574
+ const tried = new Set();
575
+ for (const aspect of [w.width / w.height, ...KNOWN_ASPECTS]) {
576
+ const px = w.width / (TILES_PER_SHORT_SIDE * Math.max(1, aspect));
577
+ const py = w.height / (TILES_PER_SHORT_SIDE * Math.max(1, 1 / aspect));
578
+ const id = `${px.toFixed(2)}:${py.toFixed(2)}`;
579
+ if (tried.has(id) || Math.min(px, py) < 8)
580
+ continue;
581
+ tried.add(id);
582
+ const n = gridFor(Math.min(px, py));
583
+ const plan = bandPlan(key, n);
584
+ crossSpectrum(w, plan, [1 / px, 0], [0, 1 / py], n, scratch);
585
+ const peak = scoreNearZero(plan, scratch, n);
586
+ if (peak.score > aligned.score)
587
+ aligned = { ...peak, period: [px * w.factor, py * w.factor] };
588
+ }
589
+ if (aligned.score >= ALIGNED_CUT) {
590
+ return { detected: true, score: aligned.score, mode: "aligned", period: aligned.period, keyId: key.id };
591
+ }
592
+ if (options.alignedOnly)
593
+ return { ...none, score: Math.max(0, aligned.score) };
594
+ // 2. Unknown geometry (crop, screen capture, rotation, mirror, stretch): the
595
+ // synchronisation peaks give the tile grid, the fold along it gives the verdict.
596
+ const coarse = whiten(image, 448);
597
+ const found = searchByPeaks(coarse, key, scratch);
598
+ if (found && found.score >= SEARCH_CUT) {
599
+ return {
600
+ detected: true,
601
+ score: found.score,
602
+ mode: "search",
603
+ period: [found.period[0] * coarse.factor, found.period[1] * coarse.factor],
604
+ rotation: found.rotation,
605
+ mirrored: found.mirrored,
606
+ keyId: key.id,
607
+ };
608
+ }
609
+ if (options.fast)
610
+ return { ...none, score: Math.max(0, aligned.score, found?.score ?? 0) };
611
+ // 3. Too weak for the peaks (a small or heavily recompressed crop that was not
612
+ // turned): scan the period on the lowest rings, which gather the whole mark.
613
+ const plan32 = bandPlan(key, 32);
614
+ const candidates = [];
615
+ const maxPeriod = Math.max(coarse.width, coarse.height) * 1.5;
616
+ for (let period = 16; period <= maxPeriod; period *= 1.012) {
617
+ crossSpectrum(coarse, plan32, [1 / period, 0], [0, 1 / period], 32, scratch);
618
+ candidates.push({ score: scoreAllShifts(plan32, scratch, 32, 2, false).score, period });
619
+ }
620
+ candidates.sort((p, q) => q.score - p.score);
621
+ const seeds = [];
622
+ for (const candidate of candidates) {
623
+ if (seeds.length >= 4)
624
+ break;
625
+ if (seeds.some((seed) => Math.abs(seed / candidate.period - 1) < 0.03))
626
+ continue;
627
+ seeds.push(candidate.period);
628
+ }
629
+ let scanned = { score: -Infinity, period: 0 };
630
+ for (const seed of seeds) {
631
+ for (let k = -8; k <= 8; k++) {
632
+ const period = seed * (1 + k * 0.0015);
633
+ const n = gridFor(period);
634
+ const plan = bandPlan(key, n);
635
+ crossSpectrum(coarse, plan, [1 / period, 0], [0, 1 / period], n, scratch);
636
+ const peak = scoreAllShifts(plan, scratch, n, plan.ends.length, false);
637
+ if (peak.score > scanned.score)
638
+ scanned = { score: peak.score, period: period * coarse.factor };
639
+ }
640
+ }
641
+ if (scanned.score >= SEARCH_CUT) {
642
+ return { detected: true, score: scanned.score, mode: "search", period: [scanned.period, scanned.period], rotation: 0, mirrored: false, keyId: key.id };
643
+ }
644
+ return { ...none, score: Math.max(0, aligned.score, found?.score ?? 0, scanned.score) };
645
+ }
646
+ /** Fourier power of the whitened picture, zero-padded so a peak spans a few bins, flattened over radius. */
647
+ function peakSpectrum(w) {
648
+ const n = 1024;
649
+ const grid = new Float64Array(2 * n * n);
650
+ // A picture longer than the grid contributes its centre.
651
+ const offX = Math.max(0, Math.floor((w.width - n) / 2));
652
+ const offY = Math.max(0, Math.floor((w.height - n) / 2));
653
+ const cw = Math.min(n, w.width);
654
+ const ch = Math.min(n, w.height);
655
+ for (let y = 0; y < ch; y++) {
656
+ for (let x = 0; x < cw; x++)
657
+ grid[2 * (y * n + x)] = w.values[(y + offY) * w.width + x + offX];
658
+ }
659
+ fft2d(grid, n);
660
+ const power = new Float32Array(n * n);
661
+ const half = n / 2;
662
+ const sums = new Float64Array(half + 2);
663
+ const counts = new Uint32Array(half + 2);
664
+ const radius = new Uint16Array(n * n);
665
+ for (let v = 0; v < n; v++) {
666
+ const fv = v < half ? v : v - n;
667
+ for (let u = 0; u < n; u++) {
668
+ const fu = u < half ? u : u - n;
669
+ const i = v * n + u;
670
+ const p = grid[2 * i] ** 2 + grid[2 * i + 1] ** 2;
671
+ power[i] = p;
672
+ const r = Math.min(half + 1, Math.round(Math.sqrt(fu * fu + fv * fv)));
673
+ radius[i] = r;
674
+ sums[r] += p;
675
+ counts[r]++;
676
+ }
677
+ }
678
+ // Mean power per radius, smoothed over neighbouring radii so a peak does not lift its own baseline.
679
+ const baseline = new Float64Array(half + 2);
680
+ for (let r = 0; r < half + 2; r++) {
681
+ let s = 0;
682
+ let c = 0;
683
+ for (let k = Math.max(0, r - 3); k <= Math.min(half + 1, r + 3); k++) {
684
+ s += sums[k];
685
+ c += counts[k];
686
+ }
687
+ baseline[r] = c ? s / c : 1;
688
+ }
689
+ for (let i = 0; i < n * n; i++)
690
+ power[i] = power[i] / (baseline[radius[i]] + 1e-30);
691
+ // Then over each bin's own neighbourhood: lines and repeating structure in a picture make
692
+ // streaks and lumps in its spectrum, a synchronisation peak is a single sharp point.
693
+ const reach = 5;
694
+ const span = 2 * reach + 1;
695
+ const rowSums = new Float32Array(n * n);
696
+ for (let v = 0; v < n; v++) {
697
+ const row = v * n;
698
+ let sum = 0;
699
+ for (let k = -reach; k <= reach; k++)
700
+ sum += power[row + ((k + n) & (n - 1))];
701
+ for (let u = 0; u < n; u++) {
702
+ rowSums[row + u] = sum;
703
+ sum += power[row + ((u + reach + 1) & (n - 1))] - power[row + ((u - reach + n) & (n - 1))];
704
+ }
705
+ }
706
+ const local = new Float32Array(n * n);
707
+ for (let u = 0; u < n; u++) {
708
+ let sum = 0;
709
+ for (let k = -reach; k <= reach; k++)
710
+ sum += rowSums[((k + n) & (n - 1)) * n + u];
711
+ for (let v = 0; v < n; v++) {
712
+ local[v * n + u] = sum;
713
+ sum += rowSums[((v + reach + 1) & (n - 1)) * n + u] - rowSums[((v - reach + n) & (n - 1)) * n + u];
714
+ }
715
+ }
716
+ for (let i = 0; i < n * n; i++) {
717
+ // The bin's own power is left out of its neighbourhood mean.
718
+ const around = (local[i] - power[i]) / (span * span - 1);
719
+ power[i] = power[i] / (around + 0.05);
720
+ }
721
+ const peaks = new Float32Array(n * n);
722
+ for (let v = 0; v < n; v++) {
723
+ const up = ((v - 1 + n) % n) * n;
724
+ const mid = v * n;
725
+ const down = ((v + 1) % n) * n;
726
+ for (let u = 0; u < n; u++) {
727
+ const l = (u - 1 + n) % n;
728
+ const r = (u + 1) % n;
729
+ peaks[mid + u] = Math.max(power[up + l], power[up + u], power[up + r], power[mid + l], power[mid + u], power[mid + r], power[down + l], power[down + u], power[down + r]);
730
+ }
731
+ }
732
+ return { n, power, peaks };
733
+ }
734
+ /** A peak far above its ring counts no more than this: one line of the picture must not outvote the constellation. */
735
+ const PEAK_CAP = 24;
736
+ function keepBest(list, candidate, limit) {
737
+ if (list.length >= limit && candidate.score <= list[list.length - 1].score)
738
+ return;
739
+ // One entry per neighbourhood of the grid.
740
+ const scale = Math.hypot(candidate.fu[0], candidate.fu[1]) * 0.05;
741
+ const near = list.findIndex((c) => Math.hypot(c.fu[0] - candidate.fu[0], c.fu[1] - candidate.fu[1]) < scale && Math.hypot(c.fv[0] - candidate.fv[0], c.fv[1] - candidate.fv[1]) < scale);
742
+ if (near >= 0) {
743
+ if (list[near].score >= candidate.score)
744
+ return;
745
+ list.splice(near, 1);
746
+ }
747
+ list.push(candidate);
748
+ list.sort((p, q) => q.score - p.score);
749
+ if (list.length > limit)
750
+ list.length = limit;
751
+ }
752
+ /** Sum of the capped peak heights where the constellation falls for the tile axes (fu, fv). */
753
+ function constellationScore(spectrum, sync, fu, fv) {
754
+ const { n, peaks } = spectrum;
755
+ const half = n / 2;
756
+ let score = 0;
757
+ let inside = 0;
758
+ for (const [u, v] of sync) {
759
+ const kx = Math.round(n * (u * fu[0] + v * fv[0]));
760
+ const ky = Math.round(n * (u * fu[1] + v * fv[1]));
761
+ if (kx >= half - 1 || kx <= 1 - half || ky >= half - 1 || ky <= 1 - half || kx * kx + ky * ky < 64)
762
+ continue;
763
+ const value = peaks[((ky + n) % n) * n + ((kx + n) % n)];
764
+ score += value > PEAK_CAP ? PEAK_CAP : value;
765
+ inside++;
766
+ }
767
+ return inside >= SYNC_PEAKS - 2 ? score * (SYNC_PEAKS / inside) : 0;
768
+ }
769
+ /**
770
+ * Every turned, scaled and mirrored square grid: the constellation's points are
771
+ * looked up for each rotation over the half-turn (the other half gives the
772
+ * same constellation), both mirrorings and every period.
773
+ */
774
+ function searchSquareGrids(spectrum, key, minPeriod, maxPeriod) {
775
+ const { n, peaks } = spectrum;
776
+ const half = n / 2;
777
+ const count = key.sync.length;
778
+ const radii = key.sync.map(([u, v]) => Math.hypot(u, v));
779
+ const angles = key.sync.map(([u, v]) => Math.atan2(v, u));
780
+ const cos = new Float64Array(count);
781
+ const sin = new Float64Array(count);
782
+ const best = [];
783
+ const step = (0.5 * Math.PI) / 180;
784
+ for (const mirror of [1, -1]) {
785
+ for (let angle = 0; angle < Math.PI; angle += step) {
786
+ for (let i = 0; i < count; i++) {
787
+ cos[i] = Math.cos(mirror * angles[i] + angle) * radii[i] * n;
788
+ sin[i] = Math.sin(mirror * angles[i] + angle) * radii[i] * n;
789
+ }
790
+ for (let period = minPeriod; period <= maxPeriod; period *= 1.01) {
791
+ const inverse = 1 / period;
792
+ let score = 0;
793
+ let inside = 0;
794
+ for (let i = 0; i < count; i++) {
795
+ const kx = Math.round(cos[i] * inverse);
796
+ const ky = Math.round(sin[i] * inverse);
797
+ if (kx >= half - 1 || kx <= 1 - half || ky >= half - 1 || ky <= 1 - half || kx * kx + ky * ky < 64)
798
+ continue;
799
+ const value = peaks[((ky + n) & (n - 1)) * n + ((kx + n) & (n - 1))];
800
+ score += value > PEAK_CAP ? PEAK_CAP : value;
801
+ inside++;
802
+ }
803
+ if (inside < count - 2)
804
+ continue;
805
+ score *= count / inside;
806
+ if (best.length >= 8 && score <= best[best.length - 1].score)
807
+ continue;
808
+ const c = Math.cos(angle) * inverse;
809
+ const s = Math.sin(angle) * inverse;
810
+ keepBest(best, { score, fu: [c, s], fv: [-s * mirror, c * mirror] }, 8);
811
+ }
812
+ }
813
+ }
814
+ return best;
815
+ }
816
+ /**
817
+ * Any grid, also stretched or sheared: two of the strongest points of the
818
+ * spectrum are taken for two points of the constellation, which fixes the grid;
819
+ * the other points must then fall on peaks too.
820
+ */
821
+ function searchAnyGrids(spectrum, key, minPeriod, maxPeriod) {
822
+ const { n, power } = spectrum;
823
+ const half = n / 2;
824
+ // Strongest local maxima of the upper half-plane (the lower half mirrors it).
825
+ const found = [];
826
+ for (let ky = 0; ky < half - 2; ky++) {
827
+ for (let kx = -half + 2; kx < half - 2; kx++) {
828
+ if (ky === 0 && kx <= 0)
829
+ continue;
830
+ if (kx * kx + ky * ky < 64)
831
+ continue;
832
+ const row = ky * n;
833
+ const col = (kx + n) & (n - 1);
834
+ const value = power[row + col];
835
+ if (value < 6)
836
+ continue;
837
+ const up = ((ky - 1 + n) & (n - 1)) * n;
838
+ const down = (ky + 1) * n;
839
+ const l = (col - 1 + n) & (n - 1);
840
+ const r = (col + 1) & (n - 1);
841
+ if (value < power[row + l] || value < power[row + r] || value < power[up + col] || value < power[down + col] ||
842
+ value < power[up + l] || value < power[up + r] || value < power[down + l] || value < power[down + r])
843
+ continue;
844
+ found.push({ x: kx / n, y: ky / n, value });
845
+ }
846
+ }
847
+ found.sort((p, q) => q.value - p.value);
848
+ const strong = found.slice(0, 64);
849
+ const best = [];
850
+ const minF = 1 / maxPeriod;
851
+ const maxF = 1 / minPeriod;
852
+ for (let a = 0; a < strong.length; a++) {
853
+ for (let b = 0; b < strong.length; b++) {
854
+ if (a === b)
855
+ continue;
856
+ for (const sign of [1, -1]) {
857
+ const ax = strong[a].x, ay = strong[a].y;
858
+ const bx = strong[b].x * sign, by = strong[b].y * sign;
859
+ for (let i = 0; i < key.sync.length; i++) {
860
+ const [u1, v1] = key.sync[i];
861
+ for (let j = 0; j < key.sync.length; j++) {
862
+ if (i === j)
863
+ continue;
864
+ const [u2, v2] = key.sync[j];
865
+ const det = u1 * v2 - u2 * v1;
866
+ if (det === 0)
867
+ continue;
868
+ // u1·fu + v1·fv = a, u2·fu + v2·fv = b
869
+ const fu = [(ax * v2 - bx * v1) / det, (ay * v2 - by * v1) / det];
870
+ const fv = [(u1 * bx - u2 * ax) / det, (u1 * by - u2 * ay) / det];
871
+ const lu = Math.hypot(fu[0], fu[1]);
872
+ const lv = Math.hypot(fv[0], fv[1]);
873
+ if (lu < minF || lu > maxF || lv < minF || lv > maxF)
874
+ continue;
875
+ const ratio = lu / lv;
876
+ if (ratio < 0.45 || ratio > 2.2)
877
+ continue;
878
+ // The axes of a stretched, turned picture stay near a right angle; a strong shear is not a copy we look for.
879
+ const cosine = Math.abs(fu[0] * fv[0] + fu[1] * fv[1]) / (lu * lv);
880
+ if (cosine > 0.5)
881
+ continue;
882
+ const score = constellationScore(spectrum, key.sync, fu, fv);
883
+ if (score > 0)
884
+ keepBest(best, { score, fu, fv }, 6);
885
+ }
886
+ }
887
+ }
888
+ }
889
+ }
890
+ return best;
891
+ }
892
+ /**
893
+ * Sharpens a grid on the measured peak positions: each constellation point is
894
+ * located to a fraction of a bin and the two tile axes are fitted to all of
895
+ * them by least squares. Returns null when too few points stand out.
896
+ */
897
+ function fitGrid(spectrum, sync, start) {
898
+ const { n, power } = spectrum;
899
+ const half = n / 2;
900
+ let fu = start.fu;
901
+ let fv = start.fv;
902
+ for (let pass = 0; pass < 3; pass++) {
903
+ let suu = 0, suv = 0, svv = 0, sux = 0, suy = 0, svx = 0, svy = 0;
904
+ let used = 0;
905
+ const reach = pass === 0 ? 3 : 1;
906
+ for (const [u, v] of sync) {
907
+ const cx = Math.round(n * (u * fu[0] + v * fv[0]));
908
+ const cy = Math.round(n * (u * fu[1] + v * fv[1]));
909
+ if (Math.abs(cx) >= half - 4 || Math.abs(cy) >= half - 4)
910
+ continue;
911
+ let bestValue = 0, bx = cx, by = cy;
912
+ for (let dy = -reach; dy <= reach; dy++) {
913
+ for (let dx = -reach; dx <= reach; dx++) {
914
+ const value = power[((cy + dy + n) & (n - 1)) * n + ((cx + dx + n) & (n - 1))];
915
+ if (value > bestValue) {
916
+ bestValue = value;
917
+ bx = cx + dx;
918
+ by = cy + dy;
919
+ }
920
+ }
921
+ }
922
+ if (bestValue < 5)
923
+ continue;
924
+ const at = (x, y) => Math.log(power[((y + n) & (n - 1)) * n + ((x + n) & (n - 1))] + 1e-6);
925
+ const c = at(bx, by);
926
+ const parabola = (lo, hi) => {
927
+ const curve = lo - 2 * c + hi;
928
+ return curve < -1e-9 ? Math.max(-0.5, Math.min(0.5, (0.5 * (lo - hi)) / curve)) : 0;
929
+ };
930
+ const mx = (bx + parabola(at(bx - 1, by), at(bx + 1, by))) / n;
931
+ const my = (by + parabola(at(bx, by - 1), at(bx, by + 1))) / n;
932
+ const weight = Math.min(bestValue, PEAK_CAP);
933
+ suu += weight * u * u;
934
+ suv += weight * u * v;
935
+ svv += weight * v * v;
936
+ sux += weight * u * mx;
937
+ suy += weight * u * my;
938
+ svx += weight * v * mx;
939
+ svy += weight * v * my;
940
+ used++;
941
+ }
942
+ const det = suu * svv - suv * suv;
943
+ if (used < 4 || Math.abs(det) < 1e-12)
944
+ return pass === 0 ? null : { score: start.score, fu, fv };
945
+ fu = [(sux * svv - svx * suv) / det, (suy * svv - svy * suv) / det];
946
+ fv = [(svx * suu - sux * suv) / det, (svy * suu - suy * suv) / det];
947
+ }
948
+ return { score: constellationScore(spectrum, sync, fu, fv), fu, fv };
949
+ }
950
+ /** Folds along a candidate grid and correlates with the key, the tile upright and turned by a half-turn. */
951
+ function verifyGrid(w, key, scratch, grid) {
952
+ const periodU = 1 / Math.hypot(grid.fu[0], grid.fu[1]);
953
+ const periodV = 1 / Math.hypot(grid.fv[0], grid.fv[1]);
954
+ const n = gridFor(Math.min(periodU, periodV));
955
+ const plan = bandPlan(key, n);
956
+ crossSpectrum(w, plan, grid.fu, grid.fv, n, scratch);
957
+ const upright = scoreAllShifts(plan, scratch, n, plan.ends.length, false);
958
+ const turned = scoreAllShifts(plan, scratch, n, plan.ends.length, true);
959
+ const halfTurn = turned.score > upright.score;
960
+ const degrees = (Math.atan2(grid.fu[1], grid.fu[0]) * 180) / Math.PI + (halfTurn ? 180 : 0);
961
+ return {
962
+ score: Math.max(upright.score, turned.score),
963
+ period: [periodU, periodV],
964
+ rotation: ((degrees % 360) + 360) % 360,
965
+ mirrored: grid.fu[0] * grid.fv[1] - grid.fu[1] * grid.fv[0] < 0,
966
+ };
967
+ }
968
+ function searchByPeaks(w, key, scratch) {
969
+ if (key.sync.length < SYNC_PEAKS - 1)
970
+ return null;
971
+ const spectrum = peakSpectrum(w);
972
+ const maxPeriod = Math.max(w.width, w.height) * 1.5;
973
+ const minPeriod = 24;
974
+ let best = null;
975
+ const consider = (candidates) => {
976
+ for (const candidate of candidates) {
977
+ const fitted = fitGrid(spectrum, key.sync, candidate);
978
+ for (const grid of fitted ? [fitted] : [candidate]) {
979
+ const result = verifyGrid(w, key, scratch, grid);
980
+ result.sync = constellationScore(spectrum, key.sync, grid.fu, grid.fv);
981
+ if (!best || result.score > best.score)
982
+ best = result;
983
+ }
984
+ if (best && best.score >= SEARCH_CUT + 4)
985
+ return true;
986
+ }
987
+ return false;
988
+ };
989
+ if (consider(searchSquareGrids(spectrum, key, minPeriod, maxPeriod).slice(0, 5)))
990
+ return best;
991
+ consider(searchAnyGrids(spectrum, key, minPeriod, maxPeriod).slice(0, 4));
992
+ return best;
993
+ }
994
+ /** For the robustness bench and tests only. */
995
+ export const __internals = { searchByPeaks, whiten, peakSpectrum, searchSquareGrids, searchAnyGrids, fitGrid, verifyGrid, constellationScore, foldScratch };