diff --git a/src/server/app.test.ts b/src/server/app.test.ts index 419d1f8..6efe054 100644 --- a/src/server/app.test.ts +++ b/src/server/app.test.ts @@ -222,3 +222,30 @@ test('retry forgets the book\'s cached source responses', async () => { assert.equal(db.cache.get('ol-data:9780201835953'), 'body'); assert.equal(db.cache.get('loc-title:Other|X'), 'body'); }); + +test('debug capture: saves a PNG, keeps the newest 30, refuses other bodies', async () => { + const { mkdtempSync, readdirSync, rmSync } = await import('node:fs'); + const { tmpdir } = await import('node:os'); + const { join } = await import('node:path'); + const dir = mkdtempSync(join(tmpdir(), 'captures-')); + try { + const db = openDb(':memory:'); + const resolver = { resolve: async () => found, search: async () => [] }; + const jobs = createJobs({ db, resolver, onChange: () => {}, retryDelaysMs: [0], log: () => {} }); + const app = createApp({ + db, jobs, resolver, capturesDir: join(dir, 'captures'), + renderCardsPdf: async () => new Uint8Array(), renderCalibrationPdf: async () => new Uint8Array(), + classNames: () => ({ className: '', subclassName: '' }), + }); + const png: Uint8Array = new Uint8Array([0x89, 0x50, 0x4e, 0x47, 0x0d, 0x0a, 0x1a, 0x0a, 1, 2, 3]); + const post = (b: Uint8Array) => app.request('/api/debug/capture', { method: 'POST', body: b }); + const r = await post(png); + assert.equal(r.status, 200); + const j = await r.json() as { saved: string }; + assert.match(j.saved, /^capture-.*\.png$/); + assert.equal((await post(new Uint8Array([1, 2, 3, 4, 5, 6, 7, 8, 9]))).status, 400); + assert.equal((await post(new Uint8Array(8 * 1024 * 1024 + 1))).status, 413); + for (let i = 0; i < 35; i++) await post(png); + assert.equal(readdirSync(join(dir, 'captures')).length, 30); + } finally { rmSync(dir, { recursive: true, force: true }); } +}); diff --git a/src/server/app.ts b/src/server/app.ts index f2917dd..4524c7b 100644 --- a/src/server/app.ts +++ b/src/server/app.ts @@ -1,3 +1,5 @@ +import { mkdirSync, readdirSync, unlinkSync, writeFileSync } from 'node:fs'; +import { join } from 'node:path'; import { Hono } from 'hono'; import type { Context } from 'hono'; import type { Book, CardData, SearchResult, Settings } from '../shared/types.ts'; @@ -37,6 +39,8 @@ export interface AppDeps { renderCardsPdf: RenderCardsPdf; renderCalibrationPdf: RenderCalibrationPdf; classNames: ClassNames; events?: EventBus; + /** Where pictures the scanner failed to read are kept for tuning (the newest 30). */ + capturesDir?: string; } class HttpError extends Error { @@ -116,6 +120,25 @@ export function createApp(deps: AppDeps): Hono { return r; } + let captureSeq = 0; + const MAX_CAPTURE_BYTES = 8 * 1024 * 1024, KEEP_CAPTURES = 30; + app.post('/api/debug/capture', async (c) => { + const dir = deps.capturesDir; + if (!dir) throw new HttpError(404, 'Saving captures is not set up'); + const declared = Number(c.req.header('content-length') ?? 0); + if (declared > MAX_CAPTURE_BYTES) return c.json({ error: 'Picture too large' }, 413); + const bytes = new Uint8Array(await c.req.arrayBuffer()); + if (bytes.length > MAX_CAPTURE_BYTES) return c.json({ error: 'Picture too large' }, 413); + const isPng = bytes.length > 8 && [0x89, 0x50, 0x4e, 0x47].every((v, i) => bytes[i] === v); + if (!isPng) throw new HttpError(400, 'Expected a PNG picture'); + mkdirSync(dir, { recursive: true }); + const saved = `capture-${new Date().toISOString().replace(/[:.]/g, '-')}-${String(captureSeq++ % 10000).padStart(4, '0')}.png`; + writeFileSync(join(dir, saved), bytes); + const old = readdirSync(dir).filter((f) => /^capture-.*\.png$/.test(f)).sort().reverse().slice(KEEP_CAPTURES); + for (const f of old) { try { unlinkSync(join(dir, f)); } catch { /* already gone */ } } + return c.json({ saved }); + }); + app.post('/api/scan', async (c) => { const b = await body(c); const isbn = typeof b.isbn === 'string' ? normalizeIsbn(b.isbn) : null; diff --git a/src/server/main.ts b/src/server/main.ts index d7d4460..d169413 100644 --- a/src/server/main.ts +++ b/src/server/main.ts @@ -1,5 +1,5 @@ import { existsSync, readFileSync, statSync } from 'node:fs'; -import { extname, join, resolve as resolvePath } from 'node:path'; +import { dirname, extname, join, resolve as resolvePath } from 'node:path'; import { staticPath } from './static.ts'; import { serve } from '@hono/node-server'; import { openDb } from './db.ts'; @@ -19,13 +19,14 @@ const MIME: Record = { '.ico': 'image/x-icon', '.webmanifest': 'application/manifest+json', '.map': 'application/json', }; +const capturesDir = process.env.BOOKSORTER_CAPTURES ?? join(dirname(dbPath), 'captures'); const db = openDb(dbPath); const events = createEventBus(); const resolver = createResolver({ fetch: globalThis.fetch, cache: db.cache }); const jobs = createJobs({ db, resolver, onChange: (b) => events.emitBook(b), isTemporary: (e) => e instanceof TemporaryError, }); -const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events }); +const app = createApp({ port, db, jobs, resolver, renderCardsPdf, renderCalibrationPdf, classNames, events, capturesDir }); app.get('*', (c) => { if (!existsSync(join(webRoot, 'index.html'))) { diff --git a/src/web/decode.test.ts b/src/web/decode.test.ts new file mode 100644 index 0000000..23d0544 --- /dev/null +++ b/src/web/decode.test.ts @@ -0,0 +1,120 @@ +import { test, before } from 'node:test'; +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { createRequire } from 'node:module'; +import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'; +import { BASE, VARIANTS, toImageForTest, decodeLive, decodeThorough, newLiveState, rowAverage, sharpness, upscale } from './decode.ts'; +import type { Pixels } from './decode.ts'; + +before(async () => { + const wasm = readFileSync(createRequire(import.meta.url).resolve('zxing-wasm/reader').replace(/dist[\\/].*$/, 'dist/reader/zxing_reader.wasm')); + await prepareZXingModule({ overrides: { wasmBinary: wasm.buffer.slice(wasm.byteOffset, wasm.byteOffset + wasm.byteLength) as ArrayBuffer }, fireImmediately: true }); +}); + +// --- synthetic EAN-13 --------------------------------------------------------------------------------- +const L = ['0001101', '0011001', '0010011', '0111101', '0100011', '0110001', '0101111', '0111011', '0110111', '0001011']; +const G = ['0100111', '0110011', '0011011', '0100001', '0011101', '0111001', '0000101', '0010001', '0001001', '0010111']; +const R = ['1110010', '1100110', '1101100', '1000010', '1011100', '1001110', '1010000', '1000100', '1001000', '1110100']; +const PARITY = ['LLLLLL', 'LLGLGG', 'LLGGLG', 'LLGGGL', 'LGLLGG', 'LGGLLG', 'LGGGLL', 'LGLGLG', 'LGLGGL', 'LGGLGL']; + +function ean13Modules(code: string): number[] { + const d = [...code].map(Number), par = PARITY[d[0]!]!; + let s = '101'; + for (let i = 0; i < 6; i++) s += (par[i] === 'L' ? L : G)[d[i + 1]!]; + s += '01010'; + for (let i = 0; i < 6; i++) s += R[d[i + 7]!]; + s += '101'; + return [...s].map(Number); +} + +function rng(seed: number) { + let a = seed >>> 0; + const u = () => { a = (a + 0x6d2b79f5) >>> 0; let t = a; t = Math.imul(t ^ (t >>> 15), t | 1); t ^= t + Math.imul(t ^ (t >>> 7), t | 61); return ((t ^ (t >>> 14)) >>> 0) / 4294967296; }; + return { u, n: () => Math.sqrt(-2 * Math.log(u() || 1e-9)) * Math.cos(2 * Math.PI * u()) }; +} + +/** A crop-sized grey image with the barcode (quiet zones included) at `ppm` pixels per module, blurred and noisy. */ +function render(code: string, ppm: number, seed: number, W = 584, H = 388): Pixels { + const r = rng(seed), mods = ean13Modules(code), left = 9, total = 95 + 18; + const bw = total * ppm, bh = Math.round(ppm * 62); + const ox = (W - bw) / 2 + (r.u() - 0.5) * 20, oy = (H - bh) / 2 + (r.u() - 0.5) * 20; + const g = new Float32Array(W * H).fill(215); + for (let y = Math.max(0, Math.floor(oy)); y < Math.min(H, Math.floor(oy) + bh); y++) { + for (let x = 0; x < W; x++) { + // coverage of dark in this pixel [x, x+1) along the module axis + const a = (x - ox) / ppm - left, b = (x + 1 - ox) / ppm - left; + let dark = 0; + for (let m = Math.max(0, Math.floor(a)); m <= Math.min(94, Math.floor(b)); m++) { + if (mods[m]) dark += Math.min(b, m + 1) - Math.max(a, m); + } + g[y * W + x] = 215 - (215 - 35) * Math.min(1, dark / (b - a)); + } + } + // gaussian blur sigma 0.8, separable + const sigma = 0.8, rad = 3, k: number[] = []; + for (let i = -rad; i <= rad; i++) k.push(Math.exp(-(i * i) / (2 * sigma * sigma))); + const ks = k.reduce((a, b) => a + b, 0); + const tmp = new Float32Array(W * H), out = new Float32Array(W * H); + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + let s = 0; for (let i = -rad; i <= rad; i++) s += k[i + rad]! * g[y * W + Math.min(W - 1, Math.max(0, x + i))]!; + tmp[y * W + x] = s / ks; + } + for (let y = 0; y < H; y++) for (let x = 0; x < W; x++) { + let s = 0; for (let i = -rad; i <= rad; i++) s += k[i + rad]! * tmp[Math.min(H - 1, Math.max(0, y + i)) * W + x]!; + out[y * W + x] = s / ks + r.n() * 7; + } + const data = new Uint8ClampedArray(W * H * 4); + for (let i = 0; i < W * H; i++) { data[i * 4] = data[i * 4 + 1] = data[i * 4 + 2] = out[i]!; data[i * 4 + 3] = 255; } + return { data, width: W, height: H }; +} + +const CODE = '9781593278281'; + +test('the synthetic barcode reads when crisp', async () => { + const p = render(CODE, 3, 1); + const r = await readBarcodes(p as ImageData, { ...BASE }); + assert.equal(r[0]?.text, CODE); +}); + +test('image operations keep sizes and smooth along rows only', () => { + const g = { g: new Uint8ClampedArray([0, 255, 0, 255, 0, 255]), w: 2, h: 3 }; + const a = rowAverage(g, 6); + assert.equal(a.w, 2); assert.equal(a.g[0], a.g[2]); // each column becomes constant + assert.notEqual(a.g[0], a.g[1]); + assert.deepEqual([upscale(g, 3).w, upscale(g, 3).h], [6, 9]); +}); + +test('a sharper picture scores higher', () => { + assert.ok(sharpness(render(CODE, 2, 3)) > sharpness({ ...render(CODE, 2, 3), data: new Uint8ClampedArray(584 * 388 * 4).fill(128) })); +}); + +test('the variant pipeline reads at least as many synthetic barcodes as one plain decode', async () => { + const rows: string[] = []; + let plainTotal = 0, pipeTotal = 0; + for (const ppm of [1.2, 1.5, 2.0]) { + let plain = 0, pipe = 0; + const per: Record = {}; + const N = 8; + for (let seed = 1; seed <= N; seed++) { + const p = render(CODE, ppm, seed * 7 + Math.round(ppm * 10)); + if ((await readBarcodes(p as ImageData, { ...BASE, binarizer: 'LocalAverage' })).some(x => x.text === CODE)) plain++; + let any = false; + for (const v of VARIANTS) { + const ok = (await readBarcodes(toImageForTest(p, v) as ImageData, v.opts)).some(x => x.text === CODE); + if (ok) { per[v.name] = (per[v.name] ?? 0) + 1; any = true; } + } + if (any) pipe++; + } + plainTotal += plain; pipeTotal += pipe; + rows.push(`${ppm} px/module: plain ${plain}/${N}, pipeline ${pipe}/${N}, per variant ${JSON.stringify(per)}`); + } + console.log(rows.join('\n')); + assert.ok(pipeTotal >= plainTotal); +}); + +test('decodeLive and decodeThorough return the ISBN of a readable frame', async () => { + const p = render(CODE, 2.5, 5); + const live = await decodeLive(p, newLiveState()); + assert.equal(live.out.isbn, CODE); + assert.equal((await decodeThorough(p, null)).isbn, CODE); +}); diff --git a/src/web/decode.ts b/src/web/decode.ts new file mode 100644 index 0000000..9fbdac1 --- /dev/null +++ b/src/web/decode.ts @@ -0,0 +1,166 @@ +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))); diff --git a/src/web/frame.test.ts b/src/web/frame.test.ts index 38bfc5b..aa1618f 100644 --- a/src/web/frame.test.ts +++ b/src/web/frame.test.ts @@ -1,16 +1,22 @@ import { test } from 'node:test'; import assert from 'node:assert/strict'; -import { cropRect, upscaleFor } from './frame.ts'; +import { boxRect, cropRect, targetBox } from './frame.ts'; -test('the crop is the target box inside the frame', () => { - const r = cropRect(1920, 1080); - assert.deepEqual(r, { x: 192, y: 292, w: 1536, h: 497 }); - assert.ok(r.x + r.w <= 1920 && r.y + r.h <= 1080); +test('the target box is about 15 percent of the frame width, 3:2', () => { + const b = boxRect(1920, 1080); + assert.equal(b.w, 292); + assert.ok(Math.abs(b.w / b.h - 1.5) < 0.02); }); -test('small crops are enlarged 2x, large ones are not', () => { - assert.equal(upscaleFor(512), 2); - assert.equal(upscaleFor(999), 2); - assert.equal(upscaleFor(1000), 1); - assert.equal(upscaleFor(1536), 1); +test('the decode crop is twice the box, centred and inside the frame', () => { + const c = cropRect(1920, 1080); + assert.deepEqual(c, { x: 668, y: 345, w: 584, h: 390 }); + assert.ok(c.x >= 0 && c.y >= 0 && c.x + c.w <= 1920 && c.y + c.h <= 1080); +}); + +test('the overlay box is centred and 38 percent wide', () => { + const t = targetBox(16 / 9); + assert.equal(t.width, 38); + assert.ok(Math.abs(t.left * 2 + t.width - 100) < 1e-9); + assert.ok(Math.abs(t.top * 2 + t.height - 100) < 1e-9); }); diff --git a/src/web/frame.ts b/src/web/frame.ts index 14fbeae..7e195c3 100644 --- a/src/web/frame.ts +++ b/src/web/frame.ts @@ -1,15 +1,33 @@ -/** Where the barcode is expected, as fractions of the video frame. The overlay box is drawn from the same numbers. */ -export const TARGET = { x: 0.1, y: 0.27, w: 0.8, h: 0.46 }; +/** + * Geometry of the scan view. The preview shows the centre of the camera frame magnified ZOOM times, mirrored, + * so the target box is drawn in display fractions, while decoding works on the real (unmirrored) frame. + */ +export const ZOOM = 2.5; + +/** The target box as fractions of the displayed width; its shape is a barcode's, 3:2 (wide:tall). */ +export const BOX_W = 0.38; +export const BOX_RATIO = 3 / 2; export interface Rect { x: number; y: number; w: number; h: number } -/** The target box in pixels of a frame of the given size. */ -export function cropRect(width: number, height: number): Rect { - const x = Math.round(width * TARGET.x), y = Math.round(height * TARGET.y); - return { x, y, w: Math.min(width - x, Math.round(width * TARGET.w)), h: Math.min(height - y, Math.round(height * TARGET.h)) }; +/** The target box as percentages of the displayed video, for a stream of the given width/height ratio. */ +export function targetBox(aspect: number): { left: number; top: number; width: number; height: number } { + const height = Math.min(0.9, (BOX_W / BOX_RATIO) * aspect); + return { left: ((1 - BOX_W) / 2) * 100, top: ((1 - height) / 2) * 100, width: BOX_W * 100, height: height * 100 }; } -/** A small crop is enlarged so that thin bars cover enough pixels for the decoder: 2x below 1000 px wide. */ -export function upscaleFor(cropWidth: number): number { - return cropWidth < 1000 ? 2 : 1; +/** The target box in pixels of the real frame (about 15 percent of its width). */ +export function boxRect(width: number, height: number): Rect { + const w = Math.round((width * BOX_W) / ZOOM), h = Math.min(height, Math.round(w / BOX_RATIO)); + return centred(width, height, w, h); +} + +/** The decode region: the target box doubled in each direction, because nobody aims perfectly. */ +export function cropRect(width: number, height: number): Rect { + const b = boxRect(width, height); + return centred(width, height, Math.min(width, b.w * 2), Math.min(height, b.h * 2)); +} + +function centred(width: number, height: number, w: number, h: number): Rect { + return { x: Math.round((width - w) / 2), y: Math.round((height - h) / 2), w, h }; } diff --git a/src/web/scanner.ts b/src/web/scanner.ts index d4f51f6..28be836 100644 --- a/src/web/scanner.ts +++ b/src/web/scanner.ts @@ -1,11 +1,12 @@ -import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader'; -import type { ReaderOptions } from 'zxing-wasm/reader'; -import { normalizeIsbn } from '../shared/isbn.ts'; +import { prepareZXingModule } from 'zxing-wasm/reader'; import { acceptRead, markEmitted, newReadState } from './readstate.ts'; -import { cropRect, upscaleFor } from './frame.ts'; +import { cropRect } from './frame.ts'; +import { decodeLive, decodeThorough, newLiveState, sharpness, wantsFull } from './decode.ts'; +import type { DecodeOutcome, Pixels } from './decode.ts'; export { acceptRead } from './readstate.ts'; export type { ReadState } from './readstate.ts'; +export type { DecodeOutcome } from './decode.ts'; /** The reader wasm is served by our own server (copied there by scripts/build-web.ts), never a CDN. */ export const WASM_PATH = '/zxing_reader.wasm'; @@ -23,92 +24,38 @@ export function prepare(): void { }); } -/** - * Book barcodes are EAN-13 (978/979); UPC-A is read too so that a US price/UPC code can be reported as - * "not an ISBN" instead of silently ignored. Everything else (QR, Code 128, ...) is not searched for. - * Settings are for a fixed-focus laptop webcam: try hard, try rotated (a book held sideways), and try - * downscaled copies (a soft image of thin bars decodes better smaller). - */ -const BASE: ReaderOptions = { - formats: ['EAN13', 'UPCA'], - tryHarder: true, tryRotate: true, tryDownscale: true, tryInvert: false, - maxNumberOfSymbols: 2, -}; -/** Extra passes for the Capture button: other thresholding, and light-on-dark codes. */ -const THOROUGH: ReaderOptions[] = [ - { ...BASE, binarizer: 'LocalAverage', tryInvert: true }, - { ...BASE, binarizer: 'GlobalHistogram', tryInvert: true }, - { ...BASE, binarizer: 'FixedThreshold', tryInvert: true, tryDownscale: false }, - { ...BASE, binarizer: 'LocalAverage', downscaleThreshold: 200, downscaleFactor: 2 }, -]; - -export interface DecodeOutcome { isbn: string | null; other: string | null } - -/** Decoding runs one at a time: a new request waits for the one in progress. */ -let queue: Promise = Promise.resolve(); -function exclusive(fn: () => Promise): Promise { - const run = queue.then(fn, fn); - queue = run.catch(() => undefined); - return run; -} - -type Source = HTMLVideoElement | ImageBitmap; -const sizeOf = (s: Source) => s instanceof HTMLVideoElement ? { w: s.videoWidth, h: s.videoHeight } : { w: s.width, h: s.height }; - let scratch: HTMLCanvasElement | null = null; -/** Draw a region of the source into a canvas of the given size and return its pixels. */ -function pixels(src: Source, sx: number, sy: number, sw: number, sh: number, dw: number, dh: number): ImageData { +/** Read a region of the video's current frame, unmirrored, at full resolution. */ +function grab(video: HTMLVideoElement, sx: number, sy: number, sw: number, sh: number): ImageData { scratch ??= document.createElement('canvas'); - scratch.width = dw; scratch.height = dh; + scratch.width = sw; scratch.height = sh; const g = scratch.getContext('2d', { willReadFrequently: true })!; - g.imageSmoothingEnabled = true; g.imageSmoothingQuality = 'high'; - g.drawImage(src, sx, sy, sw, sh, 0, 0, dw, dh); - return g.getImageData(0, 0, dw, dh); + g.drawImage(video, sx, sy, sw, sh, 0, 0, sw, sh); + return g.getImageData(0, 0, sw, sh); } -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; +/** The crop region out of a whole-frame picture. */ +function cropOf(full: Pixels): Pixels { + const c = cropRect(full.width, full.height), data = new Uint8ClampedArray(c.w * c.h * 4); + for (let y = 0; y < c.h; y++) { + const from = ((c.y + y) * full.width + c.x) * 4; + data.set(full.data.subarray(from, from + c.w * 4), y * c.w * 4); } + return { data, width: c.w, height: c.h }; } -/** The images to try, most promising first: the target box (enlarged when small), then the whole frame. */ -function views(src: Source, maxSide: number): ImageData[] { - const { w, h } = sizeOf(src); - const c = cropRect(w, h); - const k = upscaleFor(c.w); - const full = Math.min(1, maxSide / Math.max(w, h)); - return [ - pixels(src, c.x, c.y, c.w, c.h, Math.round(c.w * k), Math.round(c.h * k)), - pixels(src, 0, 0, w, h, Math.round(w * full), Math.round(h * full)), - ]; +async function pngOf(p: Pixels): Promise { + const c = document.createElement('canvas'); + c.width = p.width; c.height = p.height; + c.getContext('2d')!.putImageData(new ImageData(new Uint8ClampedArray(p.data), p.width, p.height), 0, 0); + return new Promise(res => c.toBlob(res, 'image/png')); } -/** One quick pass for the live loop: the target box, then the full frame if the box held no ISBN. */ -export function decodeLive(src: Source): Promise { - return exclusive(async () => { - const out: DecodeOutcome = { isbn: null, other: null }; - for (const img of views(src, 2560)) { - judge(await readBarcodes(img, BASE), out); - if (out.isbn) break; - } - return out; - }); -} - -/** The most thorough decode: every view with every setting, stopping at the first valid ISBN. */ -export function decodeThorough(src: Source): Promise { - return exclusive(async () => { - const out: DecodeOutcome = { isbn: null, other: null }; - const imgs = views(src, 3000); - for (const opts of [BASE, ...THOROUGH]) { - for (const img of imgs) { - judge(await readBarcodes(img, opts), out); - if (out.isbn) return out; - } - } - return out; +/** Resolves on the next new video frame (or after `fallbackMs` where the browser cannot say). */ +function nextFrame(video: HTMLVideoElement, fallbackMs: number): Promise { + return new Promise(res => { + if ('requestVideoFrameCallback' in video) video.requestVideoFrameCallback(() => res()); + else setTimeout(res, fallbackMs); }); } @@ -121,13 +68,30 @@ export interface ScannerHandlers { onEnded(): void; } -export interface Scanner { - stop(): void; - /** Take one still at the highest resolution available and decode it as thoroughly as possible. */ - capture(): Promise; +export interface CaptureResult extends DecodeOutcome { + /** File name the server gave the picture of a failed burst, when it was saved. */ + saved: string | null; } -const INTERVAL_MS = 120; +export interface Scanner { + stop(): void; + /** For 1.5 seconds try every frame as thoroughly as possible; stops at the first read. */ + capture(onProgress?: (frames: number) => void): Promise; +} + +const FRAME_FALLBACK_MS = 60; +const BURST_MS = 1500; + +/** Ask for the biggest picture the camera has; failures are ignored (the camera keeps what it gave). */ +async function wantResolution(track: MediaStreamTrack | undefined): Promise { + if (!track || (track.getSettings().width ?? 0) >= 1280) return; + for (const [width, height] of [[1920, 1080], [1280, 720]] as const) { + try { + await track.applyConstraints({ width: { exact: width }, height: { exact: height } }); + if ((track.getSettings().width ?? 0) >= 1280) return; + } catch { /* not offered */ } + } +} /** * Open the camera and start the sequential decode loop. If `signal` aborts while the permission prompt is @@ -142,7 +106,6 @@ export async function startScanner( ...(deviceId ? { deviceId: { exact: deviceId } } : {}), width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 30 }, // Not in every TypeScript lib; ignored by cameras without focus control. - ...({ advanced: [{ focusMode: 'continuous' }] } as object), }, audio: false, }); @@ -150,11 +113,9 @@ export async function startScanner( if (signal?.aborted) { release(); return null; } let stopped = false; - let timer: ReturnType | undefined; const stop = () => { if (stopped) return; stopped = true; - if (timer !== undefined) clearTimeout(timer); release(); if (video.srcObject === stream) video.srcObject = null; }; @@ -170,49 +131,77 @@ export async function startScanner( if (signal?.aborted) { stop(); return null; } stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (!stopped) { stop(); handlers.onEnded(); } }); - let state = newReadState(); + await wantResolution(stream.getVideoTracks()[0]); + if (stopped) return null; - // Sequential: the next round is scheduled only after the previous detection finished. + let state = newReadState(); + let burst = false; + let live = newLiveState(); + + // Sequential: a new frame is looked at only after the previous attempt finished. const tick = async () => { if (stopped) return; - const began = performance.now(); - if (video.readyState >= 2 && video.videoWidth > 0) { + if (!burst && video.readyState >= 2 && video.videoWidth > 0) { try { - const found = await decodeLive(video); - if (stopped) return; - for (const code of [found.isbn, found.other]) { - if (!code) continue; - const r = acceptRead(state, code, Date.now()); - state = r.state; - if (r.emit) handlers.onIsbn(r.emit); - else if (r.reject) handlers.onOther(code); + const w = video.videoWidth, h = video.videoHeight; + const c = wantsFull(live) ? { x: 0, y: 0, w, h } : cropRect(w, h); + const r = await decodeLive(grab(video, c.x, c.y, c.w, c.h), live); + live = r.state; + if (stopped || burst) { /* a burst took over: drop this result */ } else { + for (const code of [r.out.isbn, r.out.other]) { + if (!code) continue; + const a = acceptRead(state, code, Date.now()); + state = a.state; + if (a.emit) handlers.onIsbn(a.emit); + else if (a.reject) handlers.onOther(code); + } } } catch { /* a failed frame is skipped */ } } if (stopped) return; - timer = setTimeout(tick, Math.max(0, INTERVAL_MS - (performance.now() - began))); + await nextFrame(video, FRAME_FALLBACK_MS); + if (!stopped) void tick(); }; - timer = setTimeout(tick, INTERVAL_MS); + void tick(); - async function capture(): Promise { - let result: DecodeOutcome = { isbn: null, other: null }; - // Highest resolution first: the camera's still-photo mode where it exists. - const IC = (window as unknown as { ImageCapture?: new (t: MediaStreamTrack) => { takePhoto(): Promise } }).ImageCapture; - const track = stream.getVideoTracks()[0]; - if (IC && track) { - let photo: ImageBitmap | null = null; - try { photo = await createImageBitmap(await new IC(track).takePhoto()); } catch { /* use the current frame */ } - if (photo) { - try { result = await decodeThorough(photo); } finally { photo.close(); } + async function capture(onProgress?: (frames: number) => void): Promise { + burst = true; + try { + const began = performance.now(); + let frames = 0, other: string | null = null, best: { full: Pixels; score: number } | null = null; + while (!stopped && performance.now() - began < BURST_MS) { + await nextFrame(video, FRAME_FALLBACK_MS); + if (video.videoWidth === 0) continue; + const full = grab(video, 0, 0, video.videoWidth, video.videoHeight); + const crop = cropOf(full); + frames++; + onProgress?.(frames); + const score = sharpness(crop); + if (!best || score > best.score) best = { full, score }; + const out = await decodeThorough(crop, full); + other ??= out.other; + if (out.isbn) { + state = markEmitted(state, out.isbn, Date.now()); + return { isbn: out.isbn, other, saved: null }; + } } + if (other) return { isbn: null, other, saved: null }; + return { isbn: null, other: null, saved: best ? await saveFailed(best.full) : null }; + } finally { + burst = false; } - if (!result.isbn && video.videoWidth > 0) { - const frame = await decodeThorough(video); - result = { isbn: frame.isbn, other: result.other ?? frame.other }; - } - if (result.isbn) state = markEmitted(state, result.isbn, Date.now()); - return result; } return { stop, capture }; } + +/** Send the picture to the server so the reader can be tuned on it. A failure to save is not an error. */ +async function saveFailed(full: Pixels): Promise { + try { + const png = await pngOf(full); + if (!png) return null; + const res = await fetch('/api/debug/capture', { method: 'POST', headers: { 'Content-Type': 'image/png' }, body: png }); + if (!res.ok) return null; + return ((await res.json()) as { saved?: string }).saved ?? null; + } catch { return null; } +} diff --git a/src/web/styles.css b/src/web/styles.css index b5509fa..18153ad 100644 --- a/src/web/styles.css +++ b/src/web/styles.css @@ -42,12 +42,13 @@ label small { display: block; margin-top: 4px; } @media (max-width: 760px) { .scan { grid-template-columns: 1fr; } main { padding: 14px 12px; } } .video-wrap { position: relative; width: 100%; background: #0b0c0e; border-radius: 12px; overflow: hidden; border: 3px solid var(--line); transition: border-color .15s; } .video-wrap.flash { border-color: var(--flash); transition: none; } -video { width: 100%; height: 100%; object-fit: cover; display: block; } +video { width: 100%; height: 100%; object-fit: cover; display: block; transform-origin: center; } +.res { margin: -6px 0 8px; } .video-empty { position: absolute; inset: 0; display: grid; place-items: center; } button.big { font-size: 1.1rem; padding: 12px 26px; } .target { position: absolute; border: 2px solid rgba(255,255,255,.92); border-radius: 10px; box-shadow: 0 0 0 100vmax rgba(0,0,0,.38); pointer-events: none; transition: border-color .15s; } .video-wrap.flash .target { border-color: var(--flash); box-shadow: 0 0 0 100vmax rgba(0,0,0,.38), 0 0 0 3px var(--flash); } -.hint { position: absolute; left: 50%; bottom: 5%; transform: translateX(-50%); max-width: 92%; padding: 4px 12px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .9rem; white-space: nowrap; pointer-events: none; } +.hint { position: absolute; left: 50%; bottom: 5%; transform: translateX(-50%); max-width: 92%; padding: 4px 12px; border-radius: 14px; background: rgba(0,0,0,.72); color: #fff; font-size: .9rem; text-align: center; width: max-content; pointer-events: none; } .scanning { position: absolute; top: 10px; right: 10px; display: flex; align-items: center; gap: 7px; padding: 3px 11px 3px 9px; border-radius: 999px; background: rgba(0,0,0,.72); color: #fff; font-size: .82rem; pointer-events: none; } .pulse { width: 9px; height: 9px; border-radius: 50%; background: #52c586; animation: pulse 1.2s ease-in-out infinite; } @keyframes pulse { 0%, 100% { opacity: 1; transform: scale(1); } 50% { opacity: .35; transform: scale(.7); } } diff --git a/src/web/views/Scan.tsx b/src/web/views/Scan.tsx index afa949d..37c88d5 100644 --- a/src/web/views/Scan.tsx +++ b/src/web/views/Scan.tsx @@ -5,7 +5,7 @@ import { api } from '../api.ts'; import { getBook, upsertBook, useBooks } from '../live.ts'; import { startScanner } from '../scanner.ts'; import type { Scanner } from '../scanner.ts'; -import { TARGET } from '../frame.ts'; +import { targetBox, ZOOM } from '../frame.ts'; import { beepAccept, beepLow, unlockAudio } from '../sound.ts'; import { emptySession, touch } from '../session.ts'; import type { SessionState } from '../session.ts'; @@ -38,7 +38,8 @@ type Cam = 'off' | 'starting' | 'on'; type Tone = 'info' | 'ok' | 'warn'; interface Status { text: string; tone: Tone; hold: boolean } -const NOT_FOUND = 'No barcode found in that picture. Move closer, add light, or type the ISBN below.'; +const NOT_FOUND = 'No barcode found. Try again, or type the ISBN below.'; +const NOT_FOUND_SAVED = 'No barcode found. Saved the picture to data/captures so the reader can be tuned.'; export function Scan() { useBooks(); // re-render on live updates @@ -54,6 +55,7 @@ export function Scan() { const [devices, setDevices] = useState([]); const [deviceId, setDeviceId] = useState(() => readFlag('camera') ?? ''); const [aspect, setAspect] = useState('16 / 9'); + const [res, setRes] = useState(''); const [flash, setFlash] = useState(false); const [status, setStatus] = useState(null); const [capturing, setCapturing] = useState(false); @@ -108,7 +110,7 @@ export function Scan() { function stopCamera(user: boolean) { opening.current?.abort(); opening.current = null; scanner.current?.stop(); scanner.current = null; - setCam('off'); setStatus(null); setCapturing(false); setAspect('16 / 9'); + setCam('off'); setStatus(null); setCapturing(false); setAspect('16 / 9'); setRes(''); if (user) writeFlag(CAMERA_FLAG, null); } @@ -128,7 +130,7 @@ export function Scan() { setCam('on'); writeFlag(CAMERA_FLAG, '1'); const v = video.current; - if (v?.videoWidth) setAspect(`${v.videoWidth} / ${v.videoHeight}`); + if (v?.videoWidth) { setAspect(`${v.videoWidth} / ${v.videoHeight}`); setRes(`${v.videoWidth}×${v.videoHeight}`); } setDevices((await navigator.mediaDevices.enumerateDevices()).filter(d => d.kind === 'videoinput')); } catch (e) { if (ac.signal.aborted) return; @@ -144,13 +146,13 @@ export function Scan() { const sc = scanner.current; if (!sc || capturing) return; setCapturing(true); - say('Taking a picture and reading it…', 'info', true); + say('Trying… 0 frames', 'info', true); try { - const r = await sc.capture(); + const r = await sc.capture(n => say(`Trying… ${n} frames`, 'info', true)); if (scanner.current !== sc) return; if (r.isbn) gotIsbn(r.isbn); else if (r.other) { beepLow(); say('That barcode is not an ISBN', 'warn', true); } - else { beepLow(); say(NOT_FOUND, 'warn', true); } + else { beepLow(); say(r.saved ? NOT_FOUND_SAVED : NOT_FOUND, 'warn', true); } } catch { say(NOT_FOUND, 'warn', true); } @@ -215,17 +217,21 @@ export function Scan() { ? { text: 'Starting the camera. Allow access if the browser asks.', tone: 'info', hold: true } : { text: 'The camera is off. Start it to scan, or type the ISBN below.', tone: 'info', hold: true }); + const [aw, ah] = aspect.split('/').map(Number); + const t = targetBox((aw || 16) / (ah || 9)); + const boxStyle = { left: `${t.left}%`, top: `${t.top}%`, width: `${t.width}%`, height: `${t.height}%` }; + return (
-