Files
booksorter/src/web/scanner.ts
T
swaitsandClaude Fable 5.2 ddf6020731 Accept a camera read only when three frames agree
One frame was enough to accept an ISBN, on the theory that the check
digit makes a false read unlikely. About one multi-digit misread in ten
still passes the check, and a single book put two phantom ISBNs in the
queue. A read now has to repeat on three consecutive frames (two in a
capture burst), and a frame that yields two different ISBNs is ignored.

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
2026-11-22 11:58:46 -07:00

214 lines
8.0 KiB
TypeScript

import { prepareZXingModule } from 'zxing-wasm/reader';
import { acceptRead, agree, markEmitted, newReadState } from './readstate.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';
let prepared = false;
export function prepare(): void {
if (prepared) return;
prepared = true;
void prepareZXingModule({
overrides: {
locateFile: (path: string, prefix: string) =>
path.endsWith('.wasm') ? WASM_PATH : prefix + path,
},
fireImmediately: true,
});
}
let scratch: HTMLCanvasElement | null = null;
/** 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 = sw; scratch.height = sh;
const g = scratch.getContext('2d', { willReadFrequently: true })!;
g.drawImage(video, sx, sy, sw, sh, 0, 0, sw, sh);
return g.getImageData(0, 0, sw, sh);
}
/** 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 };
}
async function pngOf(p: Pixels): Promise<Blob | null> {
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'));
}
/** Resolves on the next new video frame (or after `fallbackMs` where the browser cannot say). */
function nextFrame(video: HTMLVideoElement, fallbackMs: number): Promise<void> {
return new Promise(res => {
if ('requestVideoFrameCallback' in video) video.requestVideoFrameCallback(() => res());
else setTimeout(res, fallbackMs);
});
}
export interface ScannerHandlers {
/** A valid ISBN-13 was read (at most once per 5 seconds per book). */
onIsbn(isbn13: string): void;
/** A barcode was read that is not a book ISBN. */
onOther(code: string): void;
/** The camera stopped by itself (unplugged, taken by another program). */
onEnded(): void;
}
export interface CaptureResult extends DecodeOutcome {
/** File name the server gave the picture of a failed burst, when it was saved. */
saved: string | null;
}
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<CaptureResult>;
}
const FRAME_FALLBACK_MS = 60;
const BURST_MS = 1500;
const BURST_AGREE_READS = 2;
/** Ask for the biggest picture the camera has; failures are ignored (the camera keeps what it gave). */
async function wantResolution(track: MediaStreamTrack | undefined): Promise<void> {
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
* open, the stream is stopped the moment it arrives and null is returned.
*/
export async function startScanner(
video: HTMLVideoElement, deviceId: string | undefined, handlers: ScannerHandlers, signal?: AbortSignal,
): Promise<Scanner | null> {
prepare();
const stream = await navigator.mediaDevices.getUserMedia({
video: {
...(deviceId ? { deviceId: { exact: deviceId } } : {}),
width: { ideal: 1920 }, height: { ideal: 1080 }, frameRate: { ideal: 30 },
// Not in every TypeScript lib; ignored by cameras without focus control.
},
audio: false,
});
const release = () => stream.getTracks().forEach(t => t.stop());
if (signal?.aborted) { release(); return null; }
let stopped = false;
const stop = () => {
if (stopped) return;
stopped = true;
release();
if (video.srcObject === stream) video.srcObject = null;
};
try {
video.srcObject = stream;
video.muted = true;
await video.play();
} catch (e) {
stop();
throw e;
}
if (signal?.aborted) { stop(); return null; }
stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (!stopped) { stop(); handlers.onEnded(); } });
await wantResolution(stream.getVideoTracks()[0]);
if (stopped) return null;
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;
if (!burst && video.readyState >= 2 && video.videoWidth > 0) {
try {
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;
await nextFrame(video, FRAME_FALLBACK_MS);
if (!stopped) void tick();
};
void tick();
async function capture(onProgress?: (frames: number) => void): Promise<CaptureResult> {
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) {
// The same agreement rule as the live loop, a little looser (two frames) since the burst is short and was asked for.
const a = agree(state, out.isbn, Date.now(), BURST_AGREE_READS);
state = a.state;
if (a.agreed) {
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;
}
}
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<string | null> {
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; }
}