Skip to content

Commit 547aabd

Browse files
MagicalTuxclaude
andcommitted
perf/robustness: bound QR and 1D scans; split scan_2d/scan_1d; add decode2d
Two decoders could stall for seconds on a cluttered full-frame photo: - qr::scan ran the expensive thin-plate-spline dewarp on every failed finder-triple hypothesis across all four binarization passes (~7s on a busy 1080p frame with no QR). Cap dewarp to the best MAX_DEWARP_PER_PASS hypotheses per pass; a genuine curved symbol's correct (high-scored) triple still dewarps, texture can't. - scan1d's fine edge extractor pruned luminance extrema one at a time (superlinear), so a textured full-width scanline stalled it. Bail when a profile has more than MAX_FINE_EXTREMA swings — a barcode line never does; a crop stays far under it. Also split pipeline::scan_all into scan_2d (self-localizing QR/DataMatrix/PDF417, meant for whole frames, carries location) and scan_1d (linear, wants a located crop), and add a wasm decode2d export returning each 2D code's bounding box. This lets a live front-end read 2D codes directly off each frame, independent of the coarse locator. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
1 parent 4607a68 commit 547aabd

4 files changed

Lines changed: 137 additions & 23 deletions

File tree

‎src/codes/qr/sample.rs‎

Lines changed: 14 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -123,6 +123,7 @@ pub fn scan(frame: &GrayFrame<'_>) -> Result<Symbol> {
123123
let Some(bin) = binarize(frame, pass) else {
124124
break;
125125
};
126+
let mut dewarps = 0;
126127
for located in candidates(frame, &bin) {
127128
let thr = located.threshold(&integral);
128129
let matrix = located.sample(frame, &thr);
@@ -138,8 +139,12 @@ pub fn scan(frame: &GrayFrame<'_>) -> Result<Symbol> {
138139
// `dewarp_decode` self-guards (returns `None` for version 1 and when
139140
// no alignment is found), and is only reached once the cheap path has
140141
// already failed, so clean renders never pay for it.
141-
if let Some(sym) = dewarp_decode(frame, &bin, &located, &integral, &decoder) {
142-
return Ok(sym);
142+
if dewarps < MAX_DEWARP_PER_PASS {
143+
dewarps += 1;
144+
if let Some(sym) = dewarp_decode(frame, &bin, &located, &integral, &decoder)
145+
{
146+
return Ok(sym);
147+
}
143148
}
144149
if located.dimension > 21 && pending.len() < REFINE_HYPOTHESES {
145150
pending.push(located);
@@ -164,6 +169,13 @@ pub fn scan(frame: &GrayFrame<'_>) -> Result<Symbol> {
164169
/// Located hypotheses (dim > 21) retained for the fourth-corner refinement fallback.
165170
const REFINE_HYPOTHESES: usize = 4;
166171

172+
/// Per binarization pass, how many failed hypotheses may pay for the expensive non-planar
173+
/// (thin-plate-spline) dewarp. Candidates are tried best-score first, so a genuine
174+
/// curved symbol's correct triple is dewarped within this budget, while a cluttered frame
175+
/// full of false finder triples — which would otherwise run a full TPS fit on every one —
176+
/// cannot stall the scan (that path cost ~7 s on a busy 1080p photo before this cap).
177+
const MAX_DEWARP_PER_PASS: usize = 4;
178+
167179
/// Re-decode `located` while searching for the position of its bottom-right **alignment
168180
/// pattern** — the interior fiducial at grid `(dim-6.5, dim-6.5)`.
169181
///

‎src/pipeline.rs‎

Lines changed: 48 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -90,36 +90,46 @@ impl Hints {
9090
/// vec. Intended for a located crop or a whole still image; on a live stream, gate it
9191
/// behind [`crate::detect::locate`] and decode only the regions it returns.
9292
pub fn scan_all(frame: &crate::image::GrayFrame<'_>) -> Vec<Symbol> {
93-
use crate::traits::Decode;
93+
let mut found = scan_2d(frame);
94+
dedup_extend(&mut found, scan_1d(frame));
95+
found
96+
}
9497

98+
/// Decode only the **2D matrix** symbologies (QR, Data Matrix, PDF417) from `frame`.
99+
///
100+
/// These samplers *self-localize* — they find their own finder / start patterns — so
101+
/// they are meant to run on a whole frame, not a pre-cropped region, and they carry the
102+
/// decoded [`Symbol::location`]. Splitting this out lets a live front-end decode 2D codes
103+
/// directly off each frame (fast, and independent of any coarse locator) while reserving
104+
/// the heavier, crop-dependent [`scan_1d`] pass for located regions.
105+
pub fn scan_2d(frame: &crate::image::GrayFrame<'_>) -> Vec<Symbol> {
95106
let mut found: Vec<Symbol> = Vec::new();
96-
let mut push = |sym: Symbol| {
97-
let key = (sym.symbology, sym.text().unwrap_or_default());
98-
if !found
99-
.iter()
100-
.any(|s| (s.symbology, s.text().unwrap_or_default()) == key)
101-
{
102-
found.push(sym);
103-
}
104-
};
105-
106-
// 2D image samplers.
107107
if let Ok(s) = crate::codes::qr::scan(frame) {
108-
push(s);
108+
found.push(s);
109109
}
110110
if let Ok(s) = crate::codes::datamatrix::scan(frame) {
111-
push(s);
111+
dedup_push(&mut found, s);
112112
}
113113
if let Some(s) = crate::codes::pdf417::scan(frame) {
114-
push(s);
114+
dedup_push(&mut found, s);
115115
}
116+
found
117+
}
116118

117-
// 1D front-end. The EAN/UPC edge reader (width ratios, voted across scanlines) reads
118-
// curved/blurred captures the quantized grid cannot; the quantized `scan1d` path then
119-
// feeds the remaining checksummed linear decoders.
119+
/// Decode the **1D / linear** symbologies from `frame`.
120+
///
121+
/// Unlike the 2D samplers, a linear scan reads along image rows, so it wants a region
122+
/// that contains (mostly) just the barcode — feed it a located crop, not a whole cluttered
123+
/// frame. The EAN/UPC edge reader (width ratios, voted across scanlines) reads curved and
124+
/// blurred captures the quantized grid cannot; the quantized `scan1d` front-end then feeds
125+
/// the remaining checksummed linear decoders.
126+
pub fn scan_1d(frame: &crate::image::GrayFrame<'_>) -> Vec<Symbol> {
127+
use crate::traits::Decode;
128+
129+
let mut found: Vec<Symbol> = Vec::new();
120130
let scan_opts = crate::scan1d::ScanOptions::default();
121131
if let Some(s) = crate::codes::ean::scan(frame, &scan_opts) {
122-
push(s);
132+
found.push(s);
123133
}
124134
let candidates = crate::scan1d::scan_lines(frame, &scan_opts);
125135
let linear: [Box<dyn Decode>; 6] = [
@@ -133,10 +143,27 @@ pub fn scan_all(frame: &crate::image::GrayFrame<'_>) -> Vec<Symbol> {
133143
for cand in &candidates {
134144
for dec in &linear {
135145
if let Some(s) = crate::scan1d::try_decode(cand, dec.as_ref()) {
136-
push(s);
146+
dedup_push(&mut found, s);
137147
}
138148
}
139149
}
140-
141150
found
142151
}
152+
153+
/// Push `sym` unless an equal `(symbology, text)` is already present.
154+
fn dedup_push(found: &mut Vec<Symbol>, sym: Symbol) {
155+
let key = (sym.symbology, sym.text().unwrap_or_default());
156+
if !found
157+
.iter()
158+
.any(|s| (s.symbology, s.text().unwrap_or_default()) == key)
159+
{
160+
found.push(sym);
161+
}
162+
}
163+
164+
/// De-duplicating [`Vec::extend`] by `(symbology, text)`.
165+
fn dedup_extend(found: &mut Vec<Symbol>, more: Vec<Symbol>) {
166+
for sym in more {
167+
dedup_push(found, sym);
168+
}
169+
}

‎src/scan1d/mod.rs‎

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -130,6 +130,14 @@ pub fn scan_lines(frame: &GrayFrame<'_>, opts: &ScanOptions) -> Vec<LinearCandid
130130
/// cleaner captures. Every level is tried; a width-ratio decoder validates by checksum.
131131
const FINE_PROMINENCE: &[f32] = &[0.06, 0.11];
132132

133+
/// Upper bound on luminance extrema in a single scanline profile before it is rejected as
134+
/// scene texture rather than a barcode. Even the longest linear symbologies produce a few
135+
/// hundred runs; thousands of extrema mean a cluttered full-frame line, and the
136+
/// prominence prune below is superlinear in the extrema count, so this cap keeps a busy
137+
/// image (e.g. a whole 1080p photo) from stalling the scan. A located crop, which is what
138+
/// the 1D path is meant to receive, stays far under it.
139+
const MAX_FINE_EXTREMA: usize = 1024;
140+
133141
/// Scan `frame` and return per-scanline candidates carrying **fine** sub-pixel
134142
/// [`LinearCandidate::edges`], without the dedup and truncation [`scan_lines`] applies.
135143
///
@@ -507,6 +515,13 @@ fn extract_runs_fine(profile: &[f32], prom: f32) -> Option<Runs> {
507515
}
508516
ext.push((n - 1, profile[n - 1], 1));
509517

518+
// Bail on texture before the superlinear prune: a barcode line never has this many
519+
// swings, but a cluttered full-frame profile does, and pruning them one at a time
520+
// would stall the scan.
521+
if ext.len() > MAX_FINE_EXTREMA {
522+
return None;
523+
}
524+
510525
// Collapse consecutive same-kind extrema, keeping the more extreme.
511526
let mut j = 1;
512527
while j < ext.len() {

‎src/wasm.rs‎

Lines changed: 60 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -119,6 +119,66 @@ pub unsafe extern "C" fn decode(w: usize, h: usize, luma_ptr: *const u8) -> u64
119119
export(json.into_bytes())
120120
}
121121

122+
/// Decode only the **2D** codes (QR, Data Matrix, PDF417) in a `w`×`h` luminance frame,
123+
/// returning JSON `[{"symbology":..,"text":..,"box":{"x0":..,..}|null}]`.
124+
///
125+
/// These samplers self-localize, so this is meant to run on the whole frame — a live
126+
/// front-end can read 2D codes directly per frame without depending on a coarse locator,
127+
/// and each result carries the code's bounding box (frame pixels) for overlay tracking.
128+
/// 1D codes are intentionally excluded: a linear scan wants a located crop, not a full
129+
/// cluttered frame (see [`crate::pipeline::scan_1d`]).
130+
///
131+
/// # Safety
132+
/// `luma_ptr` must point to `w*h` readable bytes.
133+
#[unsafe(no_mangle)]
134+
pub unsafe extern "C" fn decode2d(w: usize, h: usize, luma_ptr: *const u8) -> u64 {
135+
let luma = unsafe { input(luma_ptr, w * h) };
136+
let frame = match GrayFrame::new(luma, w, h) {
137+
Ok(f) => f,
138+
Err(_) => return export(b"[]".to_vec()),
139+
};
140+
141+
let out = crate::pipeline::scan_2d(&frame);
142+
let mut json = String::from("[");
143+
for (i, sym) in out.iter().enumerate() {
144+
if i > 0 {
145+
json.push(',');
146+
}
147+
json.push_str("{\"symbology\":");
148+
json_str(&mut json, &sym.symbology.to_string());
149+
json.push_str(",\"text\":");
150+
json_str(&mut json, &sym.text().unwrap_or_default());
151+
json.push_str(",\"box\":");
152+
match symbol_box(sym) {
153+
Some((x0, y0, x1, y1)) => {
154+
json.push_str("{\"x0\":");
155+
push_num(&mut json, x0);
156+
json.push_str(",\"y0\":");
157+
push_num(&mut json, y0);
158+
json.push_str(",\"x1\":");
159+
push_num(&mut json, x1);
160+
json.push_str(",\"y1\":");
161+
push_num(&mut json, y1);
162+
json.push('}');
163+
}
164+
None => json.push_str("null"),
165+
}
166+
json.push('}');
167+
}
168+
json.push(']');
169+
export(json.into_bytes())
170+
}
171+
172+
/// Axis-aligned bounds `(x0, y0, x1, y1)` of a decoded symbol's outline, if it has one.
173+
fn symbol_box(sym: &crate::Symbol) -> Option<(f32, f32, f32, f32)> {
174+
let cs = sym.location.as_ref()?.outline.corners;
175+
let x0 = cs.iter().map(|p| p.x).fold(f32::MAX, f32::min);
176+
let y0 = cs.iter().map(|p| p.y).fold(f32::MAX, f32::min);
177+
let x1 = cs.iter().map(|p| p.x).fold(f32::MIN, f32::max);
178+
let y1 = cs.iter().map(|p| p.y).fold(f32::MIN, f32::max);
179+
Some((x0, y0, x1, y1))
180+
}
181+
122182
/// Locate (position-only, no decode) every candidate code in a `w`×`h` luminance
123183
/// frame; returns JSON `[{"family":..,"corners":[[x,y],..]}]`.
124184
///

0 commit comments

Comments
 (0)