diff --git a/README.md b/README.md index 398845d..aa25820 100644 --- a/README.md +++ b/README.md @@ -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. - 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. -- 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 diff --git a/static/js/ringcode.js b/static/js/ringcode.js index 21055e2..0cf522d 100644 --- a/static/js/ringcode.js +++ b/static/js/ringcode.js @@ -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 export const CENTER = 0.62; 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 // 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 const ALPHA_DARK = [0.93, 1], ALPHA_LIGHT = [0.08, 0.19]; 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) -export function rsDecode(cw) { +// the whole corrected codeword, or null +function rsFix(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); + if (Math.max(...synd) === 0) return cw; let errLoc = [1], oldLoc = [1]; for (let i = 0; i < NSYM; i++) { const K = i + 1; @@ -100,7 +101,12 @@ export function rsDecode(cw) { }); 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); + return fixed; +} + +export function rsDecode(cw) { + const fixed = rsFix(cw); + return fixed && fixed.slice(0, cw.length - NSYM); } export function whitening(n) { @@ -261,58 +267,51 @@ function solve(A, B) { 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); +// dark blobs of one pyramid level that look like a filled ellipse. s = level px size in image px +function blobs(g, w, h, s, ratio, out) { + // dark = clearly under the brightest thing nearby. a washed projector keeps black/white around 0.6, + // and the disc always has its light surround within reach, whatever the room does around the screen + const T = 8, tw = Math.ceil(w / T), th = Math.ceil(h / T), tmax = new Float32Array(tw * th); 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 i = ((y / T) | 0) * tw + ((x / T) | 0), v = g[y * w + x]; + if (v > tmax[i]) tmax[i] = v; } - 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); - } + const dark = new Uint8Array(w * h); + for (let ty = 0; ty < th; ty++) for (let tx = 0; tx < tw; tx++) { + 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]; } - cands.push(null); - if (count < 30 || rows.size < 6) continue; + // 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++) { + if (!dark[start]) continue; + // flood fill one component, keep per-row extents + let sp = 0, count = 0, y0 = h, y1 = -1; + stack[sp++] = start; dark[start] = 0; id++; + while (sp) { + const i = stack[--sp], x = i % w, y = (i / w) | 0; + count++; + if (stamp[y] !== id) { stamp[y] = id; lo[y] = hi[y] = x; if (y < y0) y0 = y; if (y > y1) y1 = y; } + else if (x < lo[y]) lo[y] = x; else if (x > hi[y]) hi[y] = x; + if (x > 0 && dark[i - 1]) { dark[i - 1] = 0; stack[sp++] = i - 1; } + if (x < w - 1 && dark[i + 1]) { dark[i + 1] = 0; stack[sp++] = i + 1; } + if (y > 0 && dark[i - w]) { dark[i - w] = 0; stack[sp++] = i - w; } + if (y < h - 1 && dark[i + w]) { dark[i + w] = 0; stack[sp++] = i + w; } + } + if (count < 30 || y1 - y0 < 5) 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; + for (let y = y0; y <= y1; y++) { + 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; } const ux = mx / m0, uy = my / m0; @@ -322,19 +321,93 @@ export function locate(img, opts = {}) { 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; + 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 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 }; + const c = Math.cos(phi), sn = Math.sin(phi); + const k1 = (a * s) / CENTER, k2 = (b * s) / CENTER; + 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 rings themselves are the better reference: find their dark bands along rays, // fit one concentric ellipse family, undo center/scale/shear -function refine(S) { +function refine(S, span) { const rows = []; const rays = 160, r0 = 0.74, r1 = 1.48, dr = 0.005; for (let i = 0; i < rays; i++) { @@ -344,7 +417,7 @@ function refine(S) { 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; + if (bg - lo < 0.07 * span) continue; RADII.forEach((R) => { const c = Math.round((R - r0) / dr), wdw = Math.round(0.065 / dr); 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); } -// 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]; @@ -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]; } -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) }; })]; } +// image points on the center disc edge, following rays of the rough affine map +function discEdge(img, cand, rays) { + const [a11, a12, a21, a22] = cand.A, unit = Math.sqrt(Math.abs(a11 * a22 - a12 * a21)); + const map = (x, y) => [cand.cx + a11 * x + a12 * y, cand.cy + a21 * x + a22 * y]; + // about half a pixel per step, small discs don't need 85 samples per ray + const dr = Math.max(0.005, 0.5 / unit), pts = []; + for (let i = 0; i < rays; i++) { + const phi = (i / rays) * 2 * Math.PI, dx = Math.sin(phi), dy = -Math.cos(phi); + const prof = []; + 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; + } + if (bad || hi - lo < 10) continue; + // 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)); } - pts.sort((a, b) => a.v - b.v); - return pts[0].x; + 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; 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]; lastProjective = { disc: disc.length, rings: rings.map((r) => r.length), stage: 'points' }; if (disc.length < 40 || outer.length < 30) return null; @@ -573,19 +672,94 @@ function projective(img, cand) { return [X * sc + mx, Y * sc + my]; }; 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) 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 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); + // geometry comes from the plain image, tones from the sharpened one + 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; for (const S0 of maps) { - const S = (opts.refine !== false && refine(S0)) || S0; - const r = readRings(S, opts); + const S = (opts.refine !== false && refine(S0, span * (tone === img ? 1 : 2))) || S0; + const r = readRings(S, { ...opts, span }); if (r && r.token) return 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); + // 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; for (const c of coarse.slice(0, 3)) { 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 - 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 = []; 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 = []; + const out = { ...best, vals: undefined, token: null }; + 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++) { // 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; @@ -636,21 +813,68 @@ function readRings(S, opts) { 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); + if (!pick) return out; + all.push(...pick.vals); + for (const v of pick.vals) otsu.push(+(v < pick.thr)); } - const msg = rsDecode(bytesFromBits(bits)); - return { ...best, vals: undefined, bits: bits.join(""), token: msg ? tokenFromPayload(msg) : null }; + const c = classify(all); + 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 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; 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; + 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 }; diff --git a/static/js/ringscan.js b/static/js/ringscan.js new file mode 100644 index 0000000..8cfe225 --- /dev/null +++ b/static/js/ringscan.js @@ -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 }; + }, + }; +} diff --git a/static/js/vote.js b/static/js/vote.js index a49f5d5..a14d808 100644 --- a/static/js/vote.js +++ b/static/js/vote.js @@ -1,5 +1,5 @@ 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 DONE_KEY = `rv_done_${pid}`; @@ -74,20 +74,22 @@ async function startScanner() { function makeScanner(video, onToken, onOther) { let stream = null, running = false; const canvas = document.createElement("canvas"), ctx = canvas.getContext("2d", { willReadFrequently: true }); + const rings = makeRingScanner(); async function loop() { if (!running) return; const t0 = performance.now(); if (video.readyState >= 2 && video.videoWidth) { - // 960 px is plenty and keeps low-end phones near 7 fps - const k = Math.min(1, 960 / video.videoWidth); - canvas.width = Math.round(video.videoWidth * k); - canvas.height = Math.round(video.videoHeight * k); - 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))); + // 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); + canvas.width = Math.round(video.videoWidth * k); + canvas.height = Math.round(video.videoHeight * k); + ctx.drawImage(video, 0, 0, canvas.width, canvas.height); qrEngine ||= await window.QrScanner.createQrEngine(); 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?.(); } @@ -99,9 +101,13 @@ function makeScanner(video, onToken, onOther) { } return { 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({ - 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; await video.play(); running = true; diff --git a/static/ringlab/bench.html b/static/ringlab/bench.html index fa239b3..f32e165 100644 --- a/static/ringlab/bench.html +++ b/static/ringlab/bench.html @@ -5,6 +5,8 @@