Rework scan screen, make lookups non-blocking, fix review findings

Co-Authored-By: Claude Fable 5.2 <noreply@anthropic.com>
This commit is contained in:
swaitsandClaude Fable 5.2 committed 2026-11-18 10:19:32 -07:00
1 parent 468cafc6db
commit b5defb4e4f
46 files changed
+1957 -406

No files matched your search

+156 -29
View File
@@ -1,5 +1,8 @@
import { BarcodeDetector, prepareZXingModule } from 'barcode-detector/ponyfill';
import { acceptRead, endRound, newReadState } from './readstate.ts';
import { prepareZXingModule, readBarcodes } from 'zxing-wasm/reader';
import type { ReaderOptions } from 'zxing-wasm/reader';
import { normalizeIsbn } from '../shared/isbn.ts';
import { acceptRead, markEmitted, newReadState } from './readstate.ts';
import { cropRect, upscaleFor } from './frame.ts';
export { acceptRead } from './readstate.ts';
export type { ReadState } from './readstate.ts';
@@ -8,10 +11,10 @@ export type { ReadState } from './readstate.ts';
export const WASM_PATH = '/zxing_reader.wasm';
let prepared = false;
function prepare(): void {
export function prepare(): void {
if (prepared) return;
prepared = true;
prepareZXingModule({
void prepareZXingModule({
overrides: {
locateFile: (path: string, prefix: string) =>
path.endsWith('.wasm') ? WASM_PATH : prefix + path,
@@ -20,34 +23,139 @@ function prepare(): void {
});
}
/** The one detector configuration the scanner uses; also used by scripts/browser-check.ts. */
export function makeDetector(): BarcodeDetector {
prepare();
return new BarcodeDetector({ formats: ['ean_13'] });
/**
* 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;
}
const INTERVAL_MS = 150;
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 {
scratch ??= document.createElement('canvas');
scratch.width = dw; scratch.height = dh;
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);
}
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 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)),
];
}
/** 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;
});
}
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 Scanner {
stop(): void;
/** Take one still at the highest resolution available and decode it as thoroughly as possible. */
capture(): Promise<DecodeOutcome>;
}
const INTERVAL_MS = 120;
/**
* 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,
onIsbn: (isbn13: string) => void,
onReject: (code: string) => void,
): Promise<() => void> {
video: HTMLVideoElement, deviceId: string | undefined, handlers: ScannerHandlers, signal?: AbortSignal,
): Promise<Scanner | null> {
prepare();
const stream = await navigator.mediaDevices.getUserMedia({
video: {
...(deviceId ? { deviceId: { exact: deviceId } } : { facingMode: 'environment' }),
width: { ideal: 1920 }, height: { ideal: 1080 },
...(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,
});
const release = () => stream.getTracks().forEach(t => t.stop());
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);
stream.getTracks().forEach(t => t.stop());
release();
if (video.srcObject === stream) video.srcObject = null;
};
@@ -59,33 +167,52 @@ export async function startScanner(
stop();
throw e;
}
if (signal?.aborted) { stop(); return null; }
stream.getVideoTracks()[0]?.addEventListener('ended', () => { if (!stopped) { stop(); handlers.onEnded(); } });
const detector = makeDetector();
let state = newReadState();
// Sequential loop: the next round is scheduled only after the previous detection finished,
// so two detections never overlap.
// Sequential: the next round is scheduled only after the previous detection finished.
const tick = async () => {
if (stopped) return;
const began = performance.now();
if (video.readyState >= 2 && video.videoWidth > 0) {
try {
const found = await detector.detect(video);
const found = await decodeLive(video);
if (stopped) return;
const codes = found.filter(f => f.format === 'ean_13').map(f => f.rawValue);
const now = Date.now();
for (const code of codes) {
const r = acceptRead(state, code, now);
for (const code of [found.isbn, found.other]) {
if (!code) continue;
const r = acceptRead(state, code, Date.now());
state = r.state;
if (r.emit) onIsbn(r.emit);
else if (r.reject) onReject(code);
if (r.emit) handlers.onIsbn(r.emit);
else if (r.reject) handlers.onOther(code);
}
state = endRound(state, codes);
} catch { /* a failed frame is skipped */ }
}
if (stopped) return;
timer = setTimeout(tick, Math.max(0, INTERVAL_MS - (performance.now() - began)));
};
timer = setTimeout(tick, INTERVAL_MS);
return stop;
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(); }
}
}
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 };
}