Ring decoder: local tone split, sharpened crop, frame accumulation, crop scanner

This commit is contained in:
2026-08-16 19:22:24 +01:00
parent 418e7667e5
commit 05cfa36e5b
5 changed files with 265 additions and 26 deletions
+140 -21
View File
@@ -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) {
@@ -588,7 +594,7 @@ function ringDips(img, cand, span) {
return rings;
}
// projective map code space -> image from the two conics, or null
// projective map code space -> image coordinates from the two conics, or null
export let lastProjective = null;
function projective(img, cand) {
const span = cand.span || 200, disc = discEdge(img, cand, 160), rings = ringDips(img, cand, span);
@@ -654,19 +660,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 [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 span = cand.span || 200;
const maps = [opts.projective !== false && projective(img, cand), affine].filter(Boolean);
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, tc = cand;
if (opts.sharpen !== false && unit < 70) {
// small code: work on a sharpened crop
const half = Math.ceil(unit * (DISC + 0.25)) + 4;
const 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);
tc = { ...cand, cx: cand.cx - x0, cy: cand.cy - y0 };
}
const [a11, a12, a21, a22] = tc.A;
// 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 - (cand.cx - tc.cx), v - (cand.cy - tc.cy)); }),
(x, y) => bilinear(tone, tc.cx + a11 * x + a12 * y, tc.cy + a21 * x + a22 * y)].filter(Boolean);
let best = null;
for (const S0 of maps) {
const S = (opts.refine !== false && refine(S0, span)) || S0;
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;
@@ -701,12 +782,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 < Math.max(5, 0.055 * (opts.span || 200))) 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;
@@ -718,11 +800,15 @@ 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
@@ -732,10 +818,43 @@ export function decodeFrame(img, opts = {}) {
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
const gate = (token, now) => {
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)) { 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()) {
const d = decodeFrame(img, opts);
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)) token = null;
return { ...d, token, via };
},
};
}
// internals for the lab bench
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle };
export const _lab = { readRings, sector, bilinear, split, corr, sectorAngle, classify, tokenOf };
+53
View File
@@ -0,0 +1,53 @@
// 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, CROP / Math.max(w, h));
crop.width = Math.round(w * k); crop.height = Math.round(h * k);
cctx.drawImage(src, x0, y0, w, h, 0, 0, crop.width, crop.height);
const d = reader.read(grayOf(cctx.getImageData(0, 0, crop.width, crop.height)), now);
if (!d.cand) return null;
// only a blob with a sync ring keeps the crop alive, anything else falls back to the whole frame
const at = d.token || d.soft ? now : t.at ?? now - 500;
track = { cx: x0 + (d.cand.cx + 0.5) / k, cy: y0 + (d.cand.cy + 0.5) / k, unit: d.cand.r / CENTER / k, at };
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;
const k = Math.min(1, WIDE / sw);
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: 2 });
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 }, now);
if (d && d.token) return d;
last = d || last;
}
return last || { token: null, found: cands.length };
},
};
}