Mirror and zoom the scan preview, strengthen barcode decoding, save failed captures

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 10:28:45 -07:00
1 parent b5defb4e4f
commit 308c0e1ed3
10 files changed
+510 -152

No files matched your search

+107 -118
View File
@@ -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<unknown> = Promise.resolve();
function exclusive<T>(fn: () => Promise<T>): Promise<T> {
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<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'));
}
/** 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<DecodeOutcome> {
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<DecodeOutcome> {
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<void> {
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<DecodeOutcome>;
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<CaptureResult>;
}
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<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
@@ -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<typeof setTimeout> | 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<DecodeOutcome> {
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<Blob> } }).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<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) {
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<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; }
}