apertaluce 0.1.0 → 0.3.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/lib/image/mark.js CHANGED
@@ -23,20 +23,37 @@
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 = 1;
26
+ export const PIXEL_MARK_SCHEME = 3;
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
- /** Pattern band in cycles per tile. Below: picture content dominates and the eye sees it. Above: thumbnails erase it. */
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 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). */
38
+ const BAND_SPLIT = 26;
39
+ const BAND_HI = 48;
40
+ /**
41
+ * Synchronisation peaks: plain sinusoids in the tile, sharp points in a copy's spectrum that
42
+ * turn and scale with it. Each part of the mark has its own eight. Those of the coarse part
43
+ * survive a reduction to a third; they hold two thirds of that part's energy
44
+ * (`COARSE_SYNC` each, next to unit-variance noise), because a faint pattern is found by its
45
+ * peaks or not at all. Those of the fine part (`FINE_SYNC` each) sit at the grain of texture
46
+ * and are as strong as the texture lets the fine part be: a copy that is not much reduced is
47
+ * found by them even when the picture is texture all over.
48
+ */
35
49
  const SYNC_PEAKS = 8;
36
- const SYNC_AMPLITUDE = 0.225;
50
+ const COARSE_SYNC = 0.5;
51
+ const FINE_SYNC = 0.225;
52
+ const FINE_SYNC_RADIUS_MIN = 30;
53
+ const FINE_SYNC_RADIUS_MAX = 44;
37
54
  /**
38
55
  * 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
56
+ * clear of picture structure. Measured on textured illustrations (docs/MEASURED.md): at
40
57
  * 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
58
  */
42
59
  const SYNC_RADIUS_MIN = 10;
@@ -75,64 +92,84 @@ export async function derivePixelKey(secret, id = "k1") {
75
92
  const random = sfc32(digest[0], digest[1], digest[2], digest[3]);
76
93
  for (let i = 0; i < 16; i++)
77
94
  random();
78
- // White Gaussian noise, band-passed in the frequency domain.
79
- const grid = new Float64Array(2 * TILE * TILE);
95
+ // White Gaussian noise, band-passed in the frequency domain into the two parts.
96
+ const white = new Float64Array(2 * TILE * TILE);
80
97
  for (let i = 0; i < TILE * TILE; i++) {
81
98
  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;
99
+ white[2 * i] = Math.sqrt(-2 * Math.log(u)) * Math.cos(2 * Math.PI * random());
100
+ }
101
+ fft2d(white, TILE);
102
+ const part = (lo, hi, slope) => {
103
+ const grid = white.slice();
104
+ for (let v = 0; v < TILE; v++) {
105
+ const fv = v <= TILE / 2 ? v : v - TILE;
106
+ for (let u = 0; u < TILE; u++) {
107
+ const fu = u <= TILE / 2 ? u : u - TILE;
108
+ const radius = Math.hypot(fu, fv);
109
+ // Coarse part: amplitude falls as 1/r, so every octave carries the same energy and the
110
+ // rings that survive a small thumbnail hold a fair share of the mark (measured on 256 px
111
+ // JPEG thumbnails: 8/8 found, against 7/8 with 1/sqrt(r)). Fine part: flat.
112
+ const w = bandWeight(radius, lo, hi) / Math.max(1, radius) ** slope;
113
+ grid[2 * (v * TILE + u)] *= w;
114
+ grid[2 * (v * TILE + u) + 1] *= w;
115
+ }
116
+ }
117
+ fft2d(grid, TILE, true);
118
+ const out = new Float32Array(TILE * TILE);
119
+ for (let i = 0; i < TILE * TILE; i++)
120
+ out[i] = grid[2 * i];
121
+ return out;
122
+ };
123
+ const unit = (values) => {
124
+ let sumSq = 0;
125
+ for (let i = 0; i < values.length; i++)
126
+ sumSq += values[i] ** 2;
127
+ const norm = 1 / Math.sqrt(sumSq / values.length);
128
+ for (let i = 0; i < values.length; i++)
129
+ values[i] *= norm;
130
+ return values;
131
+ };
132
+ const coarse = unit(part(BAND_LO, BAND_SPLIT, 1));
133
+ const fine = unit(part(BAND_SPLIT + 3, BAND_HI, 0));
106
134
  // Synchronisation peaks: directions spread over the half-turn (the other half is their mirror
107
135
  // image in a real picture's spectrum), every radius different, so one rotation and one scale
108
136
  // 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;
137
+ const constellation = (radiusMin, radiusMax) => {
138
+ const points = [];
139
+ for (let i = 0; i < SYNC_PEAKS; i++) {
140
+ for (let attempt = 0; attempt < 50; attempt++) {
141
+ const angle = ((i + 0.15 + 0.7 * random()) * Math.PI) / SYNC_PEAKS;
142
+ const radius = radiusMin + ((i * 5) % SYNC_PEAKS + random()) * ((radiusMax - radiusMin) / SYNC_PEAKS);
143
+ const u = Math.round(radius * Math.cos(angle));
144
+ const v = Math.round(radius * Math.sin(angle));
145
+ if (points.some(([pu, pv]) => (pu === u && pv === v) || (pu === -u && pv === -v) || Math.abs(Math.hypot(pu, pv) - Math.hypot(u, v)) < 0.35))
146
+ continue;
147
+ points.push([u, v]);
148
+ break;
149
+ }
120
150
  }
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);
151
+ return points;
152
+ };
153
+ const addPeaks = (target, points, amplitude) => {
154
+ for (const [u, v] of points) {
155
+ const phase = 2 * Math.PI * random();
156
+ for (let y = 0; y < TILE; y++) {
157
+ for (let x = 0; x < TILE; x++)
158
+ target[y * TILE + x] += amplitude * Math.SQRT2 * Math.cos((2 * Math.PI * (u * x + v * y)) / TILE + phase);
159
+ }
127
160
  }
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 };
161
+ };
162
+ const coarseSync = constellation(SYNC_RADIUS_MIN, SYNC_RADIUS_MAX);
163
+ const fineSync = constellation(FINE_SYNC_RADIUS_MIN, FINE_SYNC_RADIUS_MAX);
164
+ addPeaks(coarse, coarseSync, COARSE_SYNC);
165
+ addPeaks(fine, fineSync, FINE_SYNC);
166
+ const sync = [...coarseSync, ...fineSync];
167
+ unit(coarse);
168
+ unit(fine);
169
+ const tile = new Float32Array(TILE * TILE);
170
+ for (let i = 0; i < tile.length; i++)
171
+ tile[i] = coarse[i] + fine[i];
172
+ return { tile, coarse, fine, sync, spectra: new Map(), id };
136
173
  }
137
174
  /** conj(FFT) of the key tile sampled on an `n`×`n` fold grid, limited to frequencies up to `maxRadius`. */
138
175
  function keySpectrum(key, n) {
@@ -204,11 +241,183 @@ function boxBlur(src, width, height, radius) {
204
241
  }
205
242
  return out;
206
243
  }
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;
244
+ /**
245
+ * How strong each part of the mark is at each place (grey levels, standard
246
+ * deviation), from what the picture itself hides there.
247
+ *
248
+ * The coarse part stays a fraction of a grey level everywhere and is written
249
+ * by dithering: what lands in the file is single-level grain, never a visible
250
+ * blotch or step on flat colour. The fine part is written only where the
251
+ * picture has fine detail of its own, `FINE_SLOPE` grey levels of mark per
252
+ * grey level of detail: noise two fifths as strong as the texture it sits in
253
+ * raises that texture's contrast by about 8 %, under what the eye tells apart.
254
+ * A line or an edge is not texture: the detail is taken as the lowest of its
255
+ * neighbourhood, so flat ground beside a line, and the inside of a drawn
256
+ * shape, stay flat.
257
+ */
258
+ const COARSE_FLOOR = 0.44;
259
+ const COARSE_SLOPE = 0.05;
260
+ const COARSE_CEIL = 0.8;
261
+ const FINE_SLOPE = 0.4;
262
+ const FINE_CEIL = 4;
263
+ /** Detail under this (grey levels) is sensor grain or compression residue, not texture. */
264
+ const DETAIL_FREE = 0.8;
265
+ /**
266
+ * On the stroke of a line or an edge itself (never beside it): a share of how far the pixels
267
+ * there differ from their surroundings, counted above `EDGE_FREE` grey levels and up to
268
+ * `EDGE_CEIL`. The coarse part gets `EDGE_COARSE` of it.
269
+ */
270
+ const EDGE_SHARE = 0.12;
271
+ const EDGE_FREE = 6;
272
+ const EDGE_CEIL = 3;
273
+ const EDGE_COARSE = 0.8;
274
+ /** Lowest value within `radius` cells, separable. */
275
+ function minFilter(src, width, height, radius) {
276
+ const tmp = new Float32Array(src.length);
277
+ const out = new Float32Array(src.length);
278
+ for (let y = 0; y < height; y++) {
279
+ const row = y * width;
280
+ for (let x = 0; x < width; x++) {
281
+ let low = Infinity;
282
+ const to = Math.min(width - 1, x + radius);
283
+ for (let k = Math.max(0, x - radius); k <= to; k++)
284
+ if (src[row + k] < low)
285
+ low = src[row + k];
286
+ tmp[row + x] = low;
287
+ }
288
+ }
289
+ for (let y = 0; y < height; y++) {
290
+ const from = Math.max(0, y - radius);
291
+ const to = Math.min(height - 1, y + radius);
292
+ for (let x = 0; x < width; x++) {
293
+ let low = Infinity;
294
+ for (let k = from; k <= to; k++)
295
+ if (tmp[k * width + x] < low)
296
+ low = tmp[k * width + x];
297
+ out[y * width + x] = low;
298
+ }
299
+ }
300
+ return out;
301
+ }
302
+ /** 3×3 mean, separable; at the border, of the cells that exist. */
303
+ function blur3(src, width, height) {
304
+ const tmp = new Float32Array(src.length);
305
+ const out = new Float32Array(src.length);
306
+ const third = 1 / 3;
307
+ for (let y = 0; y < height; y++) {
308
+ const row = y * width;
309
+ if (width === 1) {
310
+ tmp[row] = src[row];
311
+ continue;
312
+ }
313
+ tmp[row] = (src[row] + src[row + 1]) * 0.5;
314
+ for (let i = row + 1, end = row + width - 1; i < end; i++)
315
+ tmp[i] = (src[i - 1] + src[i] + src[i + 1]) * third;
316
+ tmp[row + width - 1] = (src[row + width - 2] + src[row + width - 1]) * 0.5;
317
+ }
318
+ if (height === 1)
319
+ return tmp;
320
+ for (let x = 0; x < width; x++) {
321
+ out[x] = (tmp[x] + tmp[width + x]) * 0.5;
322
+ const last = (height - 1) * width + x;
323
+ out[last] = (tmp[last - width] + tmp[last]) * 0.5;
324
+ }
325
+ for (let y = 1; y < height - 1; y++) {
326
+ for (let i = y * width, end = i + width; i < end; i++)
327
+ out[i] = (tmp[i - width] + tmp[i] + tmp[i + width]) * third;
328
+ }
329
+ return out;
330
+ }
331
+ /**
332
+ * The two amplitude maps on a grid of cells, `factor` pixels a side (the maps
333
+ * are smooth, or follow a stroke cell by cell; every pixel takes its cell's
334
+ * value). `strength` is folded in.
335
+ */
336
+ function amplitudeMap(image, factor, strength) {
337
+ const { data, width, height } = image;
338
+ const mw = Math.ceil(width / factor);
339
+ const mh = Math.ceil(height / factor);
340
+ const mean = new Float32Array(mw * mh);
341
+ // Detail finer than a cell: mean absolute deviation inside it.
342
+ const fine = new Float32Array(mw * mh);
343
+ const fullW = Math.floor(width / factor);
344
+ const fullH = Math.floor(height / factor);
345
+ if (factor === 2) {
346
+ // The usual case (pictures of about a megapixel), unrolled.
347
+ const down = 4 * width;
348
+ for (let my = 0; my < fullH; my++) {
349
+ let p = 8 * my * width;
350
+ for (let i = my * mw, end = i + fullW; i < end; i++, p += 8) {
351
+ const a = 0.299 * data[p] + 0.587 * data[p + 1] + 0.114 * data[p + 2];
352
+ const b = 0.299 * data[p + 4] + 0.587 * data[p + 5] + 0.114 * data[p + 6];
353
+ const c = 0.299 * data[p + down] + 0.587 * data[p + down + 1] + 0.114 * data[p + down + 2];
354
+ const d = 0.299 * data[p + down + 4] + 0.587 * data[p + down + 5] + 0.114 * data[p + down + 6];
355
+ const m = (a + b + c + d) * 0.25;
356
+ mean[i] = m;
357
+ fine[i] = (Math.abs(a - m) + Math.abs(b - m) + Math.abs(c - m) + Math.abs(d - m)) * 0.25;
358
+ }
359
+ }
360
+ }
361
+ const cell = new Float32Array(factor * factor);
362
+ for (let my = 0; my < mh; my++) {
363
+ const yEnd = Math.min(height, (my + 1) * factor);
364
+ // After the unrolled pass only the cells cut by the right and bottom border are left.
365
+ for (let mx = factor === 2 && my < fullH ? fullW : 0; mx < mw; mx++) {
366
+ const xEnd = Math.min(width, (mx + 1) * factor);
367
+ let sum = 0;
368
+ let n = 0;
369
+ for (let y = my * factor; y < yEnd; y++) {
370
+ let p = 4 * (y * width + mx * factor);
371
+ for (let x = mx * factor; x < xEnd; x++, p += 4) {
372
+ const v = 0.299 * data[p] + 0.587 * data[p + 1] + 0.114 * data[p + 2];
373
+ cell[n++] = v;
374
+ sum += v;
375
+ }
376
+ }
377
+ const m = sum / n;
378
+ let deviation = 0;
379
+ for (let k = 0; k < n; k++)
380
+ deviation += Math.abs(cell[k] - m);
381
+ mean[my * mw + mx] = m;
382
+ fine[my * mw + mx] = deviation / n;
383
+ }
384
+ }
385
+ // Detail of the two finest octaves only: what has the grain of the fine part and can hide it.
386
+ const smooth = blur3(mean, mw, mh);
387
+ for (let i = 0; i < fine.length; i++)
388
+ fine[i] = fine[i] + Math.abs(mean[i] - smooth[i]);
389
+ // Texture is judged on a grid twice as coarse again. A line answers within two cells of
390
+ // itself; the lowest value within four cells is then that of the flat ground beside it.
391
+ // Texture has no flat ground that near, and keeps its value.
392
+ const pw = Math.ceil(mw / 2);
393
+ const ph = Math.ceil(mh / 2);
394
+ const pooled = new Float32Array(pw * ph);
395
+ for (let py = 0; py < ph; py++) {
396
+ const rowA = 2 * py * mw;
397
+ const rowB = Math.min(mh - 1, 2 * py + 1) * mw;
398
+ for (let px = 0; px < pw; px++) {
399
+ const xa = 2 * px;
400
+ const xb = Math.min(mw - 1, xa + 1);
401
+ pooled[py * pw + px] = (fine[rowA + xa] + fine[rowA + xb] + fine[rowB + xa] + fine[rowB + xb]) * 0.25;
402
+ }
403
+ }
404
+ const hidden = blur3(minFilter(pooled, pw, ph, 2), pw, ph);
405
+ const coarse = new Float32Array(mw * mh);
406
+ for (let my = 0; my < mh; my++) {
407
+ const from = (my >> 1) * pw;
408
+ for (let mx = 0, i = my * mw; mx < mw; mx++, i++) {
409
+ const detail = hidden[from + (mx >> 1)] - DETAIL_FREE;
410
+ const texture = detail > 0 ? detail : 0;
411
+ // A change far smaller than the step it sits on does not show, and it is what a flat drawing
412
+ // keeps of the mark after lossy compression and reduction.
413
+ const stroke = fine[i] - EDGE_FREE;
414
+ const onEdge = stroke > 0 ? Math.min(EDGE_CEIL, EDGE_SHARE * stroke) : 0;
415
+ coarse[i] = strength * Math.max(Math.min(COARSE_CEIL, COARSE_FLOOR + COARSE_SLOPE * texture), EDGE_COARSE * onEdge);
416
+ fine[i] = strength * Math.min(FINE_CEIL, Math.max(FINE_SLOPE * texture, onEdge));
417
+ }
418
+ }
419
+ return { coarse, fine, width: mw, height: mh };
420
+ }
212
421
  /**
213
422
  * Adds the mark to `image` in place. Fully transparent pixels are left alone.
214
423
  * Returns the PSNR of the change over the touched pixels.
@@ -216,56 +425,64 @@ const ACTIVITY_FULL = 9;
216
425
  export function embedPixelMark(image, key, options = {}) {
217
426
  const { data, width, height } = image;
218
427
  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);
428
+ const factor = Math.max(1, Math.round(short / 512));
429
+ const amplitude = amplitudeMap(image, factor, options.strength ?? 1);
430
+ const coarseAmp = amplitude.coarse;
431
+ const fineAmp = amplitude.fine;
227
432
  // Tile phase per column / row: the period is short / TILES_PER_SHORT_SIDE pixels.
228
433
  const cellsPerPixel = (TILES_PER_SHORT_SIDE * TILE) / short;
229
434
  const x0 = new Int32Array(width);
230
435
  const xw = new Float32Array(width);
436
+ // The amplitude cell of each column.
437
+ const cellOf = new Int32Array(width);
231
438
  for (let x = 0; x < width; x++) {
232
439
  const pos = (x * cellsPerPixel) % TILE;
233
440
  x0[x] = Math.floor(pos);
234
441
  xw[x] = pos - x0[x];
442
+ cellOf[x] = Math.floor(x / factor);
235
443
  }
444
+ const coarseRow = new Float32Array(TILE + 1);
445
+ const fineRow = new Float32Array(TILE + 1);
236
446
  let squared = 0;
237
447
  let touched = 0;
448
+ // The dither: one draw per pixel, the same for every run on the same picture.
449
+ let seed = (width * 73856093) ^ (height * 19349663);
238
450
  for (let py = 0; py < height; py++) {
239
451
  const pos = (py * cellsPerPixel) % TILE;
240
452
  const y0 = Math.floor(pos);
241
453
  const wy = pos - y0;
242
454
  const rowA = y0 * TILE;
243
455
  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;
456
+ for (let c = 0; c < TILE; c++) {
457
+ coarseRow[c] = key.coarse[rowA + c] * (1 - wy) + key.coarse[rowB + c] * wy;
458
+ fineRow[c] = key.fine[rowA + c] * (1 - wy) + key.fine[rowB + c] * wy;
459
+ }
460
+ coarseRow[TILE] = coarseRow[0];
461
+ fineRow[TILE] = fineRow[0];
462
+ const cells = Math.floor(py / factor) * amplitude.width;
463
+ let p = 4 * py * width;
464
+ for (let px = 0; px < width; px++, p += 4) {
465
+ seed = (Math.imul(seed, 1664525) + 1013904223) | 0;
247
466
  if (data[p + 3] === 0)
248
467
  continue;
468
+ touched++;
249
469
  const cx = x0[px];
250
- const cx1 = (cx + 1) % TILE;
251
470
  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++;
471
+ const at = cells + cellOf[px];
472
+ const change = coarseAmp[at] * (coarseRow[cx] + (coarseRow[cx + 1] - coarseRow[cx]) * wx) +
473
+ fineAmp[at] * (fineRow[cx] + (fineRow[cx + 1] - fineRow[cx]) * wx);
474
+ // Dithered rounding: the mean change is the wanted one even where that is a fraction of a level.
475
+ const delta = Math.floor(change + (seed >>> 8) / 16777216);
476
+ if (delta === 0)
259
477
  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++;
478
+ const r = data[p] + delta;
479
+ const g = data[p + 1] + delta;
480
+ const b = data[p + 2] + delta;
481
+ const before = data[p + 1];
482
+ data[p] = r < 0 ? 0 : r > 255 ? 255 : r;
483
+ data[p + 1] = g < 0 ? 0 : g > 255 ? 255 : g;
484
+ data[p + 2] = b < 0 ? 0 : b > 255 ? 255 : b;
485
+ squared += (data[p + 1] - before) ** 2;
269
486
  }
270
487
  }
271
488
  const mse = touched ? squared / touched : 0;
@@ -298,8 +515,8 @@ export function pixelMarkPlane(width, height, key, tilesPerShortSide = TILES_PER
298
515
  const cx = x0[px];
299
516
  const cx1 = (cx + 1) % TILE;
300
517
  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;
518
+ const top = key.coarse[rowA + cx] * (1 - wx) + key.coarse[rowA + cx1] * wx;
519
+ const bottom = key.coarse[rowB + cx] * (1 - wx) + key.coarse[rowB + cx1] * wx;
303
520
  plane[py * width + px] = top * (1 - wy) + bottom * wy;
304
521
  }
305
522
  }
@@ -310,14 +527,17 @@ export function pixelMarkPlane(width, height, key, tilesPerShortSide = TILES_PER
310
527
  * test looks at 9 shifts of a handful of hypotheses; the search looks at every
311
528
  * shift of the grids the synchronisation peaks propose, so its cut is higher.
312
529
  *
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).
530
+ * Measured (docs/MEASURED.md) on unmarked pictures, as they are and inside a
531
+ * page. Search: 2,174 scores, no detection, highest 6.33, 99 % under 5.91; an
532
+ * exponential fit to the top tenth puts the chance of passing 7.5 at about 2 in
533
+ * a million per picture and key. Aligned test alone: 1,610 scores, highest 4.68;
534
+ * the same fit gives about 5 in ten million for 6.5. Both are extrapolations,
535
+ * not counts.
318
536
  */
319
537
  export const ALIGNED_CUT = 6.5;
320
538
  export const SEARCH_CUT = 7.5;
539
+ /** Shorter sides (pixels) pictures are generated in; used when a copy is an unscaled piece of one. */
540
+ const USUAL_SHORT_SIDES = [512, 720, 768, 832, 864, 896, 1024, 1080, 1152, 1280, 1344, 1536, 2048];
321
541
  /** Aspect ratios pictures are generated in; used when a copy was stretched. */
322
542
  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
543
  /** Luminance, reduced by an integer factor, high-passed and normalised by local contrast. */
@@ -365,7 +585,7 @@ function whiten(image, maxShort) {
365
585
  * noise from rings that hold no mark any more, so each fold is scored per
366
586
  * band and the best band counts.
367
587
  */
368
- const NESTED_BANDS = [7, 11, 17, BAND_HI + 2];
588
+ const NESTED_BANDS = [7, 11, 17, BAND_SPLIT + 2, BAND_HI + 2];
369
589
  const bandPlans = new WeakMap();
370
590
  function bandPlan(key, n) {
371
591
  let plans = bandPlans.get(key);
@@ -391,14 +611,42 @@ function bandPlan(key, n) {
391
611
  }
392
612
  bins.sort((p, q) => p.r - q.r);
393
613
  const edges = NESTED_BANDS.filter((edge, at) => edge < n / 2 || at === 0 || NESTED_BANDS[at - 1] < n / 2 - 1);
614
+ const fineFrom = bins.findIndex((b) => b.r > BAND_SPLIT + 2);
615
+ const steps = (shift) => ({
616
+ cx: Float32Array.from(bins, (b) => Math.cos((2 * Math.PI * b.fu * shift) / n)),
617
+ sx: Float32Array.from(bins, (b) => Math.sin((2 * Math.PI * b.fu * shift) / n)),
618
+ cy: Float32Array.from(bins, (b) => Math.cos((2 * Math.PI * b.fv * shift) / n)),
619
+ sy: Float32Array.from(bins, (b) => Math.sin((2 * Math.PI * b.fv * shift) / n)),
620
+ });
394
621
  const plan = {
622
+ quarter: steps(0.25),
623
+ half: steps(0.5),
624
+ ranges: [],
395
625
  index: Int32Array.from(bins, (b) => b.i),
396
626
  fu: Int16Array.from(bins, (b) => b.fu),
397
627
  fv: Int16Array.from(bins, (b) => b.fv),
398
628
  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]),
629
+ keyRe: new Float64Array(bins.length),
630
+ keyIm: new Float64Array(bins.length),
401
631
  };
632
+ // A fold bin gathers the pixels of one cell, so what it holds sits half a cell further on than
633
+ // the tile sample of that cell. Half a cell is a sixth of a wave at the fine end of the band:
634
+ // the reference is moved to meet it.
635
+ bins.forEach((b, k) => {
636
+ const angle = (-Math.PI * (b.fu + b.fv)) / TILE;
637
+ const re = spectrum[2 * b.i];
638
+ const im = spectrum[2 * b.i + 1];
639
+ plan.keyRe[k] = re * Math.cos(angle) - im * Math.sin(angle);
640
+ plan.keyIm[k] = re * Math.sin(angle) + im * Math.cos(angle);
641
+ });
642
+ // The narrow nested bands are for reduced copies, which fold on a smaller grid; on the full
643
+ // grid the coarse part, everything, and the fine part alone are read.
644
+ plan.ranges = plan.ends.map((end) => [0, end]);
645
+ if (n === 128 && plan.ends.length > 2)
646
+ plan.ranges = plan.ranges.slice(-2);
647
+ // In a textured picture the coarse rings hold almost no mark; read with them, the fine part drowns.
648
+ if (fineFrom > 0 && bins.length - fineFrom > 200)
649
+ plan.ranges.push([fineFrom, bins.length]);
402
650
  plans.set(n, plan);
403
651
  return plan;
404
652
  }
@@ -472,6 +720,10 @@ function foldScratch(width) {
472
720
  im: new Float64Array(cells),
473
721
  re2: new Float64Array(cells),
474
722
  im2: new Float64Array(cells),
723
+ sums: new Float64Array(cells + 1),
724
+ energies: new Float64Array(cells + 1),
725
+ polishRe: new Float64Array(cells),
726
+ polishIm: new Float64Array(cells),
475
727
  colBin: new Int32Array(width),
476
728
  };
477
729
  }
@@ -487,21 +739,25 @@ function scoreNearZero(plan, scratch, n) {
487
739
  let bestShift = [0, 0];
488
740
  for (let dy = -1; dy <= 1; dy++) {
489
741
  for (let dx = -1; dx <= 1; dx++) {
742
+ // Running sums over the bins in order; a range is a difference of two of them.
743
+ const sums = scratch.sums;
744
+ const energies = scratch.energies;
490
745
  let sum = 0;
491
746
  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];
747
+ sums[0] = energies[0] = 0;
748
+ for (let k = 0; k < plan.index.length; k++) {
749
+ if (dx === 0 && dy === 0)
750
+ sum += re[k];
751
+ else {
752
+ const angle = (2 * Math.PI * (plan.fu[k] * dx + plan.fv[k] * dy)) / n;
753
+ sum += re[k] * Math.cos(angle) - im[k] * Math.sin(angle);
502
754
  }
503
- from = end;
504
- const score = sum / Math.sqrt(energy + 1e-30);
755
+ energy += re[k] * re[k] + im[k] * im[k];
756
+ sums[k + 1] = sum;
757
+ energies[k + 1] = energy;
758
+ }
759
+ for (const [from, to] of plan.ranges) {
760
+ const score = (sums[to] - sums[from]) / Math.sqrt(energies[to] - energies[from] + 1e-30);
505
761
  if (score > best) {
506
762
  best = score;
507
763
  bestShift = [dx, dy];
@@ -533,11 +789,12 @@ function scoreAllShifts(plan, scratch, n, bands, halfTurn) {
533
789
  }
534
790
  let bestScore = -Infinity;
535
791
  let bestShift = [0, 0];
536
- const ends = plan.ends.slice(0, bands);
537
- for (const end of ends) {
792
+ let bestRange = [0, 0];
793
+ const ranges = bands >= plan.ends.length ? plan.ranges : plan.ranges.slice(0, bands);
794
+ for (const [from, end] of ranges) {
538
795
  surface.fill(0, 0, 2 * n * n);
539
796
  let energy = 0;
540
- for (let k = 0; k < end; k++) {
797
+ for (let k = from; k < end; k++) {
541
798
  surface[2 * plan.index[k]] = re[k];
542
799
  surface[2 * plan.index[k] + 1] = im[k];
543
800
  energy += re[k] * re[k] + im[k] * im[k];
@@ -557,6 +814,52 @@ function scoreAllShifts(plan, scratch, n, bands, halfTurn) {
557
814
  if (score > bestScore) {
558
815
  bestScore = score;
559
816
  bestShift = [at % n, Math.floor(at / n)];
817
+ bestRange = [from, end];
818
+ }
819
+ }
820
+ // The surface is known at whole bins; the true offset falls between them, and half a bin is a
821
+ // sixth of a wave at the fine end of the band. Around a peak that could still reach the cut,
822
+ // the correlation is summed directly at quarter-bin steps.
823
+ if (bestScore < POLISH_FROM)
824
+ return { score: bestScore, shift: bestShift };
825
+ const [from, end] = bestRange;
826
+ const [sx, sy] = bestShift;
827
+ // The spectrum turned to the peak's own shift, once.
828
+ const pr = scratch.polishRe;
829
+ const pi = scratch.polishIm;
830
+ let energy = 0;
831
+ for (let k = from; k < end; k++) {
832
+ const angle = (2 * Math.PI * (plan.fu[k] * sx + plan.fv[k] * sy)) / n;
833
+ const c = Math.cos(angle);
834
+ const s = Math.sin(angle);
835
+ pr[k] = re[k] * c - im[k] * s;
836
+ pi[k] = re[k] * s + im[k] * c;
837
+ energy += re[k] * re[k] + im[k] * im[k];
838
+ }
839
+ const norm = 1 / Math.sqrt(energy + 1e-30);
840
+ const tables = [plan.half, plan.quarter];
841
+ for (let iy = -2; iy <= 2; iy++) {
842
+ for (let ix = -2; ix <= 2; ix++) {
843
+ if (ix === 0 && iy === 0)
844
+ continue;
845
+ // cos and sin of the x and the y part of the extra shift; a negative shift flips the sine.
846
+ const tx = ix === 0 ? null : tables[Math.abs(ix) - 1 === 1 ? 0 : 1];
847
+ const ty = iy === 0 ? null : tables[Math.abs(iy) - 1 === 1 ? 0 : 1];
848
+ const signX = ix < 0 ? -1 : 1;
849
+ const signY = iy < 0 ? -1 : 1;
850
+ let sum = 0;
851
+ for (let k = from; k < end; k++) {
852
+ const cx = tx ? tx.cx[k] : 1;
853
+ const sxk = tx ? signX * tx.sx[k] : 0;
854
+ const cy = ty ? ty.cy[k] : 1;
855
+ const syk = ty ? signY * ty.sy[k] : 0;
856
+ // real part of (pr + i·pi) · e^{i(ax + ay)}
857
+ sum += pr[k] * (cx * cy - sxk * syk) - pi[k] * (sxk * cy + cx * syk);
858
+ }
859
+ if (sum * norm > bestScore) {
860
+ bestScore = sum * norm;
861
+ bestShift = [sx + ix * 0.25, sy + iy * 0.25];
862
+ }
560
863
  }
561
864
  }
562
865
  return { score: bestScore, shift: bestShift };
@@ -591,10 +894,43 @@ export function detectPixelMark(image, key, options = {}) {
591
894
  }
592
895
  if (options.alignedOnly)
593
896
  return { ...none, score: Math.max(0, aligned.score) };
897
+ // 1b. A piece cut out of a picture of a usual size and not scaled: the period is the picture's,
898
+ // only the offset is unknown. The fine part of the mark is read in full, which the next two
899
+ // steps (grids found to about a bin) cannot always do.
900
+ let cut = { score: -Infinity, period: 0 };
901
+ for (const short of USUAL_SHORT_SIDES) {
902
+ const period = short / TILES_PER_SHORT_SIDE / w.factor;
903
+ if (period < 96 || period > 2 * Math.max(w.width, w.height))
904
+ continue;
905
+ const plan = bandPlan(key, 128);
906
+ crossSpectrum(w, plan, [1 / period, 0], [0, 1 / period], 128, scratch);
907
+ const peak = scoreAllShifts(plan, scratch, 128, plan.ranges.length, false);
908
+ if (peak.score > cut.score)
909
+ cut = { score: peak.score, period: period * w.factor };
910
+ }
911
+ if (cut.score >= SEARCH_CUT) {
912
+ // A copy reduced to nearly one of those sizes passes here too, with its period a little
913
+ // off: look around for where the mark reads best.
914
+ const plan = bandPlan(key, 128);
915
+ const near = cut.period / w.factor;
916
+ for (let k = -8; k <= 8; k++) {
917
+ if (k === 0)
918
+ continue;
919
+ const period = near * (1 + 0.002 * k);
920
+ crossSpectrum(w, plan, [1 / period, 0], [0, 1 / period], 128, scratch);
921
+ const peak = scoreAllShifts(plan, scratch, 128, plan.ranges.length, false);
922
+ if (peak.score > cut.score)
923
+ cut = { score: peak.score, period: period * w.factor };
924
+ }
925
+ return { detected: true, score: cut.score, mode: "search", period: [cut.period, cut.period], rotation: 0, mirrored: false, keyId: key.id };
926
+ }
594
927
  // 2. Unknown geometry (crop, screen capture, rotation, mirror, stretch): the
595
928
  // synchronisation peaks give the tile grid, the fold along it gives the verdict.
596
929
  const coarse = whiten(image, 448);
597
- const found = searchByPeaks(coarse, key, scratch);
930
+ // The peaks are looked for in a reduced picture; the grid they give is then checked on one
931
+ // sharp enough to still hold the fine part of the mark.
932
+ const sharp = w.factor === 1 ? w : whiten(image, 1100);
933
+ const found = searchByPeaks(coarse, key, scratch, sharp.factor < coarse.factor ? sharp : coarse);
598
934
  if (found && found.score >= SEARCH_CUT) {
599
935
  return {
600
936
  detected: true,
@@ -606,42 +942,7 @@ export function detectPixelMark(image, key, options = {}) {
606
942
  keyId: key.id,
607
943
  };
608
944
  }
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) };
945
+ return { ...none, score: Math.max(0, aligned.score, cut.score, found?.score ?? 0) };
645
946
  }
646
947
  /** Fourier power of the whitened picture, zero-padded so a peak spans a few bins, flattened over radius. */
647
948
  function peakSpectrum(w) {
@@ -652,9 +953,22 @@ function peakSpectrum(w) {
652
953
  const offY = Math.max(0, Math.floor((w.height - n) / 2));
653
954
  const cw = Math.min(n, w.width);
654
955
  const ch = Math.min(n, w.height);
956
+ // Tapered edges (the outer 15 % of each side): without them the frame of the picture and every
957
+ // long line in a page smear across the spectrum and bury faint peaks; a full window would cost
958
+ // the peaks a third of their height.
959
+ const wx = new Float32Array(cw);
960
+ const wy = new Float32Array(ch);
961
+ const taper = (at, length) => {
962
+ const edge = Math.min(at + 0.5, length - at - 0.5) / (0.15 * length);
963
+ return edge >= 1 ? 1 : 0.5 - 0.5 * Math.cos(Math.PI * edge);
964
+ };
965
+ for (let x = 0; x < cw; x++)
966
+ wx[x] = taper(x, cw);
967
+ for (let y = 0; y < ch; y++)
968
+ wy[y] = taper(y, ch);
655
969
  for (let y = 0; y < ch; y++) {
656
970
  for (let x = 0; x < cw; x++)
657
- grid[2 * (y * n + x)] = w.values[(y + offY) * w.width + x + offX];
971
+ grid[2 * (y * n + x)] = w.values[(y + offY) * w.width + x + offX] * wx[x] * wy[y];
658
972
  }
659
973
  fft2d(grid, n);
660
974
  const power = new Float32Array(n * n);
@@ -729,8 +1043,25 @@ function peakSpectrum(w) {
729
1043
  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
1044
  }
731
1045
  }
732
- return { n, power, peaks };
1046
+ // What a point of the spectrum reads by chance: every 37th bin outside the lowest frequencies.
1047
+ let count = 0, sum = 0, sumSq = 0;
1048
+ for (let i = 0; i < n * n; i += 37) {
1049
+ const u = i & (n - 1);
1050
+ const v = i >> 10;
1051
+ const fu = u < half ? u : u - n;
1052
+ const fv = v < half ? v : v - n;
1053
+ if (fu * fu + fv * fv < 64)
1054
+ continue;
1055
+ const value = peaks[i] > PEAK_CAP ? PEAK_CAP : peaks[i];
1056
+ sum += value;
1057
+ sumSq += value * value;
1058
+ count++;
1059
+ }
1060
+ const peakMean = sum / count;
1061
+ return { n, power, peaks, peakMean, peakSpread: Math.sqrt(Math.max(1e-6, sumSq / count - peakMean * peakMean)) };
733
1062
  }
1063
+ /** How many turned grids the search hands on to be checked by folding. */
1064
+ const SQUARE_GRIDS_KEPT = 12;
734
1065
  /** A peak far above its ring counts no more than this: one line of the picture must not outvote the constellation. */
735
1066
  const PEAK_CAP = 24;
736
1067
  function keepBest(list, candidate, limit) {
@@ -749,22 +1080,46 @@ function keepBest(list, candidate, limit) {
749
1080
  if (list.length > limit)
750
1081
  list.length = limit;
751
1082
  }
752
- /** Sum of the capped peak heights where the constellation falls for the tile axes (fu, fv). */
1083
+ /**
1084
+ * How far a constellation stands out, from the sums of capped peak heights of its two halves
1085
+ * (`inside` points of each fell inside the spectrum): each half alone and both together are
1086
+ * put on one scale (standard deviations above what chance gives for that many points), and
1087
+ * the best counts. A reduced copy has lost the fine half, a picture of texture all over shows
1088
+ * little of the coarse half; neither should drag the other down. Returned as an equivalent sum
1089
+ * of eight peaks, so that the numbers stay comparable.
1090
+ */
1091
+ function standOut(spectrum, coarseSum, coarseInside, fineSum, fineInside) {
1092
+ const { peakMean } = spectrum;
1093
+ let best = -Infinity;
1094
+ if (coarseInside >= SYNC_PEAKS - 2)
1095
+ best = (coarseSum - coarseInside * peakMean) / Math.sqrt(coarseInside);
1096
+ if (fineInside >= SYNC_PEAKS - 2) {
1097
+ best = Math.max(best, (fineSum - fineInside * peakMean) / Math.sqrt(fineInside));
1098
+ if (coarseInside >= SYNC_PEAKS - 2)
1099
+ best = Math.max(best, (coarseSum + fineSum - (coarseInside + fineInside) * peakMean) / Math.sqrt(coarseInside + fineInside));
1100
+ }
1101
+ if (best === -Infinity)
1102
+ return 0;
1103
+ return Math.max(0.001, SYNC_PEAKS * peakMean + best * Math.sqrt(SYNC_PEAKS));
1104
+ }
1105
+ /** How far the constellation stands out for the tile axes (fu, fv); see {@link standOut}. */
753
1106
  function constellationScore(spectrum, sync, fu, fv) {
754
1107
  const { n, peaks } = spectrum;
755
1108
  const half = n / 2;
756
- let score = 0;
757
- let inside = 0;
758
- for (const [u, v] of sync) {
1109
+ const sums = [0, 0];
1110
+ const inside = [0, 0];
1111
+ for (let i = 0; i < sync.length; i++) {
1112
+ const [u, v] = sync[i];
759
1113
  const kx = Math.round(n * (u * fu[0] + v * fv[0]));
760
1114
  const ky = Math.round(n * (u * fu[1] + v * fv[1]));
761
1115
  if (kx >= half - 1 || kx <= 1 - half || ky >= half - 1 || ky <= 1 - half || kx * kx + ky * ky < 64)
762
1116
  continue;
763
1117
  const value = peaks[((ky + n) % n) * n + ((kx + n) % n)];
764
- score += value > PEAK_CAP ? PEAK_CAP : value;
765
- inside++;
1118
+ const part = i < SYNC_PEAKS ? 0 : 1;
1119
+ sums[part] += value > PEAK_CAP ? PEAK_CAP : value;
1120
+ inside[part]++;
766
1121
  }
767
- return inside >= SYNC_PEAKS - 2 ? score * (SYNC_PEAKS / inside) : 0;
1122
+ return standOut(spectrum, sums[0], inside[0], sums[1], inside[1]);
768
1123
  }
769
1124
  /**
770
1125
  * Every turned, scaled and mirrored square grid: the constellation's points are
@@ -789,25 +1144,52 @@ function searchSquareGrids(spectrum, key, minPeriod, maxPeriod) {
789
1144
  }
790
1145
  for (let period = minPeriod; period <= maxPeriod; period *= 1.01) {
791
1146
  const inverse = 1 / period;
792
- let score = 0;
793
- let inside = 0;
1147
+ let coarseSum = 0, fineSum = 0, coarseInside = 0, fineInside = 0;
794
1148
  for (let i = 0; i < count; i++) {
795
1149
  const kx = Math.round(cos[i] * inverse);
796
1150
  const ky = Math.round(sin[i] * inverse);
797
1151
  if (kx >= half - 1 || kx <= 1 - half || ky >= half - 1 || ky <= 1 - half || kx * kx + ky * ky < 64)
798
1152
  continue;
799
1153
  const value = peaks[((ky + n) & (n - 1)) * n + ((kx + n) & (n - 1))];
800
- score += value > PEAK_CAP ? PEAK_CAP : value;
801
- inside++;
1154
+ const capped = value > PEAK_CAP ? PEAK_CAP : value;
1155
+ if (i < SYNC_PEAKS) {
1156
+ coarseSum += capped;
1157
+ coarseInside++;
1158
+ }
1159
+ else {
1160
+ fineSum += capped;
1161
+ fineInside++;
1162
+ }
802
1163
  }
803
- if (inside < count - 2)
1164
+ const score = standOut(spectrum, coarseSum, coarseInside, fineSum, fineInside);
1165
+ if (score <= 0)
804
1166
  continue;
805
- score *= count / inside;
806
- if (best.length >= 8 && score <= best[best.length - 1].score)
1167
+ if (best.length >= SQUARE_GRIDS_KEPT && score <= best[best.length - 1].score)
807
1168
  continue;
808
1169
  const c = Math.cos(angle) * inverse;
809
1170
  const s = Math.sin(angle) * inverse;
810
- keepBest(best, { score, fu: [c, s], fv: [-s * mirror, c * mirror] }, 8);
1171
+ keepBest(best, { score, fu: [c, s], fv: [-s * mirror, c * mirror] }, SQUARE_GRIDS_KEPT);
1172
+ }
1173
+ }
1174
+ }
1175
+ return best;
1176
+ }
1177
+ /**
1178
+ * Upright grids only (also turned by a quarter and mirrored): what a screen capture, a
1179
+ * reduced copy and a crop hold. One unknown, the period, instead of period and angle, so far
1180
+ * fewer chance fits and a fainter constellation still stands out.
1181
+ */
1182
+ function searchUprightGrids(spectrum, key, minPeriod, maxPeriod) {
1183
+ const best = [];
1184
+ for (const [ux, uy] of [[1, 0], [0, 1]]) {
1185
+ for (const mirror of [1, -1]) {
1186
+ for (let period = minPeriod; period <= maxPeriod; period *= 1.003) {
1187
+ const f = 1 / period;
1188
+ const fu = [ux * f, uy * f];
1189
+ const fv = [-uy * f * mirror, ux * f * mirror];
1190
+ const score = constellationScore(spectrum, key.sync, fu, fv);
1191
+ if (score > 0)
1192
+ keepBest(best, { score, fu, fv }, 4);
811
1193
  }
812
1194
  }
813
1195
  }
@@ -845,7 +1227,7 @@ function searchAnyGrids(spectrum, key, minPeriod, maxPeriod) {
845
1227
  }
846
1228
  }
847
1229
  found.sort((p, q) => q.value - p.value);
848
- const strong = found.slice(0, 64);
1230
+ const strong = found.slice(0, 48);
849
1231
  const best = [];
850
1232
  const minF = 1 / maxPeriod;
851
1233
  const maxF = 1 / minPeriod;
@@ -858,7 +1240,9 @@ function searchAnyGrids(spectrum, key, minPeriod, maxPeriod) {
858
1240
  const bx = strong[b].x * sign, by = strong[b].y * sign;
859
1241
  for (let i = 0; i < key.sync.length; i++) {
860
1242
  const [u1, v1] = key.sync[i];
861
- for (let j = 0; j < key.sync.length; j++) {
1243
+ // Both points from the same half: the coarse peaks, or the fine ones.
1244
+ const half0 = i < SYNC_PEAKS ? 0 : SYNC_PEAKS;
1245
+ for (let j = half0; j < half0 + SYNC_PEAKS; j++) {
862
1246
  if (i === j)
863
1247
  continue;
864
1248
  const [u2, v2] = key.sync[j];
@@ -965,8 +1349,38 @@ function verifyGrid(w, key, scratch, grid) {
965
1349
  mirrored: grid.fu[0] * grid.fv[1] - grid.fu[1] * grid.fv[0] < 0,
966
1350
  };
967
1351
  }
968
- function searchByPeaks(w, key, scratch) {
969
- if (key.sync.length < SYNC_PEAKS - 1)
1352
+ /** A grid is worth refining from this score: above what most unmarked pictures reach on any grid. */
1353
+ const REFINE_FROM = 5.6;
1354
+ /** A peak is worth polishing between the bins from this score (polishing adds at most about a half to it). */
1355
+ const POLISH_FROM = 4.6;
1356
+ function refineGrid(w, key, scratch, start, first) {
1357
+ let best = first;
1358
+ let grid = start;
1359
+ for (const [scaleStep, angleStep] of [[0.003, 0.0025], [0.001, 0.0008]]) {
1360
+ let improved = true;
1361
+ for (let round = 0; round < 3 && improved; round++) {
1362
+ improved = false;
1363
+ for (const [ds, da] of [[scaleStep, 0], [-scaleStep, 0], [0, angleStep], [0, -angleStep]]) {
1364
+ const c = Math.cos(da) * (1 + ds);
1365
+ const s = Math.sin(da) * (1 + ds);
1366
+ const trial = {
1367
+ score: grid.score,
1368
+ fu: [grid.fu[0] * c - grid.fu[1] * s, grid.fu[0] * s + grid.fu[1] * c],
1369
+ fv: [grid.fv[0] * c - grid.fv[1] * s, grid.fv[0] * s + grid.fv[1] * c],
1370
+ };
1371
+ const result = verifyGrid(w, key, scratch, trial);
1372
+ if (result.score > best.score) {
1373
+ best = result;
1374
+ grid = trial;
1375
+ improved = true;
1376
+ }
1377
+ }
1378
+ }
1379
+ }
1380
+ return best;
1381
+ }
1382
+ function searchByPeaks(w, key, scratch, sharp = w) {
1383
+ if (key.sync.length < 2 * SYNC_PEAKS - 2)
970
1384
  return null;
971
1385
  const spectrum = peakSpectrum(w);
972
1386
  const maxPeriod = Math.max(w.width, w.height) * 1.5;
@@ -976,7 +1390,16 @@ function searchByPeaks(w, key, scratch) {
976
1390
  for (const candidate of candidates) {
977
1391
  const fitted = fitGrid(spectrum, key.sync, candidate);
978
1392
  for (const grid of fitted ? [fitted] : [candidate]) {
979
- const result = verifyGrid(w, key, scratch, grid);
1393
+ // Cycles per pixel of the reduced picture, in pixels of the sharp one.
1394
+ const ratio = sharp.factor / w.factor;
1395
+ const onSharp = { score: grid.score, fu: [grid.fu[0] * ratio, grid.fu[1] * ratio], fv: [grid.fv[0] * ratio, grid.fv[1] * ratio] };
1396
+ let result = verifyGrid(sharp, key, scratch, onSharp);
1397
+ // The peaks give the grid to about a bin of the spectrum; the fine part of the mark only
1398
+ // adds up when the grid is right to a fraction of a percent. A grid that already shows the
1399
+ // mark faintly is nudged in scale and angle to where it shows best.
1400
+ if (result.score >= REFINE_FROM)
1401
+ result = refineGrid(sharp, key, scratch, onSharp, result);
1402
+ result.period = [result.period[0] * ratio, result.period[1] * ratio];
980
1403
  result.sync = constellationScore(spectrum, key.sync, grid.fu, grid.fv);
981
1404
  if (!best || result.score > best.score)
982
1405
  best = result;
@@ -986,7 +1409,9 @@ function searchByPeaks(w, key, scratch) {
986
1409
  }
987
1410
  return false;
988
1411
  };
989
- if (consider(searchSquareGrids(spectrum, key, minPeriod, maxPeriod).slice(0, 5)))
1412
+ if (consider(searchUprightGrids(spectrum, key, minPeriod, maxPeriod)))
1413
+ return best;
1414
+ if (consider(searchSquareGrids(spectrum, key, minPeriod, maxPeriod)))
990
1415
  return best;
991
1416
  consider(searchAnyGrids(spectrum, key, minPeriod, maxPeriod).slice(0, 4));
992
1417
  return best;