Ring code: far and washed-out projector reading

This commit is contained in:
2026-11-16 20:43:31 +01:00
10 changed files with 1620 additions and 169 deletions
+2 -1
View File
@@ -75,7 +75,8 @@ Par défaut, le projecteur affiche un code circulaire : un disque sombre avec le
- La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée. Un segment qui change de couleur passe en fondu. - La longueur et l'opacité des segments varient en continu, dans des bornes qui ne touchent jamais la donnée. Un segment qui change de couleur passe en fondu.
- Les anneaux ne s'ouvrent pas avec l'appareil photo natif : un petit QR fixe, dans un coin de l'écran, mène à la page de vote. - Les anneaux ne s'ouvrent pas avec l'appareil photo natif : un petit QR fixe, dans un coin de l'écran, mène à la page de vote.
- Signature de 32 bits : un jeton ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire. - Signature de 32 bits : un jeton ne vaut que pendant environ 3 s et le serveur doit le recevoir en ligne. Même à 1 000 essais par seconde, la probabilité de deviner un jeton valide pendant sa durée de vie est d'environ 7 × 10⁻⁷, et il en faut 5 distincts pour s'inscrire.
- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code). `CPU=6` simule un téléphone lent. - De loin : le téléphone cherche le disque sur une copie réduite de l'image, puis lit un recadrage à la résolution du capteur. Le disque est repéré par rapport au blanc qui l'entoure, pas par un seuil global, ce qui tient avec un projecteur délavé dans une salle sombre. Repère pratique : rester à moins de 10 fois le diamètre du code (un code de 1 m se lit jusqu'à 10 m environ).
- Banc d'essai : `uv run python tools/ringbench.py` (Chrome sans interface, perspective, flou, contraste délavé, décor encombré, images sans code, code lointain sur projecteur délavé, séquences de 6 s). `CPU=6` simule un téléphone lent, `V1=1` rejoue l'ancien décodeur comme référence, `SUITE=far,seq` limite les séries.
## Sécurité : ce qui est garanti, ce qui ne l'est pas ## Sécurité : ce qui est garanti, ce qui ne l'est pas
+349 -125
View File
@@ -7,10 +7,10 @@ export const RING_SECTORS = [24, 28, 32, 36];
// code space units, centered on the origin. the solid dark center disc is what the phone looks for // code space units, centered on the origin. the solid dark center disc is what the phone looks for
export const CENTER = 0.62; export const CENTER = 0.62;
export const RADII = [0.9, 1.05, 1.2, 1.35]; export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.105; export const THICK = 0.12;
export const DISC = 1.5; // light background disc export const DISC = 1.5; // light background disc
// animation bounds: dash length and opacity breathe inside these, the data never depends on them // animation bounds: dash length and opacity breathe inside these, the data never depends on them
const LEN = [0.56, 0.86]; // part of the sector covered by the dash const LEN = [0.62, 0.88]; // part of the sector covered by the dash
// wide gap between the two classes so the camera tells them apart easily // wide gap between the two classes so the camera tells them apart easily
const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19]; const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19];
const NSYM = 6; const NSYM = 6;
@@ -54,11 +54,12 @@ export function rsEncode(msg) {
} }
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2) // port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
export function rsDecode(cw) { // the whole corrected codeword, or null
function rsFix(cw) {
const n = cw.length; const n = cw.length;
const synd = [0]; const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i))); for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM); if (Math.max(...synd) === 0) return cw;
let errLoc = [1], oldLoc = [1]; let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) { for (let i = 0; i < NSYM; i++) {
const K = i + 1; const K = i + 1;
@@ -100,7 +101,12 @@ export function rsDecode(cw) {
}); });
const fixed = cw.map((c, i) => c ^ E[i]); const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null; for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed.slice(0, n - NSYM); return fixed;
}
export function rsDecode(cw) {
const fixed = rsFix(cw);
return fixed && fixed.slice(0, cw.length - NSYM);
} }
export function whitening(n) { export function whitening(n) {
@@ -261,58 +267,51 @@ function solve(A, B) {
return B.map((b, i) => b / A[i][i]); return B.map((b, i) => b / A[i][i]);
} }
function otsu(vals) { // dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px
const hist = new Float64Array(256); function blobs(g, w, h, s, ratio, out) {
for (const v of vals) hist[Math.max(0, Math.min(255, v | 0))]++; // dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6,
let total = 0, sum = 0; // and the disc always has its light surround within reach, whatever the room does around the screen
for (let i = 0; i < 256; i++) { total += hist[i]; sum += i * hist[i]; } const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th);
let wb = 0, sb = 0, best = 0, thr = 128;
for (let i = 0; i < 256; i++) {
wb += hist[i];
if (!wb || wb === total) continue;
sb += i * hist[i];
const mb = sb / wb, mf = (sum - sb) / (total - wb), v = wb * (total - wb) * (mb - mf) ** 2;
if (v > best) { best = v; thr = i; }
}
return thr;
}
// candidate center discs: solid dark elliptic blobs. returns [{ cx, cy, A }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 480)));
const w = Math.floor(img.w / f), h = Math.floor(img.h / f), small = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0; const i = ((y / T) | 0) * tw + ((x / T) | 0), v = g[y * w + x];
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx]; if (v > tmax[i]) tmax[i] = v;
small[y * w + x] = s / (f * f);
} }
const thr = otsu(small); const dark = new Uint8Array(w * h);
const label = new Int32Array(w * h).fill(-1), cands = []; for (let ty = 0; ty < th; ty++) for (let tx = 0; tx < tw; tx++) {
const stack = []; let m = 0;
for (let dy = -1; dy <= 1; dy++) for (let dx = -1; dx <= 1; dx++) {
const yy = ty + dy, xx = tx + dx;
if (yy >= 0 && xx >= 0 && yy < th && xx < tw && tmax[yy * tw + xx] > m) m = tmax[yy * tw + xx];
}
// nothing bright around: not a screen
if (m < 48) continue;
const thr = m * ratio, y1 = Math.min(h, (ty + 1) * T), x1 = Math.min(w, (tx + 1) * T);
for (let y = ty * T; y < y1; y++) for (let x = tx * T; x < x1; x++) if (g[y * w + x] < thr) dark[y * w + x] = 1;
}
const stack = new Int32Array(w * h), lo = new Int32Array(h), hi = new Int32Array(h), stamp = new Int32Array(h).fill(-1);
let id = 0;
for (let start = 0; start < w * h; start++) { for (let start = 0; start < w * h; start++) {
if (label[start] !== -1 || small[start] > thr) continue; if (!dark[start]) continue;
// flood fill one dark component, keep per-row extents // flood fill one component, keep per-row extents
const id = cands.length, rows = new Map(); let sp = 0, count = 0, y0 = h, y1 = -1;
let count = 0; stack[sp++] = start; dark[start] = 0; id++;
label[start] = id; stack.push(start); while (sp) {
while (stack.length) { const i = stack[--sp], x = i % w, y = (i / w) | 0;
const i = stack.pop(), x = i % w, y = (i / w) | 0;
count++; count++;
const r = rows.get(y); if (stamp[y] !== id) { stamp[y] = id; lo[y] = hi[y] = x; if (y < y0) y0 = y; if (y > y1) y1 = y; }
if (r) { if (x < r[0]) r[0] = x; if (x > r[1]) r[1] = x; } else rows.set(y, [x, x]); else if (x < lo[y]) lo[y] = x; else if (x > hi[y]) hi[y] = x;
for (const j of [i - 1, i + 1, i - w, i + w]) { if (x > 0 && dark[i - 1]) { dark[i - 1] = 0; stack[sp++] = i - 1; }
if (j < 0 || j >= w * h || label[j] !== -1 || small[j] > thr) continue; if (x < w - 1 && dark[i + 1]) { dark[i + 1] = 0; stack[sp++] = i + 1; }
if ((j === i - 1 && x === 0) || (j === i + 1 && x === w - 1)) continue; if (y > 0 && dark[i - w]) { dark[i - w] = 0; stack[sp++] = i - w; }
label[j] = id; stack.push(j); if (y < h - 1 && dark[i + w]) { dark[i + w] = 0; stack[sp++] = i + w; }
} }
} if (count < 30 || y1 - y0 < 5) continue;
cands.push(null);
if (count < 30 || rows.size < 6) continue;
// moments of the row-filled shape, so the light logo inside doesn't count as holes // moments of the row-filled shape, so the light logo inside doesn't count as holes
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0; let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (const [y, [x0, x1]] of rows) { for (let y = y0; y <= y1; y++) {
const n = x1 - x0 + 1, sx = ((x0 + x1) * n) / 2, sxx = (x1 * (x1 + 1) * (2 * x1 + 1) - (x0 - 1) * x0 * (2 * x0 - 1)) / 6; if (stamp[y] !== id) continue;
const a0 = lo[y], a1 = hi[y], n = a1 - a0 + 1, sx = ((a0 + a1) * n) / 2;
const sxx = (a1 * (a1 + 1) * (2 * a1 + 1) - (a0 - 1) * a0 * (2 * a0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx; m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
} }
const ux = mx / m0, uy = my / m0; const ux = mx / m0, uy = my / m0;
@@ -322,19 +321,93 @@ export function locate(img, opts = {}) {
if (l2 <= 0) continue; if (l2 <= 0) continue;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2); const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0; const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.86 || fill > 1.14 || solidity < 0.5 || b / a < 0.38 || b < 5) continue; if (fill < 0.84 || fill > 1.16 || solidity < 0.5 || b / a < 0.38 || b < 3.5) continue;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy); const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), s = Math.sin(phi); const c = Math.cos(phi), sn = Math.sin(phi);
const k1 = (a * f) / CENTER, k2 = (b * f) / CENTER; const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER;
cands[id] = { cx: (ux + 0.5) * f - 0.5, cy: (uy + 0.5) * f - 0.5, A: [c * k1, -s * k2, s * k1, c * k2], area: m0 }; out.push({ cx: (ux + 0.5) * s - 0.5, cy: (uy + 0.5) * s - 0.5, A: [c * k1, -sn * k2, sn * k1, c * k2], area: m0 * s * s, r: Math.sqrt(a * b) * s });
} }
return cands.filter(Boolean).sort((p, q) => q.area - p.area).slice(0, opts.max || 4); }
const median = (a) => { const s = [...a].sort((x, y) => x - y); return s[s.length >> 1]; };
// does the neighbourhood look like a ring code? dark disc, light gap all around, half-dark textured band.
// cheap (a few dozen samples) and what keeps plain dark blobs away from the decoder
function ringness(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const at = (r, phi) => { const x = r * Math.sin(phi), y = -r * Math.cos(phi); return bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y); };
const n = 24, dk = [], gp = [], rb = [];
for (let i = 0; i < n; i++) {
const phi = (i / n) * 2 * Math.PI;
dk.push(at(0.48, phi)); gp.push(at(0.735, phi));
for (const R of RADII) rb.push(at(R, phi + 0.07), at(R, phi + 0.2));
}
// off-frame samples are NaN: a code cut by the border can't be read anyway
if (dk.some(Number.isNaN) || gp.some(Number.isNaN) || rb.some(Number.isNaN)) return null;
const D = median(dk), G = median(gp), span = G - D;
if (span < 14) return null;
const sg = [...gp].sort((x, y) => x - y), sd = [...dk].sort((x, y) => x - y);
if (sg[4] < D + 0.5 * span || sd[n - 5] > D + 0.4 * span) return null;
const mean = rb.reduce((x, y) => x + y, 0) / rb.length, q = (G - mean) / span;
const dev = Math.sqrt(rb.reduce((x, y) => x + (y - mean) ** 2, 0) / rb.length) / span;
if (q < 0.1 || q > 0.8 || dev < 0.1) return null;
// dashes go all the way round: text or a line next to a dark disc only inks one side
for (let k = 0; k < 4; k++) {
let s = 0, g = 0;
for (let i = k * 48; i < (k + 1) * 48; i++) s += rb[i];
// against the gap of the same side, bands shift whole sides
for (let i = k * 6; i < (k + 1) * 6; i++) g += gp[i];
const qk = (g / 6 - s / 48) / span;
if (qk < 0.08 || qk > 0.85) return null;
}
return { span, black: D, white: G };
}
// candidate center discs: solid dark elliptic blobs with rings around. returns [{ cx, cy, A, span }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 640)));
let w = Math.floor(img.w / f), h = Math.floor(img.h / f), g = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0;
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx];
g[y * w + x] = s / (f * f);
}
// each level sees discs of ~5..14 px radius, halving covers every size up to the whole frame
const raw = [];
for (let s = f; w >= 24 && h >= 24; s *= 2) {
// two cuts: the low one keeps a blurred disc apart from the first ring, the high one still sees it on a very washed screen
for (const ratio of [0.72, 0.8]) blobs(g, w, h, s, ratio, raw);
const w2 = w >> 1, h2 = h >> 1, g2 = new Float32Array(w2 * h2);
for (let y = 0; y < h2; y++) for (let x = 0; x < w2; x++) {
const i = 2 * y * w + 2 * x;
g2[y * w2 + x] = (g[i] + g[i + 1] + g[i + w] + g[i + w + 1]) / 4;
}
g = g2; w = w2; h = h2;
}
// same disc seen at two levels or cuts: keep the tightest blob, the others may have swallowed a ring
raw.sort((p, q) => q.area - p.area);
const cands = [];
for (const c of raw) {
const twin = cands.findIndex((o) => Math.hypot(o.cx - c.cx, o.cy - c.cy) < 0.5 * Math.max(o.r, c.r) && o.r / c.r < 1.6 && c.r / o.r < 1.6);
if (twin >= 0) { cands[twin] = c; continue; }
cands.push(c);
}
const out = [];
for (const c of cands) {
const fit = discFit(img, c) || c, rn = ringness(img, fit);
if (opts.dbg && Math.hypot(c.cx - opts.dbg.cx, c.cy - opts.dbg.cy) < 0.4 * opts.dbg.r) opts.dbg.stage = rn ? "ok" : fit === c ? "nofit" : "ringness";
if (rn) out.push({ ...fit, ...rn });
if (out.length >= 8) break;
}
// a projected code is the most contrasted thing around: dim look-alikes in the room go last
return out.sort((p, q) => q.span - p.span).slice(0, opts.max || 5);
} }
// the rough ellipse from the center disc is a bit off, and more so as the radius grows. // the rough ellipse from the center disc is a bit off, and more so as the radius grows.
// the rings themselves are the better reference: find their dark bands along rays, // the rings themselves are the better reference: find their dark bands along rays,
// fit one concentric ellipse family, undo center/scale/shear // fit one concentric ellipse family, undo center/scale/shear
function refine(S) { function refine(S, span) {
const rows = []; const rows = [];
const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005; const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) { for (let i = 0; i < rays; i++) {
@@ -344,7 +417,7 @@ function refine(S) {
if (prof.some(Number.isNaN)) continue; if (prof.some(Number.isNaN)) continue;
const sorted = [...prof].sort((a, b) => a - b); const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0]; const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 15) continue; if (bg - lo < 0.07 * span) continue;
RADII.forEach((R) => { RADII.forEach((R) => {
const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr); const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr);
let m = -1; let m = -1;
@@ -447,44 +520,6 @@ function cubicRoots(a, b, c, d) {
return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3); return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3);
} }
// image points on the center disc edge and on each ring, following rays of the rough affine map
function edgePoints(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const disc = [], rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
// disc edge: strongest dark-to-light step between 0.42 and 0.8
let best = 0, br = 0;
const prof = [];
for (let r = 0.4; r <= 0.82; r += 0.005) prof.push(at(r * dx, r * dy));
if (!prof.some(Number.isNaN)) {
for (let j = 2; j < prof.length - 2; j++) {
const gstep = prof[j + 2] - prof[j - 2];
if (gstep > best) { best = gstep; br = 0.4 + j * 0.005; }
}
if (best > 20) disc.push(map(br * dx, br * dy));
}
// rings: darkest point around each radius, only when it is a clear dip (a dark dash)
RADII.forEach((R, k) => {
const op = [], span = 0.07;
for (let r = R - span; r <= R + span + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 35) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - span + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return { disc, rings };
}
// center of a conic (3x3 symmetric), in its own coordinates // center of a conic (3x3 symmetric), in its own coordinates
function conicCenter(Q) { function conicCenter(Q) {
const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0]; const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0];
@@ -492,25 +527,89 @@ function conicCenter(Q) {
return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d]; return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d];
} }
function nelderMead(f, x0, step, iters) { // image points on the center disc edge, following rays of the rough affine map
let pts = [x0, [x0[0] + step, x0[1]], [x0[0], x0[1] + step]].map((x) => ({ x, v: f(x) })); function discEdge(img, cand, rays) {
for (let it = 0; it < iters; it++) { const [a11, a12, a21, a22] = cand.A, unit = Math.sqrt(Math.abs(a11 * a22 - a12 * a21));
pts.sort((a, b) => a.v - b.v); const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const [b, g, w] = pts, c = [(b.x[0] + g.x[0]) / 2, (b.x[1] + g.x[1]) / 2]; // about half a pixel per step, small discs don't need 85 samples per ray
const at = (t) => [c[0] + t * (w.x[0] - c[0]), c[1] + t * (w.x[1] - c[1])]; const dr = Math.max(0.005, 0.5 / unit), pts = [];
const r = { x: at(-1) }; r.v = f(r.x); for (let i = 0; i < rays; i++) {
if (r.v < b.v) { const e = { x: at(-2) }; e.v = f(e.x); pts[2] = e.v < r.v ? e : r; } const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
else if (r.v < g.v) pts[2] = r; const prof = [];
else { const k = { x: at(0.5) }; k.v = f(k.x); if (k.v < w.v) pts[2] = k; else pts = [b, ...[g, w].map((p) => { const x = [(p.x[0] + b.x[0]) / 2, (p.x[1] + b.x[1]) / 2]; return { x, v: f(x) }; })]; } let lo = Infinity, hi = -Infinity, bad = false;
for (let r = 0.4; r <= 0.84; r += dr) {
const [u, v] = map(r * dx, r * dy), p = bilinear(img, u, v);
if (Number.isNaN(p)) { bad = true; break; }
prof.push(p); if (p < lo) lo = p; if (p > hi) hi = p;
} }
pts.sort((a, b) => a.v - b.v); if (bad || hi - lo < 10) continue;
return pts[0].x; // strongest dark-to-light step
let best = 0, bj = 0;
for (let j = 2; j < prof.length - 2; j++) { const s = prof[j + 2] - prof[j - 2]; if (s > best) { best = s; bj = j; } }
if (best < 0.2 * (hi - lo) || bj < 4 || bj > prof.length - 5) continue;
const g0 = prof[bj + 1] - prof[bj - 3], g2 = prof[bj + 3] - prof[bj - 1], den = g0 - 2 * best + g2;
const off = den < 0 ? Math.max(-1, Math.min(1, (0.5 * (g0 - g2)) / den)) : 0;
const br = 0.4 + (bj + off) * dr;
pts.push(map(br * dx, br * dy));
}
return pts;
} }
// projective map code space -> image from the two conics, or null // the blob moments are rough on small discs: refit the ellipse on the disc edge at full resolution
function discFit(img, cand) {
let cur = cand;
for (let pass = 0; pass < 2; pass++) {
const pts = discEdge(img, cur, 48);
if (pts.length < 30) return pass ? cur : null;
const mx = pts.reduce((s, p) => s + p[0], 0) / pts.length, my = pts.reduce((s, p) => s + p[1], 0) / pts.length;
const sc = Math.sqrt(pts.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / pts.length) || 1;
const Q = fitConic(pts.map((p) => [(p[0] - mx) / sc, (p[1] - my) / sc]));
const c0 = Q && conicCenter(Q);
if (!c0) return pass ? cur : null;
const kk = -(Q[2][2] + Q[0][2] * c0[0] + Q[1][2] * c0[1]);
let p = Q[0][0] / kk, q = Q[0][1] / kk, r = Q[1][1] / kk;
const det = p * r - q * q;
if (!(p > 0 && det > 0)) return pass ? cur : null;
// x^T M x = 1: the map from the unit circle is M^-1/2, closed form for 2x2
const n11 = r / det, n12 = -q / det, n22 = p / det, sd = Math.sqrt(n11 * n22 - n12 * n12), t = Math.sqrt(n11 + n22 + 2 * sd);
const k = sc / CENTER / t, A = [(n11 + sd) * k, n12 * k, n12 * k, (n22 + sd) * k];
const size = Math.sqrt(Math.abs(A[0] * A[3] - A[1] * A[2])) * CENTER, cx = mx + c0[0] * sc, cy = my + c0[1] * sc;
if (Math.hypot(cx - cand.cx, cy - cand.cy) > 0.4 * cand.r || size < 0.6 * cand.r || size > 1.6 * cand.r) return pass ? cur : null;
cur = { ...cand, cx, cy, A, r: size };
}
return cur;
}
// image points on each ring: darkest point around each radius, only when it is a clear dip (a dark dash)
function ringDips(img, cand, span) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
RADII.forEach((R, k) => {
const op = [], reach = 0.07;
for (let r = R - reach; r <= R + reach + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 0.16 * span) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - reach + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return rings;
}
// projective map code space -> image coordinates from the two conics, or null
export let lastProjective = null; export let lastProjective = null;
function projective(img, cand) { function projective(img, cand) {
const { disc, rings } = edgePoints(img, cand); const span = cand.span || 200, disc = discEdge(img, cand, 160), rings = ringDips(img, cand, span);
const outer = rings[rings.length - 1]; const outer = rings[rings.length - 1];
lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' }; lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' };
if (disc.length < 40 || outer.length < 30) return null; if (disc.length < 40 || outer.length < 30) return null;
@@ -573,19 +672,94 @@ function projective(img, cand) {
return [X * sc + mx, Y * sc + my]; return [X * sc + mx, Y * sc + my];
}; };
lastProjective.map = map; lastProjective.map = map;
return (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); }; return map;
} }
// reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null. // unsharp mask on a small crop: undoes part of the camera blur and flattens slow brightness changes
// (rolling shutter bands, vignetting), which a washed-out projection can't afford
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) tmp[i] = (b[x > 0 ? i - 1 : i] + 2 * b[i] + b[x < w - 1 ? i + 1 : i]) / 4;
for (let y = 0, i = 0; y < h; y++) for (let x = 0; x < w; x++, i++) b[i] = (tmp[y > 0 ? i - w : i] + 2 * tmp[i] + tmp[y < h - 1 ? i + w : i]) / 4;
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
// sectors close to each other in code space, across rings: the local reference for dark vs light
const NEAR = (() => {
const pts = [];
RING_SECTORS.forEach((n, k) => { for (let j = 0; j < n; j++) { const a = sectorAngle(0, j, n); pts.push([RADII[k] * Math.sin(a), -RADII[k] * Math.cos(a)]); } });
return pts.map((p, i) => pts.map((_, m) => m).filter((m) => m !== i && Math.hypot(pts[m][0] - p[0], pts[m][1] - p[1]) < 0.5));
})();
// vals: brightness of the 120 sectors, sync ring first. two-means split against nearby sectors, seeded by the
// sync ring whose bits are known. returns data bits and soft values (> 0 dark, ~1 = a clean dash)
function classify(vals) {
const n = vals.length, known = SYNC_BITS.length;
let D = 0, L = 0, nd = 0;
for (let j = 0; j < known; j++) if (SYNC_BITS[j]) { D += vals[j]; nd++; } else L += vals[j];
D /= nd; L /= known - nd;
const swing = L - D;
if (!(swing > 0)) return null;
const bit = new Uint8Array(n), thr = new Float32Array(n).fill((D + L) / 2), half = new Float32Array(n).fill(swing / 2);
for (let i = 0; i < n; i++) bit[i] = i < known ? SYNC_BITS[i] : +(vals[i] < thr[i]);
for (let it = 0; it < 3; it++) {
for (let i = 0; i < n; i++) {
let sd = 0, cd = 0, sl = 0, cl = 0;
for (const m of NEAR[i]) if (bit[m]) { sd += vals[m]; cd++; } else { sl += vals[m]; cl++; }
if (cd < 2 || cl < 2) continue;
const d = sd / cd, l = sl / cl;
if (l - d > 0.35 * swing) { thr[i] = (d + l) / 2; half[i] = (l - d) / 2; }
}
for (let i = known; i < n; i++) bit[i] = +(vals[i] < thr[i]);
}
const soft = new Float32Array(n - known);
for (let i = known; i < n; i++) soft[i - known] = Math.max(-2, Math.min(2, (thr[i] - vals[i]) / half[i]));
return { bits: Array.from(bit.subarray(known)), soft };
}
// bits -> token, or null. soft tells how sure each bit was
function tokenOf(bits, soft, strict = true) {
const cw = bytesFromBits(bits), fixed = rsFix(cw);
if (!fixed) return null;
let bad = 0, flips = 0, shaky = 0, all = 0;
for (let i = 0; i < cw.length; i++) {
if (cw[i] === fixed[i]) continue;
bad++;
for (let k = 0; k < 8; k++) if (((cw[i] ^ fixed[i]) >> (7 - k)) & 1) { flips++; shaky += Math.abs(soft[i * 8 + k]); }
}
for (let i = 0; i < soft.length; i++) all += Math.abs(soft[i]);
// rs "repairs" 1 random word in 80000 at 3 byte errors. noise gets its confident bits flipped as often as
// the shaky ones, a real read only loses shaky ones
if (strict && bad >= 3 && shaky / flips > 0.7 * (all / soft.length)) return null;
return { token: tokenFromPayload(fixed.slice(0, fixed.length - NSYM)), fixes: bad };
}
// reads one candidate. returns { token, theta, score, scale, soft } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames) // tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) { export function decodeAt(img, cand, opts = {}) {
const span = cand.span || 200, unit = Math.sqrt(Math.abs(cand.A[0] * cand.A[3] - cand.A[1] * cand.A[2]));
let tone = img, x0 = 0, y0 = 0;
if (opts.sharpen !== false && unit < 70) {
// small code (under ~210 px across): read tones from a sharpened crop
const half = Math.ceil(unit * (DISC + 0.25)) + 4;
x0 = Math.max(0, Math.round(cand.cx) - half); y0 = Math.max(0, Math.round(cand.cy) - half);
const x1 = Math.min(img.w, Math.round(cand.cx) + half + 1), y1 = Math.min(img.h, Math.round(cand.cy) + half + 1);
const w = x1 - x0, h = y1 - y0, g = new Float32Array(w * h);
for (let y = 0; y < h; y++) g.set(img.g.subarray((y0 + y) * img.w + x0, (y0 + y) * img.w + x1), y * w);
tone = sharpen({ g, w, h }, 6, 2);
}
const [a11, a12, a21, a22] = cand.A; const [a11, a12, a21, a22] = cand.A;
const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y); // geometry comes from the plain image, tones from the sharpened one
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean); const proj = opts.projective !== false && projective(img, cand);
const maps = [proj && ((x, y) => { const [u, v] = proj(x, y); return bilinear(tone, u - x0, v - y0); }),
(x, y) => bilinear(tone, cand.cx - x0 + a11 * x + a12 * y, cand.cy - y0 + a21 * x + a22 * y)].filter(Boolean);
let best = null; let best = null;
for (const S0 of maps) { for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0)) || S0; const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0;
const r = readRings(S, opts); const r = readRings(S, { ...opts, span });
if (r && r.token) return r; if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r; if (r && (!best || r.score > best.score)) best = r;
} }
@@ -611,6 +785,8 @@ function readRings(S, opts) {
} }
} }
coarse.sort((p, q) => q.score - p.score); coarse.sort((p, q) => q.score - p.score);
// nothing like the sync pattern at any angle: not a code, skip the fine search
if (coarse[0].score < 0.5) return { token: null, ...coarse[0], vals: undefined };
let best = null; let best = null;
for (const c of coarse.slice(0, 3)) { for (const c of coarse.slice(0, 3)) {
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) { for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
@@ -619,12 +795,13 @@ function readRings(S, opts) {
} }
} }
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise // weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return best ? { token: null, ...best } : null; if (!best || best.score < minScore) return best ? { token: null, ...best, vals: undefined } : null;
const dark = [], light = []; const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v)); best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length; const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
if (ml - md < 12) return { token: null, ...best }; const out = { ...best, vals: undefined, token: null };
const bits = []; if (ml - md < Math.max(5, 0.055 * (opts.span || 200))) return out;
const all = [...best.vals], otsu = [];
for (let k = 1; k < RING_SECTORS.length; k++) { for (let k = 1; k < RING_SECTORS.length; k++) {
// nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split // nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n; const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
@@ -636,21 +813,68 @@ function readRings(S, opts) {
const sp = split(vals); const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals }; if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
} }
if (!pick) return { token: null, ...best }; if (!pick) return out;
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0); all.push(...pick.vals);
for (const v of pick.vals) otsu.push(+(v < pick.thr));
} }
const msg = rsDecode(bytesFromBits(bits)); const c = classify(all);
return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null }; if (!c) return out;
// local split first (bands, vignetting), plain per-ring split as a second opinion (strong tilt)
const strict = best.score < 0.92, t = tokenOf(c.bits, c.soft, strict) || tokenOf(otsu, c.soft, strict);
return { ...out, bits: c.bits.join(""), soft: c.soft, token: t ? t.token : null, fixes: t ? t.fixes : null };
} }
// whole frame: find center discs, read the first one that yields a valid token // whole frame: find center discs, read the first one that yields a valid token
export function decodeFrame(img, opts = {}) { export function decodeFrame(img, opts = {}) {
const cands = locate(img, opts); // seed: where the disc was a moment ago, or on a smaller copy of the frame. refit there before searching again
let cands = [];
if (opts.seed) {
const s = opts.seed, k = s.r / CENTER, fit = discFit(img, { cx: s.cx, cy: s.cy, A: s.A || [k, 0, 0, k], r: s.r }), rn = fit && ringness(img, fit);
if (rn) cands = [{ ...fit, ...rn }];
}
if (!cands.length) cands = locate(img, opts);
let last = null; let last = null;
for (const c of cands) { for (const c of cands) {
const r = decodeAt(img, c, opts); const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length }; if (r && r.token) return { ...r, cand: c, found: cands.length };
last = r || last; if (r && (!last || r.score > last.score)) last = { ...r, cand: c };
} }
return { token: null, found: cands.length, score: last?.score ?? null }; return { token: null, found: cands.length, score: last?.score ?? null, soft: last?.soft, cand: last?.cand || cands[0] };
} }
// frame after frame: adds up the soft bits of frames showing the same code, so a code too noisy
// for one frame still gets through, and keeps tokens in line with the previous ones
export function makeReader(opts = {}) {
let acc = null, frames = 0, anchor = null, pending = null;
const similar = (a, b) => { let s = 0, na = 0, nb = 0; for (let i = 0; i < a.length; i++) { s += a[i] * b[i]; na += a[i] * a[i]; nb += b[i] * b[i]; } return s / Math.sqrt(na * nb || 1); };
// slots only move forward, about 2 per second: a token far from the last one is noise or a replay
// a first token that needed the full rs correction waits for a second one to agree
const gate = (token, now, sure) => {
const slot = +token.slice(1).split(".")[0];
const near = (ref) => { const d = ((slot - ref.slot + 98304) % 65536) - 32768; return d >= -8 && d <= 8 + (now - ref.at) / 100; };
if (anchor ? near(anchor) : sure) { anchor = { slot, at: now }; pending = null; return true; }
if (pending && near(pending)) { anchor = { slot, at: now }; pending = null; return true; }
pending = { slot, at: now };
return false;
};
return {
read(img, now = Date.now(), seed = null) {
const d = decodeFrame(img, { ...opts, seed });
let token = d.token, via = "frame";
if (!token && d.soft && opts.accumulate !== false) {
if (acc && similar(acc, d.soft) > 0.3) { for (let i = 0; i < acc.length; i++) acc[i] += d.soft[i]; frames++; }
else { acc = Float32Array.from(d.soft); frames = 1; }
if (frames > 1) {
const t = tokenOf(Array.from(acc, (v) => +(v > 0)), acc);
// summed frames only get the safe corrections
if (t && t.fixes <= 2) { token = t.token; via = "sum"; }
}
} else if (token) { acc = Float32Array.from(d.soft, (v) => (v > 0 ? 1.5 : -1.5)); frames = 1; }
if (token && opts.gate !== false && !gate(token, now, via === "sum" || d.fixes <= 2)) token = null;
return { ...d, token, via };
},
};
}
// internals for the lab bench
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf };
+56
View File
@@ -0,0 +1,56 @@
// camera side of the ring code: finds the code on a small copy of the frame, then reads it from a crop
// at full sensor resolution. far codes keep every pixel the camera has, and the cost per frame stays flat
import { makeReader, locate, grayOf, CENTER, DISC } from "./ringcode.js";
const WIDE = 960, CROP = 360;
export function makeRingScanner(opts = {}) {
const reader = makeReader(opts);
const wide = document.createElement("canvas"), wctx = wide.getContext("2d", { willReadFrequently: true });
const crop = document.createElement("canvas"), cctx = crop.getContext("2d", { willReadFrequently: true });
let track = null;
// source px of the square around a code of the given unit
function readAt(src, sw, sh, t, now) {
const half = t.unit * (DISC + 0.9);
const x0 = Math.max(0, Math.round(t.cx - half)), y0 = Math.max(0, Math.round(t.cy - half));
const w = Math.min(sw, Math.round(t.cx + half)) - x0, h = Math.min(sh, Math.round(t.cy + half)) - y0;
if (w < 24 || h < 24) return null;
const k = Math.min(1, (opts.crop || CROP) / Math.max(w, h));
crop.width = Math.round(w * k); crop.height = Math.round(h * k);
cctx.imageSmoothingQuality = "high";
cctx.drawImage(src, x0, y0, w, h, 0, 0, crop.width, crop.height);
const seed = { cx: (t.cx - x0) * k - 0.5, cy: (t.cy - y0) * k - 0.5, r: t.unit * CENTER * k, A: t.A && t.A.map((v) => v * k) };
const d = reader.read(grayOf(cctx.getImageData(0, 0, crop.width, crop.height)), now, seed);
if (!d.cand) return null;
// only a blob with a sync ring keeps the crop alive, anything else goes back to the whole frame
if (!d.token && !d.soft) { track = null; return d; }
track = { cx: x0 + (d.cand.cx + 0.5) / k, cy: y0 + (d.cand.cy + 0.5) / k, unit: d.cand.r / CENTER / k, A: d.cand.A.map((v) => v / k), at: now };
return d;
}
return {
// src: video or canvas of sw x sh. returns { token, ... } with token null when nothing was read
scan(src, sw, sh, now = performance.now()) {
if (track && now - track.at < 700) {
const d = readAt(src, sw, sh, track, now);
if (d) return d;
}
track = null;
// phones held upright hand over a 1080x1920 stream
const k = Math.min(1, WIDE / Math.max(sw, sh));
wide.width = Math.round(sw * k); wide.height = Math.round(sh * k);
// plain bilinear at 3x reduction skips pixels and keeps the noise
wctx.imageSmoothingQuality = "high";
wctx.drawImage(src, 0, 0, wide.width, wide.height);
const cands = locate(grayOf(wctx.getImageData(0, 0, wide.width, wide.height)), { max: 5 });
let last = null;
for (const c of cands) {
const d = readAt(src, sw, sh, { cx: (c.cx + 0.5) / k, cy: (c.cy + 0.5) / k, unit: c.r / CENTER / k, A: c.A.map((v) => v / k) }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
},
};
}
+14 -8
View File
@@ -1,5 +1,5 @@
import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js"; import { $, h, api, pollId, liveSocket, resultsView, toast, ring, icon } from "./common.js";
import { decodeFrame, grayOf } from "./ringcode.js"; import { makeRingScanner } from "./ringscan.js";
const pid = pollId(); const pid = pollId();
const DONE_KEY = `rv_done_${pid}`; const DONE_KEY = `rv_done_${pid}`;
@@ -74,20 +74,22 @@ async function startScanner() {
function makeScanner(video, onToken, onOther) { function makeScanner(video, onToken, onOther) {
let stream = null, running = false; let stream = null, running = false;
const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
const rings = makeRingScanner();
async function loop() { async function loop() {
if (!running) return; if (!running) return;
const t0 = performance.now(); const t0 = performance.now();
if (video.readyState >= 2 && video.videoWidth) { if (video.readyState >= 2 && video.videoWidth) {
// 960 px is plenty and keeps low-end phones near 7 fps try {
if (codeStyle === "ring") {
// reads a crop at sensor resolution: a far code keeps all its pixels
const d = rings.scan(video, video.videoWidth, video.videoHeight);
if (d.token) onToken(d.token);
} else {
// 960 px is plenty for a qr and keeps low-end phones near 7 fps
const k = Math.min(1, 960 / video.videoWidth); const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k); canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k); canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
try {
if (codeStyle === "ring") {
const d = decodeFrame(grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)));
if (d.token) onToken(d.token);
} else {
qrEngine ||= await window.QrScanner.createQrEngine(); qrEngine ||= await window.QrScanner.createQrEngine();
const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null); const r = await window.QrScanner.scanImage(canvas, { qrEngine, returnDetailedScanResult: true }).catch(() => null);
if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); } if (r) { const tok = tokenOf(r.data); if (tok) onToken(tok); else onOther?.(); }
@@ -99,9 +101,13 @@ function makeScanner(video, onToken, onOther) {
} }
return { return {
async start() { async start() {
// rings from the back of a room are a few dozen pixels wide at 720p, ask for the full sensor
const [w, h] = codeStyle === "ring" ? [1920, 1080] : [1280, 720];
stream = await navigator.mediaDevices.getUserMedia({ stream = await navigator.mediaDevices.getUserMedia({
audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false, video: { facingMode: { ideal: "environment" }, width: { ideal: w }, height: { ideal: h } },
}); });
// not every browser knows focusMode, those ignore it
stream.getVideoTracks()[0]?.applyConstraints({ advanced: [{ focusMode: "continuous" }] }).catch(() => {});
video.srcObject = stream; video.srcObject = stream;
await video.play(); await video.play();
running = true; running = true;
+4 -2
View File
@@ -5,6 +5,8 @@
<script type="module"> <script type="module">
import { render, decodeFrame, grayOf, locate, decodeAt, DISC } from "/static/js/ringcode.js"; import { render, decodeFrame, grayOf, locate, decodeAt, DISC } from "/static/js/ringcode.js";
import * as RC from "/static/js/ringcode.js"; import * as RC from "/static/js/ringcode.js";
import "/static/ringlab/far.js";
import * as V1 from "/static/ringlab/ringcode_v1.js";
// warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective) // warps canvas `src` onto a new w x h canvas so that src's unit square maps to quad `dst` (perspective)
function warp(src, dst, w, h, bg) { function warp(src, dst, w, h, bg) {
@@ -86,7 +88,7 @@ window.runBench = async (cfg) => {
clutter(sctx, 960, 720, rnd); clutter(sctx, 960, 720, rnd);
if (!trial.nocode) { if (!trial.nocode) {
actx.clearRect(0, 0, A.width, A.height); actx.clearRect(0, 0, A.width, A.height);
render(actx, A.width / 2, A.height / 2, A.width / (2 * DISC), trial.theta, trial.bits, trial.anim); (cfg.v1 ? V1.render : render)(actx, A.width / 2, A.height / 2, A.width / (2 * DISC), trial.theta, trial.bits, trial.anim);
const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis, trial.dist || 3.5); const q = quad(480 + trial.dx, 360 + trial.dy, trial.d, trial.tilt, trial.axis, trial.dist || 3.5);
sctx.drawImage(warp(A, q, 960, 720), 0, 0); sctx.drawImage(warp(A, q, 960, 720), 0, 0);
} }
@@ -99,7 +101,7 @@ window.runBench = async (cfg) => {
cctx.putImageData(id, 0, 0); cctx.putImageData(id, 0, 0);
} }
const t0 = performance.now(); const t0 = performance.now();
const d = decodeFrame(grayOf(cctx.getImageData(0, 0, 960, 720))); const d = (cfg.v1 ? V1.decodeFrame : decodeFrame)(grayOf(cctx.getImageData(0, 0, 960, 720)));
const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) }; const out = { found: d.found, token: d.token, score: d.score == null ? null : +d.score.toFixed(3), ms: Math.round(performance.now() - t0) };
out.ok = trial.nocode ? !d.token : d.token === trial.token; out.ok = trial.nocode ? !d.token : d.token === trial.token;
if (d.bits && !trial.nocode) { if (d.bits && !trial.nocode) {
+193
View File
@@ -0,0 +1,193 @@
// far / low contrast bench: stills with per-stage diagnosis, and timed sequences
import * as RC from "/static/js/ringcode.js";
import { lcg, makeRoom, frame, jpeg, design } from "/static/ringlab/synth.js";
import * as V1 from "/static/ringlab/ringcode_v1.js";
import { makeRingScanner } from "/static/js/ringscan.js";
window.makeRingScanner = makeRingScanner;
const { decodeFrame, grayOf, locate, decodeAt, RADII, CENTER, _lab } = RC;
function grab(canvas, maxW) {
const k = Math.min(1, maxW / canvas.width);
if (k === 1) return { img: grayOf(canvas.getContext("2d").getImageData(0, 0, canvas.width, canvas.height)), k };
const c = document.createElement("canvas"); c.width = Math.round(canvas.width * k); c.height = Math.round(canvas.height * k);
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.drawImage(canvas, 0, 0, c.width, c.height);
return { img: grayOf(ctx.getImageData(0, 0, c.width, c.height)), k };
}
// pipelines under test: canvas -> { token, ... }
const scanners = {};
const pipes = {
legacy: (canvas) => V1.decodeFrame(grab(canvas, 960).img), // what vote.js shipped with
cap960: (canvas, t) => decodeFrame(grab(canvas, 960).img, t.opts || {}),
native: (canvas, t) => decodeFrame(grab(canvas, 1e9).img, t.opts || {}),
noacc: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner({ accumulate: false }));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
crop: (canvas, t, key) => {
const s = (scanners[key] ||= window.makeRingScanner({ gate: t.now != null, crop: +key.slice(4) }));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
scan: (canvas, t, key) => {
// a lone still has no previous token to agree with
const s = (scanners[key] ||= window.makeRingScanner(t.now == null ? { gate: false } : {}));
return s.scan(canvas, canvas.width, canvas.height, t.now ?? undefined);
},
};
// where does a failed frame break? substitutes the truth stage by stage
function diagnose(img, k, truth, t) {
const T = (x, y) => { const [u, v] = truth(x, y); return [(u + 0.5) * k - 0.5, (v + 0.5) * k - 0.5]; };
const [cx, cy] = T(0, 0), [ex, ey] = T(CENTER, 0), rpx = Math.hypot(ex - cx, ey - cy);
const out = { rpx: +rpx.toFixed(1) };
const dbg = { cx, cy, r: rpx, stage: "noblob" };
const cands = locate(img, { max: 60, dbg });
out.loc = dbg.stage;
out.rank = cands.findIndex((c) => Math.hypot(c.cx - cx, c.cy - cy) < 0.3 * rpx);
out.ncand = cands.length;
if (out.rank >= 0) { const r = decodeAt(img, cands[out.rank], {}); out.candOk = !!(r && r.token === t.token); out.candScore = r ? +(+r.score).toFixed(2) : null; }
const S = (x, y) => { const [u, v] = T(x, y); return _lab.bilinear(img, u, v); };
const r = _lab.readRings(S, {});
out.oracleGeo = !!(r && r.token === t.token);
out.oracleScore = r && r.score != null ? +r.score.toFixed(2) : null;
// true geometry and rotation: is the tone of each dash still separable?
const rings = RC.ringsOf(t.bits);
let bitErr = 0, idealErr = 0; const dp = [], byteBits = [];
rings.forEach((ring, ri) => {
const n = ring.length, step = (2 * Math.PI) / n, vals = [];
for (let j = 0; j < n; j++) vals.push(_lab.sector(S, RADII[ri], _lab.sectorAngle(t.theta, j, n), step));
const dark = vals.filter((_, j) => ring[j] === "1"), light = vals.filter((_, j) => ring[j] === "0");
const m = (a) => a.reduce((x, y) => x + y, 0) / a.length, sd = (a) => Math.sqrt(m(a.map((v) => (v - m(a)) ** 2)));
dp.push(+((m(light) - m(dark)) / (Math.hypot(sd(light), sd(dark)) / Math.SQRT2 || 1)).toFixed(1));
if (ri === 0) { out.span = +(m(light) - m(dark)).toFixed(0); return; }
const sp = _lab.split(vals);
let best = n;
for (const thr of vals) { let e = 0; vals.forEach((v, j) => { e += (v <= thr ? "1" : "0") !== ring[j]; }); best = Math.min(best, e); }
idealErr += best;
vals.forEach((v, j) => { const e = (v < sp.thr ? "1" : "0") !== ring[j]; bitErr += e; byteBits.push(e); });
});
let byteErr = 0;
for (let i = 0; i < 96; i += 8) byteErr += byteBits.slice(i, i + 8).some(Boolean);
Object.assign(out, { dprime: dp, bitErr, idealErr, byteErr, lab: toneLab(img, T, t) });
out.stage = out.rank < 0 || out.rank >= 4 ? "locate" : out.oracleGeo ? "geometry" : byteErr <= 3 ? "sync/thr" : "tone";
return out;
}
// lab only: which bit decision would survive, given the true geometry? and how much do neighbours bleed in?
function sharpen(img, passes, amt) {
const { g, w, h } = img, b = Float32Array.from(g), tmp = new Float32Array(w * h);
for (let p = 0; p < passes; p++) {
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; tmp[i] = (b[i - (x > 0)] + 2 * b[i] + b[i + (x < w - 1)]) / 4; }
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) { const i = y * w + x; b[i] = (tmp[i - (y > 0 ? w : 0)] + 2 * tmp[i] + tmp[i + (y < h - 1 ? w : 0)]) / 4; }
}
for (let i = 0; i < b.length; i++) b[i] = g[i] + amt * (g[i] - b[i]);
return { g: b, w, h };
}
function toneLab(img, T, t) {
const rings = RC.ringsOf(t.bits), out = {};
const read = (im) => {
const S = (x, y) => { const [u, v] = T(x, y); return _lab.bilinear(im, u, v); };
return rings.map((ring, ri) => { const n = ring.length, step = (2 * Math.PI) / n; return ring.split("").map((_, j) => _lab.sector(S, RADII[ri], _lab.sectorAngle(t.theta, j, n), step)); });
};
const errs = (vals, thrOf) => { let e = 0; for (let ri = 1; ri < 4; ri++) { const thr = thrOf(ri); vals[ri].forEach((v, j) => { e += (v < thr ? "1" : "0") !== rings[ri][j]; }); } return e; };
const m = (a) => a.reduce((x, y) => x + y, 0) / a.length;
const variants = { raw: img, sh1: sharpen(img, 3, 1), sh2: sharpen(img, 6, 2) };
for (const [name, im] of Object.entries(variants)) {
const vals = read(im);
if (vals.flat().some(Number.isNaN)) continue;
const D = m(vals[0].filter((_, j) => rings[0][j] === "1")), L = m(vals[0].filter((_, j) => rings[0][j] === "0"));
out[name + "Otsu"] = errs(vals, (ri) => _lab.split(vals[ri]).thr);
out[name + "Sync"] = errs(vals, () => (D + L) / 2);
const all = _lab.split(vals.slice(1).flat()).thr;
out[name + "All"] = errs(vals, () => all);
// local: compare each dash with the mean of its ring neighbourhood
let e = 0;
for (let ri = 1; ri < 4; ri++) { const v = vals[ri], n = v.length; v.forEach((x, j) => { let lo = Infinity, hi = -Infinity; for (let d = -3; d <= 3; d++) { const y = v[(j + d + n) % n]; if (y < lo) lo = y; if (y > hi) hi = y; } const thr = hi - lo > 0.5 * (L - D) ? (lo + hi) / 2 : (D + L) / 2; e += (x < thr ? "1" : "0") !== rings[ri][j]; }); }
out[name + "Local"] = e;
if (name !== "raw") continue;
// y = c0 + own*b + ang*mean(ring neighbours) + rad*mean(adjacent rings), in units of the sync ring swing
const rows = [];
rings.forEach((ring, ri) => {
const n = ring.length;
for (let j = 0; j < n; j++) {
const frac = (j + 0.5) / n, nb = (k) => (k < 0 || k > 3 ? 0 : +rings[k][Math.floor(frac * rings[k].length)]);
rows.push([1, +ring[j], (+ring[(j + 1) % n] + +ring[(j + n - 1) % n]) / 2, (nb(ri - 1) + nb(ri + 1)) / 2, (L - vals[ri][j]) / (L - D)]);
}
});
const N = Array.from({ length: 4 }, () => new Array(4).fill(0)), V = new Array(4).fill(0);
for (const r of rows) for (let i = 0; i < 4; i++) { V[i] += r[i] * r[4]; for (let j = 0; j < 4; j++) N[i][j] += r[i] * r[j]; }
for (let i = 0; i < 4; i++) { let p = i; for (let r = i + 1; r < 4; r++) if (Math.abs(N[r][i]) > Math.abs(N[p][i])) p = r; [N[i], N[p]] = [N[p], N[i]]; [V[i], V[p]] = [V[p], V[i]]; for (let r = 0; r < 4; r++) if (r !== i) { const f = N[r][i] / N[i][i]; for (let k = i; k < 4; k++) N[r][k] -= f * N[i][k]; V[r] -= f * V[i]; } }
const co = V.map((v, i) => v / N[i][i]);
let res = 0;
for (const r of rows) res += (r[4] - co[0] - co[1] * r[1] - co[2] * r[2] - co[3] * r[3]) ** 2;
out.isi = [...co, Math.sqrt(res / rows.length)].map((v) => +v.toFixed(3));
}
return out;
}
window.runFar = async (cfg) => {
const rnd = lcg(cfg.seed || 4242), results = [];
design.v1 = !!cfg.v1;
for (const t of cfg.trials) {
const room = makeRoom(t.W, t.H, t.room, rnd);
let f = frame(room, t, rnd);
if (t.jpeg) f = { ...f, canvas: await jpeg(f.canvas, t.jpeg) };
const res = { ...t, bits: undefined };
for (const name of cfg.pipes) {
for (const key of Object.keys(scanners)) delete scanners[key];
const t0 = performance.now();
const d = (pipes[name] || pipes[name.slice(0, 4)])(f.canvas, t, name);
const ms = performance.now() - t0;
res[name] = { ok: t.nocode ? !d.token : d.token === t.token, token: d.token || null, ms: +ms.toFixed(1), found: d.found, score: d.score == null ? null : +(+d.score).toFixed(2) };
}
if (cfg.diag && !t.nocode) {
const { img, k } = grab(f.canvas, cfg.diag === "legacy" ? 960 : 1e9);
res.diag = diagnose(img, k, f.truth, t);
}
if (cfg.keep && results.length < cfg.keep) res.png = f.canvas.toDataURL("image/jpeg", 0.9);
results.push(res);
}
return results;
};
// a phone held for a few seconds: rotation, token switches with cross-fade, shake, per-frame noise.
// seq: frame params + { fps, secs, interval, tokens: [{ bits, token }], shake }
window.runSeq = async (cfg) => {
const rnd = lcg(cfg.seed || 777), results = [];
design.v1 = !!cfg.v1;
for (const s of cfg.seqs) {
const room = makeRoom(s.W, s.H, s.room, rnd);
const res = { ...s, tokens: undefined };
for (const name of cfg.pipes) res[name] = { got: [], false: 0, frames: 0, ms: 0, first5: null };
for (const key of Object.keys(scanners)) delete scanners[key];
let px = 0, py = 0;
const fadeMs = Math.min(220, s.interval * 0.25), t00 = s.t0 || 0;
for (let i = 0; i < s.fps * s.secs; i++) {
const ms = t00 + (i * 1000) / s.fps + rnd() * 20, slot = Math.floor(ms / s.interval), idx = slot - Math.floor(t00 / s.interval);
const cur = s.tokens[idx], prev = idx > 0 ? s.tokens[idx - 1] : null, since = ms - slot * s.interval;
// hand shake: drifting offset plus a random smear for this exposure
px = px * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3; py = py * 0.8 + (rnd() - 0.5) * 2 * s.shake * 3;
const t = { ...s, bits: cur.bits, token: cur.token, theta: (ms / 1000) * (2 * Math.PI / 45), anim: ms / 1000,
fade: prev && since < fadeMs ? { from: prev.bits, k: since / fadeMs } : null,
dx: (s.dx || 0) + px * (s.W / 1280), dy: (s.dy || 0) + py * (s.W / 1280),
motion: [(rnd() - 0.5) * 2 * s.shake, (rnd() - 0.5) * 2 * s.shake], now: ms };
const f = frame(room, t, rnd);
for (const name of cfg.pipes) {
const r = res[name], t0 = performance.now();
const d = pipes[name](f.canvas, t, name + results.length);
r.ms += performance.now() - t0; r.frames++;
if (!d.token) continue;
// late reads of an older token are fine (accumulation), anything never shown is a false token
if (!s.tokens.slice(0, idx + 1).some((k) => k.token === d.token)) r.false++;
else if (!r.got.includes(d.token)) { r.got.push(d.token); if (r.got.length === 5) r.first5 = +((ms - t00) / 1000).toFixed(2); }
}
}
for (const name of cfg.pipes) { const r = res[name]; r.ms = +(r.ms / r.frames).toFixed(1); r.got = r.got.length; }
results.push(res);
}
return results;
};
+6 -5
View File
@@ -1,4 +1,6 @@
import { decodeFrame, grayOf } from "/static/js/ringcode.js"; import { makeRingScanner } from "/static/js/ringscan.js";
const rings = makeRingScanner();
const $ = (id) => document.getElementById(id); const $ = (id) => document.getElementById(id);
const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); const video = $("v"), canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true });
@@ -26,15 +28,14 @@ async function start() {
async function loop() { async function loop() {
if (!running) return; if (!running) return;
if (video.readyState >= 2) { if (video.readyState >= 2) {
// 960 px is plenty for the locator and keeps capture cheap on low-end phones // the qr reference reads a 960 px copy, the rings read their own crop of the full frame
const k = Math.min(1, 960 / video.videoWidth); const k = Math.min(1, 960 / video.videoWidth);
canvas.width = Math.round(video.videoWidth * k); canvas.width = Math.round(video.videoWidth * k);
canvas.height = Math.round(video.videoHeight * k); canvas.height = Math.round(video.videoHeight * k);
ctx.drawImage(video, 0, 0, canvas.width, canvas.height); ctx.drawImage(video, 0, 0, canvas.width, canvas.height);
frames++; fpsN++; frames++; fpsN++;
const img = grayOf(ctx.getImageData(0, 0, canvas.width, canvas.height)); const d = rings.scan(video, video.videoWidth, video.videoHeight);
const d = decodeFrame(img); if (d.cand) qr++;
if (d.found) qr++;
if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); } if (d.token) { ring++; mode = "anneaux"; tokens.add(d.token); }
else if (mode !== "anneaux") { else if (mode !== "anneaux") {
// reference mode: the classic rotating qr // reference mode: the classic rotating qr
+656
View File
@@ -0,0 +1,656 @@
// ring code: dark logo disc in the middle + rotating rings of dashes carrying the time token.
// layout, bit order and reed-solomon params must match rotatyvote/ringcode.py
// pure functions, no dom: runs in the browser and under node for the cross tests
export const SYNC = "010001100101001000111111";
export const RING_SECTORS = [24, 28, 32, 36];
// code space units, centered on the origin. the solid dark center disc is what the phone looks for
export const CENTER = 0.62;
export const RADII = [0.9, 1.05, 1.2, 1.35];
export const THICK = 0.105;
export const DISC = 1.5; // light background disc
// animation bounds: dash length and opacity breathe inside these, the data never depends on them
const LEN = [0.56, 0.86]; // part of the sector covered by the dash
// wide gap between the two classes so the camera tells them apart easily
const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19];
const NSYM = 6;
// gf(256), poly 0x11d, generator 2
const EXP = new Uint8Array(512), LOG = new Uint8Array(256);
{
let x = 1;
for (let i = 0; i < 255; i++) { EXP[i] = x; LOG[x] = i; x <<= 1; if (x & 0x100) x ^= 0x11d; }
for (let i = 255; i < 512; i++) EXP[i] = EXP[i - 255];
}
const mul = (a, b) => (a && b ? EXP[LOG[a] + LOG[b]] : 0);
const div = (a, b) => (a ? EXP[(LOG[a] + 255 - LOG[b]) % 255] : 0);
const pow = (x, p) => EXP[(((LOG[x] * p) % 255) + 255) % 255];
const inv = (x) => EXP[255 - LOG[x]];
const polyScale = (p, x) => p.map((c) => mul(c, x));
const polyAdd = (p, q) => {
const r = new Array(Math.max(p.length, q.length)).fill(0);
for (let i = 0; i < p.length; i++) r[i + r.length - p.length] = p[i];
for (let i = 0; i < q.length; i++) r[i + r.length - q.length] ^= q[i];
return r;
};
const polyMul = (p, q) => {
const r = new Array(p.length + q.length - 1).fill(0);
for (let j = 0; j < q.length; j++) for (let i = 0; i < p.length; i++) r[i + j] ^= mul(p[i], q[j]);
return r;
};
const polyEval = (p, x) => { let y = p[0]; for (let i = 1; i < p.length; i++) y = mul(y, x) ^ p[i]; return y; };
let GEN = [1];
for (let i = 0; i < NSYM; i++) GEN = polyMul(GEN, [1, pow(2, i)]);
export function rsEncode(msg) {
const rem = new Array(NSYM).fill(0);
for (const byte of msg) {
const f = byte ^ rem[0];
rem.shift(); rem.push(0);
if (f) for (let j = 0; j < NSYM; j++) rem[j] ^= mul(GEN[j + 1], f);
}
return [...msg, ...rem];
}
// port of the wikiversity "reed-solomon codes for coders" decoder (fcr 0, generator 2)
export function rsDecode(cw) {
const n = cw.length;
const synd = [0];
for (let i = 0; i < NSYM; i++) synd.push(polyEval(cw, pow(2, i)));
if (Math.max(...synd) === 0) return cw.slice(0, n - NSYM);
let errLoc = [1], oldLoc = [1];
for (let i = 0; i < NSYM; i++) {
const K = i + 1;
let delta = synd[K];
for (let j = 1; j < errLoc.length; j++) delta ^= mul(errLoc[errLoc.length - 1 - j], synd[K - j]);
oldLoc = [...oldLoc, 0];
if (delta) {
if (oldLoc.length > errLoc.length) {
const newLoc = polyScale(oldLoc, delta);
oldLoc = polyScale(errLoc, inv(delta));
errLoc = newLoc;
}
errLoc = polyAdd(errLoc, polyScale(oldLoc, delta));
}
}
while (errLoc.length && errLoc[0] === 0) errLoc.shift();
const errs = errLoc.length - 1;
if (errs * 2 > NSYM) return null;
const rev = [...errLoc].reverse();
const errPos = [];
for (let i = 0; i < n; i++) if (polyEval(rev, pow(2, i)) === 0) errPos.push(n - 1 - i);
if (errPos.length !== errs) return null;
const coefPos = errPos.map((p) => n - 1 - p);
let eLoc = [1];
for (const i of coefPos) eLoc = polyMul(eLoc, polyAdd([1], [pow(2, i), 0]));
// error evaluator: (synd reversed * eLoc) mod x^(len)
const prod = polyMul([...synd].reverse(), eLoc);
const evalLen = eLoc.length;
const errEval = prod.slice(prod.length - evalLen).reverse();
const X = coefPos.map((c) => pow(2, -(255 - c)));
const E = new Array(n).fill(0);
X.forEach((Xi, i) => {
const XiInv = inv(Xi);
let prime = 1;
X.forEach((Xj, j) => { if (j !== i) prime = mul(prime, 1 ^ mul(XiInv, Xj)); });
if (!prime) return;
const y = mul(Xi, polyEval([...errEval].reverse(), XiInv));
E[errPos[i]] = div(y, prime);
});
const fixed = cw.map((c, i) => c ^ E[i]);
for (let i = 0; i < NSYM; i++) if (polyEval(fixed, pow(2, i))) return null;
return fixed.slice(0, n - NSYM);
}
export function whitening(n) {
let lfsr = 0xace1;
const out = [];
for (let i = 0; i < n; i++) { const bit = lfsr & 1; lfsr >>= 1; if (bit) lfsr ^= 0xb400; out.push(bit); }
return out;
}
export function dataBits(codeword) {
const bits = [];
for (const b of codeword) for (let k = 7; k >= 0; k--) bits.push((b >> k) & 1);
const w = whitening(bits.length);
return bits.map((b, i) => b ^ w[i]).join("");
}
export function bytesFromBits(bits) {
const w = whitening(bits.length);
const out = [];
for (let i = 0; i < bits.length; i += 8) {
let v = 0;
for (let k = 0; k < 8; k++) v = (v << 1) | (bits[i + k] ^ w[i + k]);
out.push(v);
}
return out;
}
export function tokenFromPayload(p) {
const slot = (p[0] << 8) | p[1];
return `r${slot}.${p.slice(2).map((b) => b.toString(16).padStart(2, "0")).join("")}`;
}
// splits the 120 render bits into rings
export function ringsOf(bits) {
const rings = [];
let k = 0;
for (const n of RING_SECTORS) { rings.push(bits.slice(k, k + n)); k += n; }
return rings;
}
const sectorAngle = (theta, j, n) => theta + ((j + 0.5) * 2 * Math.PI) / n;
// ---- drawing (projector + bench) ----
const INK = "#1c2036";
function logo(ctx, cx, cy, r) {
// the rotaty mark in light tones on the dark disc
const n = 6, rr = r * 0.52, step = (2 * Math.PI) / n;
ctx.lineCap = "round";
ctx.lineWidth = r * 0.17;
for (let j = 0; j < n; j++) {
const a = -Math.PI / 2 + j * step;
ctx.strokeStyle = j === 0 ? "#ffcc00" : "#ffffff";
ctx.beginPath(); ctx.arc(cx, cy, rr, a + step * 0.2, a + step * 0.8); ctx.stroke();
}
}
// deterministic per-dash phase so every dash breathes on its own rhythm
const phase = (k, j) => ((Math.sin(k * 12.9898 + j * 78.233) * 43758.5453) % 1 + 1) % 1;
// fade: { from: previous bits, k: 0..1 } while the code switches, so changed dashes cross-fade
export function render(ctx, cx, cy, unit, theta, bits, t = 0, fade = null) {
ctx.fillStyle = "#eef0f6";
ctx.beginPath(); ctx.arc(cx, cy, DISC * unit, 0, 2 * Math.PI); ctx.fill();
ctx.fillStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, CENTER * unit, 0, 2 * Math.PI); ctx.fill();
logo(ctx, cx, cy, CENTER * unit);
const prev = fade && fade.k < 1 ? ringsOf(fade.from) : null;
const ease = fade ? fade.k * fade.k * (3 - 2 * fade.k) : 1;
ctx.lineCap = "round";
ctx.lineWidth = THICK * unit;
ringsOf(bits).forEach((ring, k) => {
const n = ring.length, r = RADII[k] * unit, step = (2 * Math.PI) / n;
const cap = (THICK * unit) / 2 / r;
for (let j = 0; j < n; j++) {
const ph = phase(k, j) * 2 * Math.PI, w = 0.5 + 0.5 * Math.sin(t * 1.3 + ph), w2 = 0.5 + 0.5 * Math.sin(t * 0.9 + ph * 1.7);
const len = LEN[0] + (LEN[1] - LEN[0]) * w;
const alphaOf = (bit) => { const [a0, a1] = bit === "1" ? ALPHA_DARK : ALPHA_LIGHT; return a0 + (a1 - a0) * w2; };
const now = alphaOf(ring[j]), before = prev ? alphaOf(prev[k][j]) : now;
const half = Math.max(0.01, (step * len) / 2 - cap);
const a = sectorAngle(theta, j, n) - Math.PI / 2;
ctx.globalAlpha = before + (now - before) * ease;
ctx.strokeStyle = INK;
ctx.beginPath(); ctx.arc(cx, cy, r, a - half, a + half); ctx.stroke();
}
});
ctx.globalAlpha = 1;
}
// ---- decoding (phone) ----
export function grayOf(imageData) {
const { data, width, height } = imageData, g = new Float32Array(width * height);
for (let i = 0, j = 0; i < g.length; i++, j += 4) g[i] = 0.299 * data[j] + 0.587 * data[j + 1] + 0.114 * data[j + 2];
return { g, w: width, h: height };
}
function bilinear(img, u, v) {
const { g, w, h } = img;
if (!(u >= 0 && v >= 0 && u < w - 1 && v < h - 1)) return NaN;
const x0 = u | 0, y0 = v | 0, fx = u - x0, fy = v - y0, i = y0 * w + x0;
return (g[i] * (1 - fx) + g[i + 1] * fx) * (1 - fy) + (g[i + w] * (1 - fx) + g[i + w + 1] * fx) * fy;
}
// mean brightness of one dash: a few points across its middle
function sector(S, r, a, step) {
let sum = 0, n = 0;
for (const dr of [-0.028, 0, 0.028]) for (const da of [-0.18, 0, 0.18]) {
const ang = a + da * step, rr = r + dr;
const v = S(rr * Math.sin(ang), -rr * Math.cos(ang));
if (!Number.isNaN(v)) { sum += v; n++; }
}
return n >= 6 ? sum / n : NaN;
}
const SYNC_BITS = [...SYNC].map(Number);
function corr(vals, bits) {
// dark (1) should be low: correlate values with -bit
const n = vals.length;
let mv = 0, mb = 0;
for (let i = 0; i < n; i++) { mv += vals[i]; mb += bits[i]; }
mv /= n; mb /= n;
let num = 0, dv = 0, db = 0;
for (let i = 0; i < n; i++) { const a = vals[i] - mv, b = -(bits[i] - mb); num += a * b; dv += a * a; db += b * b; }
return dv && db ? num / Math.sqrt(dv * db) : 0;
}
// otsu split of one ring: threshold + how well it separates (between-class / total variance)
function split(vals) {
const s = [...vals].sort((a, b) => a - b), n = s.length;
const total = s.reduce((a, b) => a + b, 0), mean = total / n;
const tv = s.reduce((a, v) => a + (v - mean) ** 2, 0) || 1;
let best = { quality: -1, thr: mean }, left = 0;
for (let i = 1; i < n; i++) {
left += s[i - 1];
const m0 = left / i, m1 = (total - left) / (n - i);
const q = (i * (n - i) * (m0 - m1) ** 2) / n / tv;
if (q > best.quality) best = { quality: q, thr: (s[i - 1] + s[i]) / 2 };
}
return best;
}
function solve(A, B) {
const n = B.length;
for (let i = 0; i < n; i++) {
let p = i;
for (let r = i + 1; r < n; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
if (Math.abs(A[i][i]) < 1e-12) return null;
for (let r = 0; r < n; r++) if (r !== i) {
const f = A[r][i] / A[i][i];
for (let k = i; k < n; k++) A[r][k] -= f * A[i][k];
B[r] -= f * B[i];
}
}
return B.map((b, i) => b / A[i][i]);
}
function otsu(vals) {
const hist = new Float64Array(256);
for (const v of vals) hist[Math.max(0, Math.min(255, v | 0))]++;
let total = 0, sum = 0;
for (let i = 0; i < 256; i++) { total += hist[i]; sum += i * hist[i]; }
let wb = 0, sb = 0, best = 0, thr = 128;
for (let i = 0; i < 256; i++) {
wb += hist[i];
if (!wb || wb === total) continue;
sb += i * hist[i];
const mb = sb / wb, mf = (sum - sb) / (total - wb), v = wb * (total - wb) * (mb - mf) ** 2;
if (v > best) { best = v; thr = i; }
}
return thr;
}
// candidate center discs: solid dark elliptic blobs. returns [{ cx, cy, A }] in image pixels,
// A maps code space (center disc radius CENTER) onto the ellipse, rotation left free
export function locate(img, opts = {}) {
const f = Math.max(1, Math.ceil(Math.max(img.w, img.h) / (opts.maxDim || 480)));
const w = Math.floor(img.w / f), h = Math.floor(img.h / f), small = new Float32Array(w * h);
for (let y = 0; y < h; y++) for (let x = 0; x < w; x++) {
let s = 0;
for (let dy = 0; dy < f; dy++) for (let dx = 0; dx < f; dx++) s += img.g[(y * f + dy) * img.w + x * f + dx];
small[y * w + x] = s / (f * f);
}
const thr = otsu(small);
const label = new Int32Array(w * h).fill(-1), cands = [];
const stack = [];
for (let start = 0; start < w * h; start++) {
if (label[start] !== -1 || small[start] > thr) continue;
// flood fill one dark component, keep per-row extents
const id = cands.length, rows = new Map();
let count = 0;
label[start] = id; stack.push(start);
while (stack.length) {
const i = stack.pop(), x = i % w, y = (i / w) | 0;
count++;
const r = rows.get(y);
if (r) { if (x < r[0]) r[0] = x; if (x > r[1]) r[1] = x; } else rows.set(y, [x, x]);
for (const j of [i - 1, i + 1, i - w, i + w]) {
if (j < 0 || j >= w * h || label[j] !== -1 || small[j] > thr) continue;
if ((j === i - 1 && x === 0) || (j === i + 1 && x === w - 1)) continue;
label[j] = id; stack.push(j);
}
}
cands.push(null);
if (count < 30 || rows.size < 6) continue;
// moments of the row-filled shape, so the light logo inside doesn't count as holes
let m0 = 0, mx = 0, my = 0, mxx = 0, myy = 0, mxy = 0;
for (const [y, [x0, x1]] of rows) {
const n = x1 - x0 + 1, sx = ((x0 + x1) * n) / 2, sxx = (x1 * (x1 + 1) * (2 * x1 + 1) - (x0 - 1) * x0 * (2 * x0 - 1)) / 6;
m0 += n; mx += sx; my += y * n; mxx += sxx; myy += y * y * n; mxy += y * sx;
}
const ux = mx / m0, uy = my / m0;
const cxx = mxx / m0 - ux * ux + 1 / 12, cyy = myy / m0 - uy * uy + 1 / 12, cxy = mxy / m0 - ux * uy;
const tr = cxx + cyy, dt = Math.sqrt(Math.max(0, ((cxx - cyy) / 2) ** 2 + cxy * cxy));
const l1 = tr / 2 + dt, l2 = tr / 2 - dt;
if (l2 <= 0) continue;
const a = 2 * Math.sqrt(l1), b = 2 * Math.sqrt(l2);
const fill = m0 / (Math.PI * a * b), solidity = count / m0;
if (fill < 0.86 || fill > 1.14 || solidity < 0.5 || b / a < 0.38 || b < 5) continue;
const phi = 0.5 * Math.atan2(2 * cxy, cxx - cyy);
const c = Math.cos(phi), s = Math.sin(phi);
const k1 = (a * f) / CENTER, k2 = (b * f) / CENTER;
cands[id] = { cx: (ux + 0.5) * f - 0.5, cy: (uy + 0.5) * f - 0.5, A: [c * k1, -s * k2, s * k1, c * k2], area: m0 };
}
return cands.filter(Boolean).sort((p, q) => q.area - p.area).slice(0, opts.max || 4);
}
// the rough ellipse from the center disc is a bit off, and more so as the radius grows.
// the rings themselves are the better reference: find their dark bands along rays,
// fit one concentric ellipse family, undo center/scale/shear
function refine(S) {
const rows = [];
const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
const prof = [];
for (let r = r0; r <= r1 + 1e-9; r += dr) prof.push(S(r * dx, r * dy));
if (prof.some(Number.isNaN)) continue;
const sorted = [...prof].sort((a, b) => a - b);
const bg = sorted[Math.floor(sorted.length * 0.9)], lo = sorted[0];
if (bg - lo < 15) continue;
RADII.forEach((R) => {
const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr);
let m = -1;
for (let j = Math.max(1, c - wdw); j <= Math.min(prof.length - 2, c + wdw); j++) if (m < 0 || prof[j] < prof[m]) m = j;
if (m <= 0 || m >= prof.length - 1) return;
// a ray through a gap or a pale dash has no real dip, skip it
if (bg - prof[m] < 0.4 * (bg - lo)) return;
const a = prof[m - 1], b = prof[m], cc = prof[m + 1], den = a - 2 * b + cc;
const off = den > 0 ? (0.5 * (a - cc)) / den : 0;
const r = r0 + (m + Math.max(-1, Math.min(1, off))) * dr;
const x = r * dx, y = r * dy;
rows.push([x * x, x * y, y * y, x, y, 1, R * R]);
});
}
if (rows.length < 80) return null;
const N = Array.from({ length: 6 }, () => new Array(6).fill(0)), V = new Array(6).fill(0);
for (const row of rows) for (let i = 0; i < 6; i++) { V[i] += row[i] * row[6]; for (let j = 0; j < 6; j++) N[i][j] += row[i] * row[j]; }
const sol = solve(N, V);
if (!sol) return null;
const [a, b, c, d, e] = sol;
if (!(a > 0 && a * c - (b * b) / 4 > 0)) return null;
const x0 = (-d * 2 * c + e * b) / (4 * a * c - b * b), y0 = (-e * 2 * a + d * b) / (4 * a * c - b * b);
const p = Math.sqrt(a), q = b / 2 / p, s = Math.sqrt(c - q * q);
if (!(s > 0) || Math.hypot(x0, y0) > 0.2 || Math.abs(Math.log(p * s)) > 0.35) return null;
const i11 = 1 / p, i12 = -q / (p * s), i22 = 1 / s;
return (x, y) => S(x0 + i11 * x + i12 * y, y0 + i22 * y);
}
// ---- perspective from two concentric circles ----
// images of concentric circles C1, C2 are conics Q1, Q2. the pencil Q1 - l*Q2 holds a rank-1 member,
// the doubled vanishing line. knowing that line undoes the projective part, the rest is affine.
function jacobi(M) {
// eigen decomposition of a small symmetric matrix
const n = M.length, A = M.map((r) => [...r]), V = Array.from({ length: n }, (_, i) => Array.from({ length: n }, (_, j) => +(i === j)));
for (let sweep = 0; sweep < 60; sweep++) {
let off = 0;
for (let i = 0; i < n; i++) for (let j = i + 1; j < n; j++) off += A[i][j] * A[i][j];
if (off < 1e-22) break;
for (let p = 0; p < n; p++) for (let q = p + 1; q < n; q++) {
if (Math.abs(A[p][q]) < 1e-30) continue;
const th = (A[q][q] - A[p][p]) / (2 * A[p][q]);
const t = Math.sign(th || 1) / (Math.abs(th) + Math.sqrt(th * th + 1)), c = 1 / Math.sqrt(t * t + 1), s = t * c;
for (let k = 0; k < n; k++) {
const akp = A[k][p], akq = A[k][q];
A[k][p] = c * akp - s * akq; A[k][q] = s * akp + c * akq;
}
for (let k = 0; k < n; k++) {
const apk = A[p][k], aqk = A[q][k];
A[p][k] = c * apk - s * aqk; A[q][k] = s * apk + c * aqk;
}
for (let k = 0; k < n; k++) {
const vkp = V[k][p], vkq = V[k][q];
V[k][p] = c * vkp - s * vkq; V[k][q] = s * vkp + c * vkq;
}
}
}
return { values: A.map((r, i) => r[i]), vectors: V };
}
function fitConic(pts) {
// algebraic fit, smallest eigenvector of the scatter matrix (points already normalized)
if (pts.length < 12) return null;
const S = Array.from({ length: 6 }, () => new Array(6).fill(0));
for (const [x, y] of pts) {
const r = [x * x, x * y, y * y, x, y, 1];
for (let i = 0; i < 6; i++) for (let j = 0; j < 6; j++) S[i][j] += r[i] * r[j];
}
const { values, vectors } = jacobi(S);
let k = 0;
for (let i = 1; i < 6; i++) if (values[i] < values[k]) k = i;
const [a, b, c, d, e, f] = vectors.map((row) => row[k]);
return [[a, b / 2, d / 2], [b / 2, c, e / 2], [d / 2, e / 2, f]];
}
const det3 = (m) => m[0][0] * (m[1][1] * m[2][2] - m[1][2] * m[2][1]) - m[0][1] * (m[1][0] * m[2][2] - m[1][2] * m[2][0]) + m[0][2] * (m[1][0] * m[2][1] - m[1][1] * m[2][0]);
const sub3 = (A, B, l) => A.map((r, i) => r.map((v, j) => v - l * B[i][j]));
function inv3(m) {
const d = det3(m);
if (Math.abs(d) < 1e-30) return null;
const c = (i, j) => {
const r = [0, 1, 2].filter((k) => k !== i), q = [0, 1, 2].filter((k) => k !== j);
return ((i + j) % 2 ? -1 : 1) * (m[r[0]][q[0]] * m[r[1]][q[1]] - m[r[0]][q[1]] * m[r[1]][q[0]]);
};
return [0, 1, 2].map((i) => [0, 1, 2].map((j) => c(j, i) / d));
}
const mul3 = (A, B) => A.map((r) => [0, 1, 2].map((j) => r[0] * B[0][j] + r[1] * B[1][j] + r[2] * B[2][j]));
const tr3 = (A) => [0, 1, 2].map((i) => [0, 1, 2].map((j) => A[j][i]));
function cubicRoots(a, b, c, d) {
// real roots of a x^3 + b x^2 + c x + d
b /= a; c /= a; d /= a;
const p = c - (b * b) / 3, q = (2 * b * b * b) / 27 - (b * c) / 3 + d, disc = (q * q) / 4 + (p * p * p) / 27;
if (disc > 0) {
const u = Math.cbrt(-q / 2 + Math.sqrt(disc)), v = Math.cbrt(-q / 2 - Math.sqrt(disc));
// near a double root the pair turns complex with noise: report its real part twice
return [u + v - b / 3, -(u + v) / 2 - b / 3, -(u + v) / 2 - b / 3];
}
const r = 2 * Math.sqrt(-p / 3), phi = Math.acos(Math.max(-1, Math.min(1, (3 * q) / (p * r))));
return [0, 1, 2].map((k) => r * Math.cos(phi / 3 - (2 * Math.PI * k) / 3) - b / 3);
}
// image points on the center disc edge and on each ring, following rays of the rough affine map
function edgePoints(img, cand) {
const [a11, a12, a21, a22] = cand.A;
const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y];
const at = (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
const disc = [], rings = RADII.map(() => []), rays = 160;
for (let i = 0; i < rays; i++) {
const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi);
// disc edge: strongest dark-to-light step between 0.42 and 0.8
let best = 0, br = 0;
const prof = [];
for (let r = 0.4; r <= 0.82; r += 0.005) prof.push(at(r * dx, r * dy));
if (!prof.some(Number.isNaN)) {
for (let j = 2; j < prof.length - 2; j++) {
const gstep = prof[j + 2] - prof[j - 2];
if (gstep > best) { best = gstep; br = 0.4 + j * 0.005; }
}
if (best > 20) disc.push(map(br * dx, br * dy));
}
// rings: darkest point around each radius, only when it is a clear dip (a dark dash)
RADII.forEach((R, k) => {
const op = [], span = 0.07;
for (let r = R - span; r <= R + span + 1e-9; r += 0.004) op.push(at(r * dx, r * dy));
if (op.some(Number.isNaN)) return;
let m = 0;
for (let j = 1; j < op.length; j++) if (op[j] < op[m]) m = j;
const edge = Math.max(op[0], op[op.length - 1]);
if (m > 1 && m < op.length - 2 && edge - op[m] > 35) {
const a = op[m - 1], b = op[m], c = op[m + 1], den = a - 2 * b + c;
const off = den > 0 ? (0.5 * (a - c)) / den : 0;
const r = R - span + (m + off) * 0.004;
rings[k].push(map(r * dx, r * dy));
}
});
}
return { disc, rings };
}
// center of a conic (3x3 symmetric), in its own coordinates
function conicCenter(Q) {
const d = Q[0][0] * Q[1][1] - Q[0][1] * Q[1][0];
if (Math.abs(d) < 1e-18) return null;
return [-(Q[1][1] * Q[0][2] - Q[0][1] * Q[1][2]) / d, -(-Q[1][0] * Q[0][2] + Q[0][0] * Q[1][2]) / d];
}
function nelderMead(f, x0, step, iters) {
let pts = [x0, [x0[0] + step, x0[1]], [x0[0], x0[1] + step]].map((x) => ({ x, v: f(x) }));
for (let it = 0; it < iters; it++) {
pts.sort((a, b) => a.v - b.v);
const [b, g, w] = pts, c = [(b.x[0] + g.x[0]) / 2, (b.x[1] + g.x[1]) / 2];
const at = (t) => [c[0] + t * (w.x[0] - c[0]), c[1] + t * (w.x[1] - c[1])];
const r = { x: at(-1) }; r.v = f(r.x);
if (r.v < b.v) { const e = { x: at(-2) }; e.v = f(e.x); pts[2] = e.v < r.v ? e : r; }
else if (r.v < g.v) pts[2] = r;
else { const k = { x: at(0.5) }; k.v = f(k.x); if (k.v < w.v) pts[2] = k; else pts = [b, ...[g, w].map((p) => { const x = [(p.x[0] + b.x[0]) / 2, (p.x[1] + b.x[1]) / 2]; return { x, v: f(x) }; })]; }
}
pts.sort((a, b) => a.v - b.v);
return pts[0].x;
}
// projective map code space -> image from the two conics, or null
export let lastProjective = null;
function projective(img, cand) {
const { disc, rings } = edgePoints(img, cand);
const outer = rings[rings.length - 1];
lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' };
if (disc.length < 40 || outer.length < 30) return null;
// normalize coordinates for a well conditioned fit
const all = [disc, ...rings].flat();
const mx = all.reduce((s, p) => s + p[0], 0) / all.length, my = all.reduce((s, p) => s + p[1], 0) / all.length;
const sc = Math.sqrt(all.reduce((s, p) => s + (p[0] - mx) ** 2 + (p[1] - my) ** 2, 0) / all.length) || 1;
const nrm = (p) => [(p[0] - mx) / sc, (p[1] - my) / sc];
const Q1 = fitConic(disc.map(nrm)), Q2 = fitConic(outer.map(nrm));
if (!Q1 || !Q2) return null;
// for concentric circles C1 C2^-1 = diag(1, 1, r1^2/r2^2): its simple eigenvalue belongs to the
// line at infinity. in the image that eigenvector of Q1 Q2^-1 is the vanishing line (stable, unlike the double one)
const Q2i = inv3(Q2);
if (!Q2i) return null;
const N = mul3(Q1, Q2i);
const tr = N[0][0] + N[1][1] + N[2][2];
const minors = N[0][0] * N[1][1] - N[0][1] * N[1][0] + N[0][0] * N[2][2] - N[0][2] * N[2][0] + N[1][1] * N[2][2] - N[1][2] * N[2][1];
const roots = cubicRoots(1, -tr, minors, -det3(N));
let mu = roots[0], gap = -1;
for (let i = 0; i < 3; i++) {
const g = Math.min(...roots.filter((_, j) => j !== i).map((r) => Math.abs(r - roots[i])));
if (g > gap) { gap = g; mu = roots[i]; }
}
lastProjective.roots = roots; lastProjective.stage = 'roots';
// left eigenvector: l^T (N - mu I) = 0, so l is orthogonal to the columns of (N - mu I)
const Mt = tr3(sub3(N, [[1, 0, 0], [0, 1, 0], [0, 0, 1]], mu));
const cross = (u, v) => [u[1] * v[2] - u[2] * v[1], u[2] * v[0] - u[0] * v[2], u[0] * v[1] - u[1] * v[0]];
let l = null, ln = 0;
for (const [i, j] of [[0, 1], [0, 2], [1, 2]]) {
const c = cross(Mt[i], Mt[j]), n = Math.hypot(...c);
if (n > ln) { ln = n; l = c; }
}
if (!l || Math.abs(l[2]) < 1e-9) return null;
l = l.map((v) => v / l[2]);
lastProjective.l = l; lastProjective.stage = 'line';
// rectify: P maps the vanishing line to infinity
const P = [[1, 0, 0], [0, 1, 0], l];
const Pi = inv3(P);
if (!Pi) return null;
const Q1r = mul3(tr3(Pi), mul3(Q1, Pi));
// Q1r is now an ellipse: x^T M x + 2 g.x + f = 0
const M = [[Q1r[0][0], Q1r[0][1]], [Q1r[1][0], Q1r[1][1]]], g = [Q1r[0][2], Q1r[1][2]], f = Q1r[2][2];
const dm = M[0][0] * M[1][1] - M[0][1] * M[1][0];
if (Math.abs(dm) < 1e-18) return null;
const c0 = [-(M[1][1] * g[0] - M[0][1] * g[1]) / dm, -(-M[1][0] * g[0] + M[0][0] * g[1]) / dm];
const kk = -(f + g[0] * c0[0] + g[1] * c0[1]);
// (x-c0)^T (M/kk) (x-c0) = 1 is the disc: scale so it becomes radius CENTER
let a = M[0][0] / kk, b = M[0][1] / kk, c = M[1][1] / kk;
if (a < 0) { a = -a; b = -b; c = -c; }
lastProjective.ellipse = [a, b, c]; lastProjective.stage = 'ellipse';
if (!(a > 0 && a * c - b * b > 0)) return null;
lastProjective.stage = 'ok';
const p = Math.sqrt(a), q = b / p, s = Math.sqrt(c - q * q);
// affine from code space (radius CENTER) into the rectified plane: x = c0 + B t, B = (A^-1) / CENTER
const B = [[1 / p / CENTER, -q / (p * s) / CENTER], [0, 1 / s / CENTER]];
const map = (x, y) => {
const u = c0[0] + B[0][0] * x + B[0][1] * y, v = c0[1] + B[1][1] * y;
const w = Pi[2][0] * u + Pi[2][1] * v + Pi[2][2];
const X = (Pi[0][0] * u + Pi[0][1] * v + Pi[0][2]) / w, Y = (Pi[1][0] * u + Pi[1][1] * v + Pi[1][2]) / w;
return [X * sc + mx, Y * sc + my];
};
lastProjective.map = map;
return (x, y) => { const [u, v] = map(x, y); return bilinear(img, u, v); };
}
// reads one candidate. returns { token, theta, score, scale } or { token: null, ... } or null.
// tries the projective geometry (better under tilt) and the plain affine one (safer on soft frames)
export function decodeAt(img, cand, opts = {}) {
const [a11, a12, a21, a22] = cand.A;
const affine = (x, y) => bilinear(img, cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y);
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean);
let best = null;
for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0)) || S0;
const r = readRings(S, opts);
if (r && r.token) return r;
if (r && (!best || r.score > best.score)) best = r;
}
return best;
}
function readRings(S, opts) {
const minScore = opts.minScore ?? 0.8;
const n0 = RING_SECTORS[0], step0 = (2 * Math.PI) / n0;
const syncAt = (theta, scale) => {
const vals = [];
for (let j = 0; j < n0; j++) vals.push(sector(S, RADII[0] * scale, sectorAngle(theta, j, n0), step0));
return vals.some(Number.isNaN) ? null : { score: corr(vals, SYNC_BITS), theta, scale, vals };
};
// coarse pass over the full turn (no rotational symmetry), then a fine pass around the best hits.
// ~5x fewer samples than a dense search, which matters on low-end phones
const coarse = [];
for (const scale of opts.scales || [0.96, 1.0, 1.04]) {
for (let t = 0; t < 72; t++) {
const r = syncAt((t / 72) * 2 * Math.PI, scale);
if (!r) return null;
coarse.push(r);
}
}
coarse.sort((p, q) => q.score - p.score);
let best = null;
for (const c of coarse.slice(0, 3)) {
for (const ds of [-0.02, 0, 0.02]) for (let dt = -10; dt <= 10; dt++) {
const r = syncAt(c.theta + (dt * 0.5 * Math.PI) / 180, c.scale + ds);
if (r && (!best || r.score > best.score)) best = r;
}
}
// weak sync means we're not looking at a ring code (or a bad frame): don't let rs "fix" noise
if (!best || best.score < minScore) return best ? { token: null, ...best } : null;
const dark = [], light = [];
best.vals.forEach((v, j) => (SYNC_BITS[j] ? dark : light).push(v));
const md = dark.reduce((x, y) => x + y) / dark.length, ml = light.reduce((x, y) => x + y) / light.length;
if (ml - md < 12) return { token: null, ...best };
const bits = [];
for (let k = 1; k < RING_SECTORS.length; k++) {
// nudge scale and rotation per ring (perspective is only approximated) and keep the cleanest split
const n = RING_SECTORS[k], step = (2 * Math.PI) / n;
let pick = null;
for (const ds of [-0.03, -0.015, 0, 0.015, 0.03]) for (const dt of [-0.22, 0, 0.22]) {
const r = RADII[k] * best.scale * (1 + ds), vals = [];
for (let j = 0; j < n; j++) vals.push(sector(S, r, sectorAngle(best.theta + dt * step, j, n), step));
if (vals.some(Number.isNaN)) continue;
const sp = split(vals);
if (!pick || sp.quality > pick.quality) pick = { ...sp, vals };
}
if (!pick) return { token: null, ...best };
for (const v of pick.vals) bits.push(v < pick.thr ? 1 : 0);
}
const msg = rsDecode(bytesFromBits(bits));
return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null };
}
// whole frame: find center discs, read the first one that yields a valid token
export function decodeFrame(img, opts = {}) {
const cands = locate(img, opts);
let last = null;
for (const c of cands) {
const r = decodeAt(img, c, opts);
if (r && r.token) return { ...r, cand: c, found: cands.length };
last = r || last;
}
return { token: null, found: cands.length, score: last?.score ?? null };
}
+159
View File
@@ -0,0 +1,159 @@
// synthetic camera frames of a projected ring code: a washed-out screen in a room, seen by a phone sensor
import { render, DISC } from "/static/js/ringcode.js";
import { render as renderV1 } from "/static/ringlab/ringcode_v1.js";
// v1: draw the code as it was before the far-reading work, for baselines
export const design = { v1: false };
export function lcg(seed) {
let s = (seed >>> 0) || 1;
return () => ((s = (Math.imul(s, 1103515245) + 12345) & 0x7fffffff) / 0x7fffffff);
}
// 8 coefs of the homography sending src[i] to dst[i]
function homography(src, dst) {
const A = [], B = [];
for (let i = 0; i < 4; i++) {
const [x, y] = src[i], [u, v] = dst[i];
A.push([x, y, 1, 0, 0, 0, -u * x, -u * y]); B.push(u);
A.push([0, 0, 0, x, y, 1, -v * x, -v * y]); B.push(v);
}
for (let i = 0; i < 8; i++) {
let p = i;
for (let r = i + 1; r < 8; r++) if (Math.abs(A[r][i]) > Math.abs(A[p][i])) p = r;
[A[i], A[p]] = [A[p], A[i]]; [B[i], B[p]] = [B[p], B[i]];
for (let r = 0; r < 8; r++) if (r !== i) { const f = A[r][i] / A[i][i]; for (let k = i; k < 8; k++) A[r][k] -= f * A[i][k]; B[r] -= f * B[i]; }
}
return B.map((b, i) => b / A[i][i]);
}
const applyH = (h, x, y) => { const w = h[6] * x + h[7] * y + 1; return [(h[0] * x + h[1] * y + h[2]) / w, (h[3] * x + h[4] * y + h[5]) / w]; };
export function makeRoom(W, H, kind, rnd) {
const c = document.createElement("canvas"); c.width = W; c.height = H;
const ctx = c.getContext("2d");
// dark room: lights off for the projector. bright: daylight, full range clutter around the screen
const lmax = kind === "dark" ? 28 : 95, lmin = kind === "dark" ? 2 : 15;
const L = () => lmin + rnd() * (lmax - lmin);
const g = ctx.createLinearGradient(0, 0, W, H);
g.addColorStop(0, `hsl(${rnd() * 360}, 15%, ${L()}%)`); g.addColorStop(1, `hsl(${rnd() * 360}, 20%, ${L()}%)`);
ctx.fillStyle = g; ctx.fillRect(0, 0, W, H);
const k = W / 960;
for (let i = 0; i < 22; i++) {
ctx.fillStyle = `hsl(${rnd() * 360}, ${rnd() * 40}%, ${L()}%)`;
const t = rnd();
if (t < 0.4) ctx.fillRect(rnd() * W, rnd() * H, (20 + rnd() * 200) * k, (10 + rnd() * 120) * k);
else if (t < 0.65) { ctx.beginPath(); ctx.arc(rnd() * W, rnd() * H, (6 + rnd() * 60) * k, 0, 7); ctx.fill(); } // decoy discs (heads, lamps)
else if (t < 0.8) { ctx.font = `${(14 + rnd() * 40) * k}px system-ui`; ctx.fillText("Assemblée générale 2026", rnd() * W, rnd() * H); }
else { ctx.lineWidth = (2 + rnd() * 10) * k; ctx.strokeStyle = ctx.fillStyle; ctx.beginPath(); ctx.moveTo(rnd() * W, rnd() * H); ctx.lineTo(rnd() * W, rnd() * H); ctx.stroke(); }
}
return c;
}
// the projector page around the code: light page, title, the small entry qr, a few text lines
function page(pw, ph, d, t, rnd) {
const c = document.createElement("canvas"); c.width = pw; c.height = ph;
const ctx = c.getContext("2d", { willReadFrequently: true });
ctx.fillStyle = "#f5f6fa"; ctx.fillRect(0, 0, pw, ph);
const cx = pw * 0.36, cy = ph * 0.54, unit = (d / 2 / DISC);
if (!t.nocode) (design.v1 ? renderV1 : render)(ctx, cx, cy, unit, t.theta, t.bits, t.anim, t.fade || null);
ctx.fillStyle = "#1c2036";
ctx.font = `700 ${d * 0.11}px system-ui`; ctx.fillText("Inscription", pw * 0.66, ph * 0.2);
ctx.font = `${d * 0.05}px system-ui`;
for (let i = 0; i < 3; i++) ctx.fillText("Ouvrez la page de vote", pw * 0.66, ph * (0.3 + i * 0.07));
const m = 25, q = d * 0.36, qx = pw * 0.68, qy = ph * 0.52, r2 = lcg(t.qseed || 7);
for (let i = 0; i < m; i++) for (let j = 0; j < m; j++) if (r2() < 0.5) ctx.fillRect(qx + (i * q) / m, qy + (j * q) / m, q / m + 0.5, q / m + 0.5);
if (t.nocode && t.decoy) {
// things a projector may show instead: a plain dark disc, a pie chart
ctx.beginPath(); ctx.arc(cx, cy, unit * (0.4 + rnd() * 0.8), 0, 7); ctx.fill();
if (t.decoy > 1) for (let i = 0; i < 5; i++) { ctx.lineWidth = unit * 0.1; ctx.strokeStyle = `rgba(28,32,54,${rnd()})`; ctx.beginPath(); ctx.arc(cx, cy, unit * (0.9 + i * 0.15), rnd() * 7, rnd() * 7); ctx.stroke(); }
}
// washed projection: raised black, lower white, colour cast. only the screen is affected
const [b0, w0] = t.wash || [0, 255], cast = t.cast || [1, 1, 1];
const id = ctx.getImageData(0, 0, pw, ph), px = id.data;
for (let i = 0; i < px.length; i += 4) for (let ch = 0; ch < 3; ch++) px[i + ch] = (b0 + (px[i + ch] / 255) * (w0 - b0)) * cast[ch];
ctx.putImageData(id, 0, 0);
return { canvas: c, id, cx, cy, unit };
}
// one sensor frame. t: W H frac tilt axis dist wash cast oblur pblur motion noise band gain dx dy theta bits anim fade
// returns { canvas, truth } where truth maps code space to pixel index coordinates of the frame
export function frame(room, t, rnd) {
const { W, H } = t, ss = 2;
const d = t.frac * W; // code disc diameter in sensor px
const sw = 2.3 * d, sh = 1.5 * d; // projected page in sensor px, before tilt
const P = page(Math.round(sw * ss), Math.round(sh * ss), d * ss, t, rnd);
const pw = P.canvas.width, ph = P.canvas.height;
const tl = (t.tilt * Math.PI) / 180, a = (t.axis * Math.PI) / 180, f = (t.dist || 3.5) * d;
// keep the code itself near the frame centre, the page hangs around it
const ox = W / 2 + (t.dx || 0) + (0.5 - 0.36) * sw, oy = H / 2 + (t.dy || 0) + (0.5 - 0.54) * sh;
const corner = (x, y) => {
const X = x * Math.cos(a) + y * Math.sin(a), Y = -x * Math.sin(a) + y * Math.cos(a);
const Y2 = Y * Math.cos(tl), Z2 = Y * Math.sin(tl);
const xr = X * Math.cos(a) - Y2 * Math.sin(a), yr = X * Math.sin(a) + Y2 * Math.cos(a), s = f / (f + Z2);
return [ox + xr * s, oy + yr * s];
};
const quad = [[-sw / 2, -sh / 2], [sw / 2, -sh / 2], [sw / 2, sh / 2], [-sw / 2, sh / 2]].map(([x, y]) => corner(x, y));
const src = [[0, 0], [pw, 0], [pw, ph], [0, ph]];
const inv = homography(quad, src), fwd = homography(src, quad);
const x0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[0])))), x1 = Math.min(W, Math.ceil(Math.max(...quad.map((p) => p[0]))));
const y0 = Math.max(0, Math.floor(Math.min(...quad.map((p) => p[1])))), y1 = Math.min(H, Math.ceil(Math.max(...quad.map((p) => p[1]))));
const bw = (x1 - x0) * ss, bh = (y1 - y0) * ss;
const scene = document.createElement("canvas"); scene.width = W; scene.height = H;
const sctx = scene.getContext("2d");
sctx.drawImage(room, 0, 0);
if (bw > 0 && bh > 0) {
// warp at 2x then box-downscale, so small codes are area-sampled instead of aliased
const B = document.createElement("canvas"); B.width = bw; B.height = bh;
const bctx = B.getContext("2d"), od = bctx.createImageData(bw, bh), s = P.id.data;
for (let Y = 0; Y < bh; Y++) for (let X = 0; X < bw; X++) {
const [pu, pv] = applyH(inv, x0 + (X + 0.5) / ss, y0 + (Y + 0.5) / ss), u = pu - 0.5, v = pv - 0.5, o = (Y * bw + X) * 4;
if (u >= 0 && v >= 0 && u < pw - 1 && v < ph - 1) {
const ix = u | 0, iy = v | 0, fx = u - ix, fy = v - iy, i = (iy * pw + ix) * 4;
for (let ch = 0; ch < 3; ch++) od.data[o + ch] = (s[i + ch] * (1 - fx) + s[i + 4 + ch] * fx) * (1 - fy) + (s[i + pw * 4 + ch] * (1 - fx) + s[i + pw * 4 + 4 + ch] * fx) * fy;
od.data[o + 3] = 255;
}
}
bctx.putImageData(od, 0, 0);
sctx.imageSmoothingQuality = "high";
sctx.drawImage(B, x0, y0, x1 - x0, y1 - y0);
}
const out = document.createElement("canvas"); out.width = W; out.height = H;
const octx = out.getContext("2d", { willReadFrequently: true });
// optical blur is angular (scales with sensor resolution), pixel softness is not
const sigma = Math.hypot((t.oblur || 0) * (W / 1280), t.pblur || 0);
octx.filter = `blur(${sigma}px) brightness(${t.gain || 1})`;
const [mx, my] = (t.motion || [0, 0]).map((v) => v * (W / 1280)), steps = Math.max(1, Math.ceil(Math.hypot(mx, my)));
for (let i = 0; i < steps; i++) {
const k = steps > 1 ? i / (steps - 1) - 0.5 : 0;
octx.globalAlpha = 1 / (i + 1);
octx.drawImage(scene, mx * k, my * k);
}
octx.globalAlpha = 1; octx.filter = "none";
if (t.noise || t.band) {
const id = octx.getImageData(0, 0, W, H), px = id.data, period = (t.bandPeriod || 90) * (H / 720), ph0 = rnd() * 7;
for (let y = 0, i = 0; y < H; y++) {
// rolling shutter vs projector/lamp flicker: horizontal brightness bands
const g = 1 + (t.band || 0) * Math.sin((y / period) * 2 * Math.PI + ph0);
for (let x = 0; x < W; x++, i += 4) {
const n = (rnd() + rnd() + rnd() - 1.5) * 2 * (t.noise || 0);
px[i] = px[i] * g + n; px[i + 1] = px[i + 1] * g + n; px[i + 2] = px[i + 2] * g + n;
}
}
octx.putImageData(id, 0, 0);
}
const truth = (x, y) => {
const [u, v] = applyH(fwd, P.cx + x * P.unit, P.cy + y * P.unit);
return [u - 0.5, v - 0.5];
};
return { canvas: out, truth, d };
}
// lossy video path of cheap phones: jpeg round trip
export async function jpeg(canvas, q) {
const img = new Image();
img.src = canvas.toDataURL("image/jpeg", q);
await img.decode();
const c = document.createElement("canvas"); c.width = canvas.width; c.height = canvas.height;
c.getContext("2d", { willReadFrequently: true }).drawImage(img, 0, 0);
return c;
}
+180 -27
View File
@@ -1,10 +1,13 @@
"""ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome, """ring code bench: renders codes with perspective, blur, washed contrast and clutter in headless chrome,
runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]""" runs the real decoder and prints read rates. usage: uv run python tools/ringbench.py [trials per cell]
env: SUITE=legacy,far,seq,neg (default all) PIPES=legacy,cap960,scan DIAG=legacy|native FAR_D=80,100 NEG=300
CPU=6 (slow phone) V1=1 (decoder and dash design from before the far-reading work, the baseline)"""
import asyncio import asyncio
import base64 import base64
import collections import collections
import itertools import itertools
import json import json
import math
import os import os
import random import random
import subprocess import subprocess
@@ -20,6 +23,7 @@ from cdp import Browser # noqa: E402
from rotatyvote import ringcode # noqa: E402 from rotatyvote import ringcode # noqa: E402
PORT = 8200 PORT = 8200
V1 = bool(os.environ.get("V1"))
rng = random.Random(11) rng = random.Random(11)
@@ -45,32 +49,86 @@ def trials(n):
return out return out
async def main(): def code(r):
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3 secret, slot = r.randbytes(32), r.randrange(1 << 36)
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"} return {"bits": ringcode.render_bits(secret, "abcdefgh", 500, slot), "token": ringcode.token(secret, "abcdefgh", 500, slot)}
server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try: # washed projector: (black level, white level) of the screen as the camera sees it
for _ in range(100): WASH = {0.45: (80, 195), 0.3: (105, 181)}
try: SENSORS = {1280: (1280, 720), 1920: (1920, 1080)}
httpx.get(f"http://127.0.0.1:{PORT}/api/config", timeout=0.5)
break
except httpx.HTTPError: def camera(r, d, contrast, blur, sensor):
await asyncio.sleep(0.1) """one phone looking at a projected code d px wide in a 1280 px frame, plus what a real room adds"""
b = Browser(9336) W, H = SENSORS[sensor]
await b.start() return {"W": W, "H": H, "d": d, "frac": d / 1280, "contrast": contrast, "wash": WASH[contrast], "blur": blur, "sensor": sensor,
p = await b.page(960, 720) # optical blur is angular, pixel softness (demosaic, video codec) is per sensor pixel
throttle = float(os.environ.get("CPU", "1")) "oblur": blur, "pblur": 0.6 + 0.2 * blur,
if throttle > 1: "cast": [r.uniform(0.9, 1.0), 1.0, r.uniform(0.95, 1.1)], "gain": r.uniform(0.85, 1.2),
# rough low-end phone: chrome devtools cpu slowdown factor "room": r.choice(["dark", "dark", "bright"]), "band": r.choice([0, 0, 0.06, 0.1]), "bandPeriod": r.uniform(40, 200),
await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle}) "noise": r.uniform(4, 8), "axis": r.uniform(0, 360), "dx": r.uniform(-250, 250) * W / 1280, "dy": r.uniform(-120, 120) * W / 1280,
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html") "theta": r.uniform(0, 6.283), "anim": r.uniform(0, 100), "qseed": r.randrange(1 << 20)}
for _ in range(50):
if await p.js("!!window.benchReady"):
break def far_trials(n):
await asyncio.sleep(0.1) r = random.Random(23)
out = []
sizes = [int(x) for x in os.environ.get("FAR_D", "80,100,120,150,180").split(",")]
for d, contrast, blur, tilt, sensor in itertools.product(sizes, [0.45, 0.3], [0.7, 1.5], [0, 20], [1280, 1920]):
for _ in range(n):
t = camera(r, d, contrast, blur, sensor)
m = r.uniform(0, 1.5), r.uniform(0, 6.283)
t.update(code(r), tilt=tilt, motion=[m[0] * math.cos(m[1]), m[0] * math.sin(m[1])], jpeg=r.choice([0, 0, 0.6]))
out.append(t)
return out
def neg_trials(n):
"""nothing to read: no code on the screen, bare dark discs, discs with pie-like arcs around"""
r = random.Random(31)
out = []
for i in range(n):
t = camera(r, r.choice([80, 120, 180, 300]), r.choice([0.45, 0.3]), r.choice([0.7, 1.5]), r.choice([1280, 1920]))
t.update(tilt=r.choice([0, 20]), nocode=True, decoy=i % 3)
out.append(t)
return out
def seqs(n):
r = random.Random(47)
out = []
for d, contrast, fps in itertools.product([60, 70, 80, 100, 120, 150], [0.45, 0.3], [15, 7]):
for _ in range(n):
s = camera(r, d, contrast, r.choice([0.7, 1.5]), 1920)
s.update(tilt=r.choice([0, 10, 20]), fps=fps, secs=6, interval=500, shake=r.uniform(0.3, 1.2),
tokens=[code(r) for _ in range(14)], t0=r.randrange(1 << 20) * 500 + r.uniform(0, 400))
out.append(s)
return out
def table(rows, keys, pipes):
for key in keys:
vals = sorted({r[key] for r in rows})
for p in pipes:
cells = []
for v in vals:
sub = [r for r in rows if r[key] == v]
cells.append(f"{v}: {100 * sum(r[p]['ok'] for r in sub) / len(sub):3.0f}%")
print(f" {key:9s}{p:7s}", " ".join(cells))
async def chunks(p, fn, key, items, cfg, size):
# cdp calls time out after 60 s
out = []
for i in range(0, len(items), size):
out += await p.js(f"{fn}({json.dumps({**cfg, key: items[i:i + size], 'seed': 1000 + i, 'v1': V1})})")
return out
async def run_legacy(p, n):
ts = trials(n) ts = trials(n)
res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4})})") res = await p.js(f"runBench({json.dumps({'trials': ts, 'keep': 4, 'v1': V1})})")
harsh = [r for r in res if r.get("harsh")] harsh = [r for r in res if r.get("harsh")]
print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}") print(f"harsh perspective (close-up, 25 deg): {sum(r['ok'] for r in harsh)}/{len(harsh)}")
codes = [r for r in res if not r.get("nocode") and not r.get("harsh")] codes = [r for r in res if not r.get("nocode") and not r.get("harsh")]
@@ -93,9 +151,104 @@ async def main():
for i, r in enumerate(res[:4]): for i, r in enumerate(res[:4]):
if r.get("png"): if r.get("png"):
(out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1])) (out / f"sample_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
async def run_far(p, n, pipes, diag):
ts = far_trials(n)
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes, "diag": diag, "keep": 3}, 10)
print(f"\n== far + washed projector, single frames ({len(res)} frames), d = code diameter in a 1280 px wide frame ==")
table(res, ("d", "contrast", "blur", "tilt", "sensor", "room"), pipes)
for pn in pipes:
ms = sorted(r[pn]["ms"] for r in res)
wrong = sum(1 for r in res if r[pn]["token"] and not r[pn]["ok"])
print(f" {pn}: read {100 * sum(r[pn]['ok'] for r in res) / len(res):.0f} %, ms/frame median {ms[len(ms) // 2]} p90 {ms[int(len(ms) * .9)]}, false tokens {wrong}")
if diag:
print(f" where {diag} resolution frames break (truth substituted stage by stage):")
for d in sorted({r["d"] for r in res}):
sub = [r["diag"] for r in res if r["d"] == d]
good = [x for x in sub if x["rank"] in range(4) and x.get("candOk")]
st = collections.Counter(x["stage"] + ("/" + x["loc"] if x["stage"] == "locate" else "") for x in sub if x not in good)
print(f" d {d}: ok {len(good)}/{len(sub)} fails by stage {dict(st)}"
f" bit errs with true geometry {sum(x['bitErr'] for x in sub) / len(sub):.1f} (ideal thr {sum(x['idealErr'] for x in sub) / len(sub):.1f})"
f" worst-ring d' {sum(min(x['dprime']) for x in sub) / len(sub):.1f} sync span {sum(x['span'] for x in sub) / len(sub):.0f} levels")
print(" bit errors with true geometry per decision rule, and bleed model (own, ring neighbours, adjacent rings, residual):")
for d in sorted({r["d"] for r in res}):
labs = [r["diag"]["lab"] for r in res if r["d"] == d and "isi" in r["diag"]["lab"]]
keys = [k for k in labs[0] if k != "isi"]
isi = [sum(x["isi"][i] for x in labs) / len(labs) for i in range(5)]
print(f" d {d}: " + " ".join(f"{k} {sum(x.get(k, 0) for x in labs) / len(labs):.1f}" for k in keys)
+ f" | own {isi[1]:.2f} ang {isi[2]:.2f} rad {isi[3]:.2f} resid {isi[4]:.2f}")
out = ROOT / "tools" / "bench_out"
out.mkdir(exist_ok=True)
for i, r in enumerate(res[:3]):
if r.get("png"):
(out / f"far_{i}.jpg").write_bytes(base64.b64decode(r["png"].split(",")[1]))
return res
async def run_neg(p, n, pipes):
ts = neg_trials(n)
res = await chunks(p, "runFar", "trials", ts, {"pipes": pipes}, 10)
print(f"\n== negatives ({len(res)} frames without a code) ==")
for pn in pipes:
print(f" {pn}: false tokens {sum(1 for r in res if r[pn]['token'])}")
async def run_seq(p, n, pipes):
ss = seqs(n)
res = await chunks(p, "runSeq", "seqs", ss, {"pipes": pipes}, 1)
print(f"\n== far sequences: 6 s = 12 tokens shown, 1920x1080 sensor, hand shake ({len(res)} sequences) ==")
for key in ("d", "contrast", "fps"):
for pn in pipes:
cells = []
for v in sorted({r[key] for r in res}):
sub = [r[pn] for r in res if r[key] == v]
done = sorted(x["first5"] for x in sub if x["first5"] is not None)
med = f"{done[len(done) // 2]:.1f}s" if done else "-"
cells.append(f"{v}: {sum(x['got'] for x in sub) / len(sub):4.1f} tok, 5 in 6s {100 * len(done) / len(sub):3.0f}% ({med})")
print(f" {key:9s}{pn:7s}", " ".join(cells))
for pn in pipes:
print(f" {pn}: false tokens {sum(r[pn]['false'] for r in res)}, ms/frame {sum(r[pn]['ms'] for r in res) / len(res):.1f}")
async def main():
n = int(sys.argv[1]) if len(sys.argv) > 1 else 3
suites = os.environ.get("SUITE", "legacy,far,seq,neg").split(",")
pipes = os.environ.get("PIPES", "legacy" if V1 else "scan").split(",")
env = {**os.environ, "PORT": str(PORT), "HOST": "127.0.0.1", "DB_PATH": "/tmp/rv-bench.db"}
server = subprocess.Popen([sys.executable, "-m", "rotatyvote"], cwd=ROOT, env=env,
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
try:
for _ in range(100):
try:
httpx.get(f"http://127.0.0.1:{PORT}/api/config", timeout=0.5)
break
except httpx.HTTPError:
await asyncio.sleep(0.1)
b = Browser(9336)
await b.start()
p = await b.page(960, 720)
throttle = float(os.environ.get("CPU", "1"))
if throttle > 1:
# rough low-end phone: chrome devtools cpu slowdown factor
await p.send("Emulation.setCPUThrottlingRate", {"rate": throttle})
await p.goto(f"http://127.0.0.1:{PORT}/static/ringlab/bench.html")
for _ in range(50):
if await p.js("!!window.benchReady"):
break
await asyncio.sleep(0.1)
if "legacy" in suites:
await run_legacy(p, n)
if "far" in suites:
await run_far(p, n, pipes, os.environ.get("DIAG"))
if "seq" in suites:
await run_seq(p, max(1, n // 2), pipes)
if "neg" in suites:
await run_neg(p, int(os.environ.get("NEG", "300")), pipes)
await b.close() await b.close()
finally: finally:
server.terminate() server.terminate()
asyncio.run(main()) if __name__ == "__main__":
asyncio.run(main())