import { readBarcodes } from 'zxing-wasm/reader'; import type { ReaderOptions } from 'zxing-wasm/reader'; import { normalizeIsbn } from '../shared/isbn.ts'; /** RGBA pixels, as from ImageData. Plain data so that this module runs in Node tests. */ export interface Pixels { data: Uint8ClampedArray | Uint8Array; width: number; height: number } export interface DecodeOutcome { isbn: string | null; other: string | null } // ---- image operations (grey, one byte per pixel) ------------------------------------------------------- export interface Grey { g: Uint8ClampedArray; w: number; h: number } export function toGrey(p: Pixels): Grey { const n = p.width * p.height, g = new Uint8ClampedArray(n), d = p.data; for (let i = 0, j = 0; i < n; i++, j += 4) g[i] = (d[j]! * 77 + d[j + 1]! * 151 + d[j + 2]! * 28) >> 8; return { g, w: p.width, h: p.height }; } /** Bilinear enlargement by a whole factor. */ export function upscale(s: Grey, k: number): Grey { if (k === 1) return s; const w = s.w * k, h = s.h * k, g = new Uint8ClampedArray(w * h); for (let y = 0; y < h; y++) { const fy = Math.max(0, (y + 0.5) / k - 0.5), y0 = Math.min(s.h - 1, Math.floor(fy)), y1 = Math.min(s.h - 1, y0 + 1), ty = fy - y0; for (let x = 0; x < w; x++) { const fx = Math.max(0, (x + 0.5) / k - 0.5), x0 = Math.min(s.w - 1, Math.floor(fx)), x1 = Math.min(s.w - 1, x0 + 1), tx = fx - x0; const a = s.g[y0 * s.w + x0]!, b = s.g[y0 * s.w + x1]!, c = s.g[y1 * s.w + x0]!, d = s.g[y1 * s.w + x1]!; g[y * w + x] = (a + (b - a) * tx) * (1 - ty) + (c + (d - c) * tx) * ty; } } return { g, w, h }; } /** Replace each pixel by the mean of the pixels within `r` rows above and below it (along the bars). */ export function rowAverage(s: Grey, r: number): Grey { const { w, h } = s, out = new Uint8ClampedArray(w * h); for (let x = 0; x < w; x++) { let sum = 0, lo = 0, hi = -1; // window [lo, hi] for (let y = 0; y < h; y++) { const nlo = Math.max(0, y - r), nhi = Math.min(h - 1, y + r); while (hi < nhi) { hi++; sum += s.g[hi * w + x]!; } while (lo < nlo) { sum -= s.g[lo * w + x]!; lo++; } out[y * w + x] = sum / (hi - lo + 1); } } return { g: out, w, h }; } /** Unsharp mask across the bars: sharpen horizontally only. */ export function sharpenAcross(s: Grey, radius: number, amount: number): Grey { const { w, h } = s, out = new Uint8ClampedArray(w * h); for (let y = 0; y < h; y++) { const row = y * w; let sum = 0, lo = 0, hi = -1; for (let x = 0; x < w; x++) { const nlo = Math.max(0, x - radius), nhi = Math.min(w - 1, x + radius); while (hi < nhi) { hi++; sum += s.g[row + hi]!; } while (lo < nlo) { sum -= s.g[row + lo]!; lo++; } const blur = sum / (hi - lo + 1), v = s.g[row + x]!; out[row + x] = v + amount * (v - blur); } } return { g: out, w, h }; } function toImage(s: Grey): Pixels { const n = s.w * s.h, data = new Uint8ClampedArray(n * 4); for (let i = 0, j = 0; i < n; i++, j += 4) { data[j] = data[j + 1] = data[j + 2] = s.g[i]!; data[j + 3] = 255; } return { data, width: s.w, height: s.h }; } /** Sum of squared horizontal and vertical differences: larger means sharper. Samples every second pixel. */ export function sharpness(p: Pixels): number { const g = toGrey(p); let e = 0; for (let y = 0; y < g.h - 1; y += 2) for (let x = 0; x < g.w - 1; x += 2) { const v = g.g[y * g.w + x]!, dx = g.g[y * g.w + x + 1]! - v, dy = g.g[(y + 1) * g.w + x]! - v; e += dx * dx + dy * dy; } return e; } // ---- variants ------------------------------------------------------------------------------------------ export const BASE: ReaderOptions = { formats: ['EAN13', 'UPCA'], tryHarder: true, tryDownscale: true, tryRotate: false, tryInvert: false, maxNumberOfSymbols: 2, }; export interface Variant { name: string; opts: ReaderOptions; prep: (g: Grey) => Grey } const rowSmooth = (g: Grey) => upscale(rowAverage(g, 6), 2); /** * Ordered by the synthetic hit rates in decode.test.ts (blur 0.8 px, noise): at 1.2 to 1.5 px per module only * the row-averaged and sharpened version reads, the plain crop reads from 2 px. Binarizers alternate: local * for uneven light, global for blur. */ export const VARIANTS: Variant[] = [ { name: 'rows+sharp2x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => sharpenAcross(rowSmooth(g), 3, 1.2) }, { name: 'rows2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: rowSmooth }, { name: 'crop', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g }, { name: 'up2x', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => upscale(g, 2) }, { name: 'up3x', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => upscale(g, 3) }, ]; /** For the whole frame, which is too big to enlarge: no upscaling. */ export const WHOLE_VARIANTS: Variant[] = [ { name: 'whole', opts: { ...BASE, binarizer: 'LocalAverage' }, prep: g => g }, { name: 'whole-rows', opts: { ...BASE, binarizer: 'GlobalHistogram' }, prep: g => sharpenAcross(rowAverage(g, 6), 1, 1) }, ]; function judge(codes: { text: string }[], into: DecodeOutcome): void { for (const c of codes) { const isbn = /^\d{13}$/.test(c.text) ? normalizeIsbn(c.text) : null; if (isbn) into.isbn ??= isbn; else into.other ??= c.text; } } async function tryVariant(g: Grey, v: Variant, extra: ReaderOptions, into: DecodeOutcome): Promise { judge(await readBarcodes(toImage(v.prep(g)) as ImageData, { ...v.opts, ...extra }), into); } export interface LiveState { round: number; cursor: number } export const newLiveState = (): LiveState => ({ round: 0, cursor: 0 }); /** Every FULL_EVERY-th live round looks at the whole frame instead of the crop. */ export const FULL_EVERY = 5; export const LIVE_BUDGET_MS = 80; const REST = VARIANTS.slice(1); /** Whether the next live round should be given the whole frame. */ export const wantsFull = (st: LiveState): boolean => st.round % FULL_EVERY === FULL_EVERY - 1; /** * One live attempt on one frame's pixels (the crop, or the whole frame on a full round). The first variant * always runs; the others are taken in turn until the time budget is spent, resuming where the last round * stopped, so that slow machines still get through every variant across frames. */ export async function decodeLive(p: Pixels, st: LiveState, now: () => number = () => performance.now()): Promise<{ out: DecodeOutcome; state: LiveState }> { const out: DecodeOutcome = { isbn: null, other: null }; const began = now(), g = toGrey(p); let cursor = st.cursor; if (wantsFull(st)) { for (const v of WHOLE_VARIANTS) if (!out.isbn) await tryVariant(g, v, {}, out); } else { await tryVariant(g, VARIANTS[0]!, {}, out); for (let i = 0; i < REST.length && !out.isbn && now() - began <= LIVE_BUDGET_MS; i++) { await tryVariant(g, REST[cursor]!, {}, out); cursor = (cursor + 1) % REST.length; } } return { out, state: { round: st.round + 1, cursor } }; } /** Everything we have on one frame, for the Capture burst: every variant, rotated too, crop then whole frame. */ export async function decodeThorough(crop: Pixels, whole: Pixels | null): Promise { const out: DecodeOutcome = { isbn: null, other: null }; for (const p of whole ? [crop, whole] : [crop]) { const g = toGrey(p); for (const v of p === crop ? VARIANTS : WHOLE_VARIANTS) { await tryVariant(g, v, { tryRotate: true, tryInvert: true }, out); if (out.isbn) return out; } } return out; } /** The pixels a variant would hand to the reader (exposed for the tuning test). */ export const toImageForTest = (p: Pixels, v: Variant): Pixels => toImage(v.prep(toGrey(p)));