Skip to main content

qrcode_barcode_scanner/
ladder.rs

1//! Deterministic decode ladder — S1 pyramid → S2 direct → S3 enhance → S4
2//! deep → S5 rescue.
3//!
4//! Replaces the v0.2 RNG brute force: the attempt sequence is a fixed,
5//! declared order, so the same input under the same config always walks the
6//! same path. Budget (wall clock, attempt-granular — an engine call is not
7//! interruptible) and cooperative cancellation are checked between attempts.
8//! Early exit happens at stage boundaries: a stage that finds something
9//! still completes, so consensus data within that stage is preserved — and
10//! a stage that found only QR Code reads whose ECI declarations are
11//! signalled, never located, does not end the walk (a later stage may
12//! locate them), nor one whose only reads the acceptance holds
13//! (`engine::reconcile`). A read of a symbology the readers invent from
14//! noise gets one decode of that symbology alone on its attempt's plane at
15//! three quarters of its size, right after the attempt (at most one per
16//! content and `MAX_CONFIRMATIONS` per walk, past the deadline too, never
17//! after cancellation): the read at an independent scale it waits for. A
18//! UPC-E read is first held to a second scan line: its bytes must read
19//! again in a band beside the row it was read on, in the attempt's image,
20//! or the read is dropped before anything collects or confirms it.
21//!
22//! Every attempt runs the engines, re-derives the grids rqrr detected but
23//! could not decode (at most `MAX_RESCUE_CANDIDATES`, while a QR Code read
24//! the scanner has not parsed is in play — rqrr's adapter already decided
25//! the first four grids' orientation: per grid at most one extra raw read
26//! of its own grid and two plain RS passes, no image sampling), records the
27//! refusals they prove, re-reads the reads no parse of the attempt carries
28//! where they lie and no recorded refusal withholds (`engine::locate`, at
29//! most `MAX_REREADS` per scan) and collects the reads
30//! (`engine::reconcile`). Nothing is decided per attempt: the walk ends
31//! with one more pass over the rescue candidates collected in every
32//! attempt — clean RS, no sampling, past the deadline too (a refusal stays a
33//! refusal; cancellation is checked before it) — and the reconciliation of
34//! the whole read set.
35
36use std::sync::Arc;
37use std::sync::atomic::{AtomicBool, Ordering};
38
39use web_time::Instant;
40
41use crate::engine::content::{self, ContentKey, EciEvidence, Fnc1, Reading, Segments};
42use crate::engine::locate::{LocateHint, Located};
43use crate::engine::occurrence::{self, Footprint, Kind, Observation};
44use crate::engine::reconcile::{Geometry, Rank, Read, ReadStore, Reconciled, Seed, inside, source};
45use crate::engine::{self, RawDetection, Refusal};
46use crate::error::{Result, ScanError};
47use crate::input::LumaImage;
48use crate::report::{EngineKind, PipelineTrace, Point, Saturation, StageTrace, Symbology};
49use crate::rescue::{Acceptance, Margin, Rederived, RescueCandidate};
50use crate::transform::{self, Channel, SourcePlanes};
51
52/// Cooperative cancellation handle. Cheap to clone; `Send + Sync`.
53#[derive(Debug, Clone, Default)]
54pub struct CancelToken(Arc<AtomicBool>);
55
56impl CancelToken {
57    /// A fresh, non-cancelled token.
58    #[must_use]
59    pub fn new() -> Self {
60        Self::default()
61    }
62
63    /// Request cancellation — honoured at the next attempt boundary.
64    pub fn cancel(&self) {
65        self.0.store(true, Ordering::Relaxed);
66    }
67
68    /// Whether cancellation has been requested.
69    #[must_use]
70    pub fn is_cancelled(&self) -> bool {
71        self.0.load(Ordering::Relaxed)
72    }
73}
74
75/// Stress-scoring depth — how many cells each axis ramp runs.
76#[derive(Debug, Clone, Copy, PartialEq, Eq)]
77#[non_exhaustive]
78pub enum ScoreDepth {
79    /// No scoring (camera frames).
80    Off,
81    /// Reduced ramps (upload tool).
82    Reduced,
83    /// Full ramps (generator quality gate).
84    Full,
85}
86
87/// Stage-level scan configuration. Build from a profile preset, then adjust
88/// public fields as needed (the struct is non-exhaustive: presets are the
89/// only constructors). Clone-not-Copy: the axis-skip list is a collection.
90#[derive(Debug, Clone, PartialEq, Eq)]
91#[non_exhaustive]
92#[expect(
93    clippy::struct_excessive_bools,
94    reason = "stage switches ARE independent booleans — a bitflags layer would obscure the API"
95)]
96pub struct ScanConfig {
97    /// Wall-clock budget in milliseconds. `None` = unbounded: the scan runs the full
98    /// ladder, bounded only by the input-size `Limits`, never by time — the mode for
99    /// strictly reproducible reports. Every built-in profile sets one (full 4 s · fast
100    /// 800 ms · frame 80 ms) and server callers should keep a budget. A planned unit
101    /// the deadline prevents does not run and the report says so
102    /// (`trace.budget_exhausted`): a judgment it interrupts is absent, never partial.
103    /// (`Some(0)` cuts immediately; bindings exposing a numeric budget map `0` →
104    /// unbounded — see each binding's docs.)
105    pub budget_ms: Option<u64>,
106    /// S1 — decode a ≤`pyramid_side` downscale first (cheapest win).
107    pub pyramid: bool,
108    /// S2 — decode the full-resolution luma.
109    pub direct: bool,
110    /// S3 — enhance set: otsu · invert · contrast · R/G/B channels.
111    pub enhance: bool,
112    /// S4 — curated deep grid (size × contrast × binarization).
113    pub deep: bool,
114    /// Longest side of the S1 pyramid attempt.
115    pub pyramid_side: u32,
116    /// Hard cap on the longest side of ANY image handed to the engines —
117    /// the wall-clock of one engine call is otherwise unbounded (a single
118    /// rxing `TryHarder` pass on 64MP runs for minutes and is not
119    /// interruptible). Detections are rescaled to original coordinates.
120    pub max_engine_side: u32,
121    /// Stress-scoring depth applied after a successful decode.
122    pub score_depth: ScoreDepth,
123    /// Stress axes EXCLUDED from scoring — integration config for hosts
124    /// where an axis is meaningless (a generated preview has no capture
125    /// angle: builders skip `perspective` + `rotation`). Skipped axes never
126    /// run (their stress cells are never built — real wall-clock savings)
127    /// and the composite renormalizes over the axes that DID run, so the
128    /// value stays 0-100 on the same contract-v3 weights. The report
129    /// self-describes: `score.axes` carries only the axes that ran. Empty
130    /// (every profile's default) = the full six-axis contract, byte for
131    /// byte. Skipping ALL axes yields no score at all (an axis-less value
132    /// would be fiction) — same outcome as `ScoreDepth::Off`.
133    pub score_skip_axes: Vec<crate::report::StressAxis>,
134    /// Score SECTIONS excluded from the report — the same integration seam
135    /// as `score_skip_axes`, for report blocks instead of stress axes. A
136    /// host that displays neither the correction margin nor the ISO
137    /// parameters skips `uec` + `iso15415`: the wire carries `null` for
138    /// them and the UEC-driven hints never fire. The UEC margin is still
139    /// measured and caps the composite, so `score.value`, `score.grade` and
140    /// the ISO `overall` never move — skipping checks is surface truth,
141    /// never score surgery. Empty (every profile's default) = every section
142    /// runs, byte for byte.
143    pub score_skip_checks: Vec<ScoreCheck>,
144    /// Background handling for inputs that carry transparent pixels — the
145    /// flatten runs BEFORE luma conversion and RGB extraction, so every
146    /// downstream stage (ladder · score · UEC · ISO) sees the composited
147    /// image. Opaque inputs never enter this path: their reports stay
148    /// byte-identical whatever this is set to.
149    pub alpha_background: AlphaBackground,
150    /// HOST palette colors probed by the placement envelope, on top of the
151    /// neutral sweep — "does my design survive on MY theme/brand colors",
152    /// answered inside one scan instead of one full scan per color
153    /// (`alpha.envelope.palette`). Probes are luma-space like the rest of
154    /// the sweep and budget-bounded per probe. At most
155    /// [`ScanConfig::MAX_ALPHA_PALETTE`] colors (a palette is the first
156    /// caller-sized loop in the scan path — unbounded, it would be a CPU
157    /// amplifier under `budget_ms: None`): [`ScanConfig::validate`], which
158    /// every scan runs first, refuses a longer one with `QRS-006`, and the
159    /// bindings refuse a longer list before the core sees it, with their own
160    /// argument error. Empty (every profile's default) = the neutral sweep
161    /// only.
162    pub alpha_palette: Vec<[u8; 3]>,
163    /// The symbologies the scan looks for. Empty (every profile's default)
164    /// = every symbology the build reads. A host that only handles some of
165    /// them names those: no reader of another symbology runs in any stage,
166    /// and the stages that exist for the others are not planned — the
167    /// native-resolution completion after a QR pyramid read when no listed
168    /// symbology is outside the QR family, the deep stage when none is
169    /// inside it. A listed symbology is read by the same readers, judged
170    /// and reported as in an unrestricted scan, with the one difference
171    /// that fewer readers imply: an unrestricted scan sets each symbol it
172    /// reads aside and reads again around it, so a symbol that shares its
173    /// rows with one of an unlisted symbology (two linear codes side by
174    /// side) can need its neighbor listed to be read; and a UPC-A symbol
175    /// read with `ean13` listed and `upc_a` not is the EAN-13 it also is
176    /// (a leading zero). The report says what it looked for
177    /// (`trace.formats`).
178    pub formats: Vec<crate::report::Symbology>,
179}
180
181/// A skippable score SECTION — the same integration seam as
182/// [`crate::report::StressAxis`]-skipping, for report blocks instead of stress axes. A host
183/// that displays neither the correction margin nor the ISO parameters skips
184/// them at scan time: the wire carries `null` for them and the section-driven
185/// hints never fire; the verdict never moves. Config-only (never
186/// serialized) — the report self-describes through the absent sections.
187#[derive(Debug, Clone, Copy, PartialEq, Eq)]
188pub enum ScoreCheck {
189    /// Unused-error-correction margin (`score.uec`) — skipping it also
190    /// withholds the ISO `unused_error_correction` parameter and silences
191    /// the two hints it drives (the thin-margin priority path of
192    /// `raise_error_correction`, and `low_correction_margin`). The margin is
193    /// still measured: it caps the composite either way.
194    Uec,
195    /// ISO 15415-informed parameters (`score.iso15415`). Independent of
196    /// [`ScoreCheck::Uec`]: skipping UEC alone nulls only the
197    /// `unused_error_correction` parameter inside a still-present block.
198    Iso15415,
199    /// The alpha placement envelope (`alpha.envelope`) — the neutral-
200    /// background decode sweep for transparent inputs. Skipping it never
201    /// touches the flatten itself (the verdict keeps its declared
202    /// background); it only drops the sweep and silences the
203    /// `alpha_background_dependent` hint.
204    AlphaEnvelope,
205}
206
207impl ScoreCheck {
208    /// Parse the wire name of the section (`uec` / `iso15415` /
209    /// `alpha_envelope` — the report field spellings). Same shape as
210    /// [`crate::report::StressAxis::from_name`]: `None` on anything else,
211    /// so bindings can fail LOUD on a typo.
212    #[must_use]
213    pub fn from_name(name: &str) -> Option<Self> {
214        match name {
215            "uec" => Some(Self::Uec),
216            "iso15415" => Some(Self::Iso15415),
217            "alpha_envelope" => Some(Self::AlphaEnvelope),
218            _ => None,
219        }
220    }
221}
222
223/// Named axis-skip presets — the drift-proof spelling of the two canonical
224/// integration postures, so N host surfaces cannot slowly diverge on their
225/// hand-built skip lists. Pure sugar over `score_skip_axes` (the bindings
226/// reject passing BOTH, loudly): `design` = a generated preview with no
227/// capture geometry (skips perspective + rotation · keeps lighting — the
228/// glare cell measures the DESIGN's fragility, not the capture) · `capture`
229/// = the full six-axis contract for photo/camera surfaces.
230#[derive(Debug, Clone, Copy, PartialEq, Eq)]
231pub enum ScorePreset {
232    /// Generated-preview posture: skip `perspective` + `rotation`.
233    Design,
234    /// Photo/camera posture: every axis runs (an explicit spelling of the
235    /// default — so integrations can WRITE their posture down).
236    Capture,
237}
238
239impl ScorePreset {
240    /// Parse the cross-language wire name (`design` · `capture`) — the ONE
241    /// mapping every binding reuses. `None` on anything else, loud upstream.
242    #[must_use]
243    pub fn from_name(name: &str) -> Option<Self> {
244        match name {
245            "design" => Some(Self::Design),
246            "capture" => Some(Self::Capture),
247            _ => None,
248        }
249    }
250
251    /// The axes this preset SKIPS.
252    #[must_use]
253    pub fn skips(self) -> Vec<crate::report::StressAxis> {
254        match self {
255            Self::Design => vec![
256                crate::report::StressAxis::Perspective,
257                crate::report::StressAxis::Rotation,
258            ],
259            Self::Capture => Vec::new(),
260        }
261    }
262}
263
264/// Background applied under transparent pixels BEFORE luma conversion and
265/// RGB extraction — the config side of the report's `alpha` block. A
266/// transparent asset has no one background: 0.8.x read the STORED RGB
267/// under the transparency, an exporter-dependent verdict (canvas exports
268/// store black under full transparency, image editors often white — the
269/// same visual design scored 100, 74 or "no detection" depending on which
270/// tool exported it). Config-only, never serialized; the report echoes the
271/// requested mode and the resolved background.
272#[derive(Debug, Clone, Copy, PartialEq, Eq)]
273pub enum AlphaBackground {
274    /// Resolve the maximum-contrast background from the design's own
275    /// visible pixels: dark content (alpha-weighted mean luma < 128)
276    /// flattens over white, light content over black — the code is
277    /// measured on its intended placement. A zero-detection scan retries
278    /// once over the opposite background (`alpha.fallback_used`), so a
279    /// mis-called mean can never turn a decodable design into a false
280    /// "no detection".
281    Auto,
282    /// Force a white background.
283    White,
284    /// Force a black background.
285    Black,
286    /// Force the host's real placement background (sRGB) — the truest
287    /// verdict when the embedder knows the surface the code will sit on.
288    Custom([u8; 3]),
289    /// Drop the alpha channel (the pre-0.9 behavior) and carry no `alpha`
290    /// block at all. Escape hatch for byte-parity with 0.8.x — never the
291    /// default, because the verdict depends on invisible stored RGB.
292    None,
293}
294
295impl AlphaBackground {
296    /// Parse one PALETTE color for the envelope's palette probes —
297    /// `white` · `black` · `#rrggbb`. The flatten keywords `auto`/`none`
298    /// are modes, not colors, and are rejected here. Same loud-typo seam
299    /// as [`AlphaBackground::from_name`].
300    #[must_use]
301    pub fn palette_color(name: &str) -> Option<[u8; 3]> {
302        match name {
303            "white" => Some([255; 3]),
304            "black" => Some([0; 3]),
305            _ => match Self::from_name(name) {
306                Some(Self::Custom(rgb)) => Some(rgb),
307                _ => None,
308            },
309        }
310    }
311
312    /// Parse the cross-language wire name (`auto` · `white` · `black` ·
313    /// `none` · `#rrggbb`) — the ONE mapping every binding reuses. `None`
314    /// on anything else, so bindings fail LOUD on a typo.
315    #[must_use]
316    pub fn from_name(name: &str) -> Option<Self> {
317        match name {
318            "auto" => Some(Self::Auto),
319            "white" => Some(Self::White),
320            "black" => Some(Self::Black),
321            "none" => Some(Self::None),
322            _ => {
323                let hex = name.strip_prefix('#')?;
324                // from_str_radix alone would admit signs ("+a") — hexdigit-gate first.
325                if hex.len() != 6 || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
326                    return None;
327                }
328                let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
329                Some(Self::Custom([channel(0)?, channel(2)?, channel(4)?]))
330            }
331        }
332    }
333}
334
335impl ScanConfig {
336    /// Hard cap on `alpha_palette` (anti-DoS: a palette entry costs a
337    /// composite + up to three decode attempts). [`ScanConfig::validate`]
338    /// refuses a longer palette with `QRS-006`; every binding refuses one
339    /// before the core sees it. 32 covers any real theme/brand palette with
340    /// headroom.
341    pub const MAX_ALPHA_PALETTE: usize = 32;
342
343    /// The largest `budget_ms` a scan accepts: 4 294 967 295 ms (about 49.7
344    /// days), the one range every binding can carry exactly and every
345    /// platform clock can add to now. A larger budget is refused
346    /// (`QRS-006`), never silently made unbounded.
347    pub const MAX_BUDGET_MS: u64 = 4_294_967_295;
348
349    /// Refuse a configuration no scan can honour (`QRS-006`), before any
350    /// input is read: a budget above [`ScanConfig::MAX_BUDGET_MS`], a zero
351    /// pyramid or engine side, a palette above
352    /// [`ScanConfig::MAX_ALPHA_PALETTE`]. [`crate::Scanner::scan`] checks it
353    /// first.
354    ///
355    /// # Errors
356    /// `QRS-006` naming the first option out of its domain.
357    pub fn validate(&self) -> crate::Result<()> {
358        if let Some(ms) = self.budget_ms
359            && ms > Self::MAX_BUDGET_MS
360        {
361            return Err(crate::ScanError::invalid_option(
362                "budget_ms",
363                format!(
364                    "{ms} ms is above the maximum {} ms (no budget = unbounded)",
365                    Self::MAX_BUDGET_MS
366                ),
367            ));
368        }
369        for (option, side) in [
370            ("pyramid_side", self.pyramid_side),
371            ("max_engine_side", self.max_engine_side),
372        ] {
373            if side == 0 {
374                return Err(crate::ScanError::invalid_option(
375                    option,
376                    "a side of 0 pixels; the smallest is 1",
377                ));
378            }
379        }
380        if self.alpha_palette.len() > Self::MAX_ALPHA_PALETTE {
381            return Err(crate::ScanError::invalid_option(
382                "alpha_palette",
383                format!(
384                    "{} colors (max {})",
385                    self.alpha_palette.len(),
386                    Self::MAX_ALPHA_PALETTE
387                ),
388            ));
389        }
390        Ok(())
391    }
392
393    /// The symbologies named by `names`, for [`ScanConfig::formats`]: wire
394    /// names ([`crate::Symbology::name`]: `qr_code`, `ean13`, …), in the
395    /// order given. One parser for every binding, so they accept and refuse
396    /// the same names.
397    ///
398    /// # Errors
399    /// `QRS-006` naming the first unknown name: a typo never widens the
400    /// scan back to every symbology.
401    pub fn formats_from_names<S: AsRef<str>>(
402        names: &[S],
403    ) -> crate::Result<Vec<crate::report::Symbology>> {
404        names
405            .iter()
406            .map(|name| {
407                let name = name.as_ref();
408                crate::report::Symbology::from_name(name).ok_or_else(|| {
409                    let known: Vec<&str> = crate::report::Symbology::ALL
410                        .iter()
411                        .map(|symbology| symbology.name())
412                        .collect();
413                    crate::ScanError::invalid_option(
414                        "formats",
415                        format!("unknown symbology `{name}`; expected {}", known.join(" | ")),
416                    )
417                })
418            })
419            .collect()
420    }
421
422    /// Everything on — the quality-gate profile (~4 s budget).
423    #[must_use]
424    pub fn full() -> Self {
425        Self {
426            budget_ms: Some(4_000),
427            pyramid: true,
428            direct: true,
429            enhance: true,
430            deep: true,
431            pyramid_side: 512,
432            max_engine_side: 2_048,
433            score_depth: ScoreDepth::Full,
434            score_skip_axes: Vec::new(),
435            score_skip_checks: Vec::new(),
436            alpha_background: AlphaBackground::Auto,
437            alpha_palette: Vec::new(),
438            formats: Vec::new(),
439        }
440    }
441
442    /// Upload-tool profile: no deep grid (~800 ms budget).
443    #[must_use]
444    pub fn fast() -> Self {
445        Self {
446            budget_ms: Some(800),
447            deep: false,
448            score_depth: ScoreDepth::Reduced,
449            ..Self::full()
450        }
451    }
452
453    /// Camera-frame profile: pyramid + direct only (~80 ms budget).
454    #[must_use]
455    pub fn frame() -> Self {
456        Self {
457            budget_ms: Some(80),
458            enhance: false,
459            deep: false,
460            score_depth: ScoreDepth::Off,
461            ..Self::full()
462        }
463    }
464
465    /// Whether this configuration judges a detection at all: `false` for
466    /// score depth [`ScoreDepth::Off`] (the `frame` profile) and when every
467    /// stress axis is skipped — such scans publish `score: null` whatever
468    /// they decode and whatever the budget.
469    #[must_use]
470    pub fn computes_score(&self) -> bool {
471        crate::score::plans_cells(self.score_depth, &self.score_skip_axes)
472    }
473}
474
475/// Named scan profiles — the public selector.
476#[derive(Debug, Clone, PartialEq, Eq, Default)]
477#[non_exhaustive]
478pub enum ScanProfile {
479    /// Full ladder + full stress score (generator quality gate).
480    #[default]
481    Full,
482    /// Reduced ladder, reduced budget (upload tool).
483    Fast,
484    /// Per-frame camera decode: no scoring, tight budget.
485    Frame,
486    /// Explicit stage configuration.
487    Custom(ScanConfig),
488}
489
490impl ScanProfile {
491    /// Parse the cross-language wire name (`full` · `fast` · `frame`) — the
492    /// ONE mapping every binding reuses (drift-proof).
493    #[must_use]
494    pub fn from_name(name: &str) -> Option<Self> {
495        match name {
496            "full" => Some(Self::Full),
497            "fast" => Some(Self::Fast),
498            "frame" => Some(Self::Frame),
499            _ => None,
500        }
501    }
502
503    /// The profile's [`ScanConfig`] — the embedder hook for adjusting a
504    /// preset (e.g. tightening `budget_ms` for a UI-thread scan) before
505    /// wrapping it back in [`ScanProfile::Custom`].
506    #[must_use]
507    pub fn config(self) -> ScanConfig {
508        match self {
509            Self::Full => ScanConfig::full(),
510            Self::Fast => ScanConfig::fast(),
511            Self::Frame => ScanConfig::frame(),
512            Self::Custom(config) => config,
513        }
514    }
515}
516
517/// Rescue candidates kept per walk (S5 cost is per candidate) and
518/// re-derived per attempt.
519const MAX_RESCUE_CANDIDATES: usize = crate::rescue::MAX_CANDIDATES;
520
521/// Re-reads per scan (both walks of an alpha fallback together): each
522/// spends at most `engine::locate::MAX_PROBES` format probes and as many
523/// error-correction attempts.
524const MAX_REREADS: usize = 16;
525
526/// Confirmation decodes per walk: at most one per (symbology, bytes).
527const MAX_CONFIRMATIONS: usize = 4;
528
529/// One S4 deep-recovery transform recipe. The SAME enumeration drives the
530/// ladder and the score probe ([`crate::score`]'s `CellProbe`) — a symbol
531/// that only decodes via rung N must measure its stress margin in that
532/// decode class (the round-2 "decodes but scores 0" regression).
533#[derive(Debug, Clone, Copy, PartialEq)]
534pub(crate) enum Rung {
535    /// Downscale → multiplicative contrast/brightness → blur — the v0.2
536    /// tier-3 "known-good" set, empirically selected on the original
537    /// 74-image artistic corpus: contrast crushing averages art texture
538    /// into module means (probe-verified on the legacy corpus, 2026-06-11).
539    Boost {
540        resize: u32,
541        contrast: f32,
542        brightness: f32,
543        blur: f32,
544    },
545    /// Morphological close of DARK structures at native resolution, then
546    /// downscale. Blob/dot pixel styles read as gap-noise to grid sampling —
547    /// growing dark blobs merges them into solid modules. Kernel scales with
548    /// render size: `side/divisor` (odd, floor 3). Probe-calibrated on the
549    /// qrcode-ai.com template corpus (R3 blitz, 2026-06-11): k=11 and k=13
550    /// at 1024px decode the blob class, k≤9 never does.
551    MorphCloseDark {
552        /// Kernel scale: `k = side/divisor`.
553        divisor: u32,
554        /// Post-close downscale side (sampling-friendly resolution).
555        target: u32,
556    },
557    /// The mirror for LIGHT blob structures (light-on-dark styles).
558    MorphCloseLight {
559        /// Kernel scale: `k = side/divisor`.
560        divisor: u32,
561        /// Post-close downscale side.
562        target: u32,
563    },
564}
565
566impl Rung {
567    /// Build this rung's attempt image.
568    pub(crate) fn apply(self, luma: &LumaImage) -> LumaImage {
569        match self {
570            Self::Boost {
571                resize,
572                contrast,
573                brightness,
574                blur,
575            } => {
576                let sized = if resize > 0 {
577                    transform::downscale_to(luma, resize)
578                } else {
579                    luma.clone()
580                };
581                let boosted = transform::contrast_boost(&sized, contrast, brightness);
582                if blur > 0.3 {
583                    transform::gaussian_blur(&boosted, blur)
584                } else {
585                    boosted
586                }
587            }
588            Self::MorphCloseDark { divisor, target } => {
589                let closed = transform::min_filter(luma, morph_kernel(luma, divisor));
590                transform::downscale_to(&closed, target)
591            }
592            Self::MorphCloseLight { divisor, target } => {
593                let closed = transform::max_filter(luma, morph_kernel(luma, divisor));
594                transform::downscale_to(&closed, target)
595            }
596        }
597    }
598}
599
600/// Blob-gap closing kernel: gaps scale with the symbol's render size, not
601/// with module count — `side/divisor` (the min/max filters normalize to an
602/// odd window ≥ 3 themselves; ONE normalization site, in `transform`).
603fn morph_kernel(luma: &LumaImage, divisor: u32) -> u32 {
604    luma.width().max(luma.height()) / divisor.max(1)
605}
606
607/// S4 deep rungs, cheap-and-common first. Boosts are the highest-yield
608/// class on artistic codes; the morphological closes catch the blob/dot
609/// pixel-style class that no contrast transform recovers (two kernel
610/// scales cover the observed gap range).
611pub(crate) const DEEP_RUNGS: [Rung; 15] = [
612    Rung::Boost {
613        resize: 400,
614        contrast: 2.0,
615        brightness: 1.0,
616        blur: 0.0,
617    },
618    Rung::Boost {
619        resize: 350,
620        contrast: 2.5,
621        brightness: 1.0,
622        blur: 0.5,
623    },
624    Rung::Boost {
625        resize: 300,
626        contrast: 2.0,
627        brightness: 1.1,
628        blur: 0.3,
629    },
630    Rung::Boost {
631        resize: 400,
632        contrast: 1.8,
633        brightness: 0.9,
634        blur: 0.0,
635    },
636    Rung::Boost {
637        resize: 250,
638        contrast: 2.5,
639        brightness: 1.0,
640        blur: 1.0,
641    },
642    Rung::Boost {
643        resize: 300,
644        contrast: 3.0,
645        brightness: 1.0,
646        blur: 0.8,
647    },
648    Rung::Boost {
649        resize: 0,
650        contrast: 2.5,
651        brightness: 1.0,
652        blur: 0.0,
653    },
654    Rung::Boost {
655        resize: 0,
656        contrast: 2.0,
657        brightness: 1.1,
658        blur: 0.5,
659    },
660    Rung::Boost {
661        resize: 500,
662        contrast: 1.5,
663        brightness: 1.0,
664        blur: 0.0,
665    },
666    Rung::Boost {
667        resize: 450,
668        contrast: 2.2,
669        brightness: 1.0,
670        blur: 0.3,
671    },
672    Rung::Boost {
673        resize: 350,
674        contrast: 3.5,
675        brightness: 1.2,
676        blur: 1.0,
677    },
678    Rung::Boost {
679        resize: 300,
680        contrast: 4.0,
681        brightness: 1.0,
682        blur: 1.5,
683    },
684    Rung::MorphCloseDark {
685        divisor: 93,
686        target: 360,
687    },
688    Rung::MorphCloseDark {
689        divisor: 76,
690        target: 420,
691    },
692    Rung::MorphCloseLight {
693        divisor: 93,
694        target: 360,
695    },
696];
697
698/// One published content: the reconciled reads and the scanner's one
699/// reading of them (its field set is what the score evaluates).
700#[derive(Debug, Clone)]
701pub(crate) struct MergedDetection {
702    pub symbology: crate::report::Symbology,
703    /// Original payload bytes, designators excluded.
704    pub raw: Vec<u8>,
705    /// The scanner's one interpretation of the content (`engine::content`).
706    /// Identity is the content, not this text: two contents that read the
707    /// same stay two detections.
708    pub text: String,
709    /// How `text` relates to `raw` (spec/01 § Content).
710    pub charset: crate::report::Charset,
711    pub masked_stream: Option<engine::MaskedStream>,
712    pub corners: Option<[Point; 4]>,
713    pub version: Option<u8>,
714    pub ec: Option<crate::report::EcLevel>,
715    pub mask: Option<u8>,
716    /// FNC1 in first position (GS1). Second position is never GS1: the
717    /// position itself travels in [`LadderOutcome::contents`].
718    pub fnc1: bool,
719    /// The GEOMETRY SOURCE's attempt photometrically inverted the symbol
720    /// (light-on-dark original). Meaningful only when `corners` is `Some`;
721    /// adopted together with the corners.
722    pub photometric_inverted: bool,
723    pub engines: Vec<EngineKind>,
724    /// Where each physical copy of the content was measured (validated,
725    /// original space): at least one, at most
726    /// [`occurrence::MAX_OCCURRENCES`], earliest observed first.
727    pub occurrences: Vec<Footprint>,
728}
729
730/// Ladder result: the published detections, what they are, the walk's
731/// reads and refusals, and the execution trace.
732#[derive(Debug)]
733pub(crate) struct LadderOutcome {
734    pub merged: Vec<MergedDetection>,
735    /// Each detection's content and its one reading, aligned with `merged`:
736    /// what the wire publishes (`eci`, `fnc1`) and what probes match reads
737    /// against (`ContentKey::admits`).
738    pub contents: Vec<(ContentKey, Reading)>,
739    /// The walk's reads and refusals.
740    store: ReadStore,
741    /// Re-reads the scan spent.
742    rereads: usize,
743    pub trace: PipelineTrace,
744}
745
746impl LadderOutcome {
747    /// What the opposite-background walk starts from: this walk's
748    /// refusals (those past capacity included), the contents its parses
749    /// read, and the re-reads already spent.
750    pub(crate) fn seed(&self) -> Seed {
751        self.store.seed(self.rereads)
752    }
753
754    /// Fold a second walk (the alpha fallback) in: both walks stay in the
755    /// trace — their stages, panics and time, and the cut of either (the
756    /// report is partial when the deadline prevented a planned unit of one
757    /// of them) — and its detections replace these only when it found some.
758    /// It started from this walk's refusals and protection ([`run_seeded`])
759    /// and applied them place by place, so whatever it publishes already
760    /// stands against them. Returns whether the fallback found a detection.
761    pub(crate) fn fold_fallback(&mut self, fallback: LadderOutcome) -> bool {
762        self.trace.stages.extend(fallback.trace.stages);
763        self.trace.engine_panics = self
764            .trace
765            .engine_panics
766            .saturating_add(fallback.trace.engine_panics);
767        self.trace.total_ms += fallback.trace.total_ms;
768        self.trace.budget_exhausted = Some(
769            self.trace.budget_exhausted == Some(true)
770                || fallback.trace.budget_exhausted == Some(true),
771        );
772        // the fallback runs after a walk that published nothing: its
773        // detection and occurrence capacities held; a read left out by
774        // either walk is left out of the scan
775        self.trace.saturation = Some(Saturation::either(
776            self.trace.saturation.unwrap_or_default(),
777            fallback.trace.saturation.unwrap_or_default(),
778        ));
779        let found = !fallback.merged.is_empty();
780        if found {
781            self.merged = fallback.merged;
782            self.contents = fallback.contents;
783        }
784        found
785    }
786}
787
788struct Run<'a> {
789    cancel: &'a CancelToken,
790    deadline: Option<Instant>,
791    /// Original input dimensions — every attempt's geometry is rescaled
792    /// back into this coordinate space (decodes happen on downscales).
793    orig: (u32, u32),
794    /// The walk's reads and refusals.
795    store: ReadStore,
796    /// Grids detected but not decoded (rqrr stream readable) — S5 inputs
797    /// and the end-of-walk pass's grids. Corners already rescaled to
798    /// original space; capped to bound cost.
799    rescue_candidates: Vec<RescueCandidate>,
800    /// Attempts made so far: the next attempt's rank.
801    attempts: u32,
802    /// Re-reads the scan spent.
803    rereads: usize,
804    /// The contents a margin re-read measured (once each).
805    margin_rereads: Vec<(Symbology, ContentKey)>,
806    /// The contents a confirmation decode ran for, in walk order.
807    confirmations: Vec<(Symbology, Vec<u8>)>,
808    panics: u8,
809    /// The deadline prevented a planned unit of the walk.
810    cut: bool,
811    /// The walk's working plane, once [`run_seeded`] built it: the image
812    /// several attempts hand the engines unchanged ([`Run::engine_pass`]).
813    plane: Option<&'a LumaImage>,
814    /// The engine passes made over the working plane, one per filter: the
815    /// outcome its second lines left ([`Run::hold_to_second_line`]) and how
816    /// many reads they refused.
817    plane_passes: Vec<(engine::FormatFilter, engine::EngineOutcome, u32)>,
818}
819
820#[cfg(test)]
821thread_local! {
822    /// Engine passes the walks of this thread ran ([`Run::engine_pass`]) —
823    /// the witness that an attempt reused one.
824    static ENGINE_PASSES: std::cell::Cell<u32> = const { std::cell::Cell::new(0) };
825    /// Test-only: while set, every attempt runs the engines — the walk a
826    /// reusing walk is held to.
827    static EVERY_PASS_RUNS: std::cell::Cell<bool> = const { std::cell::Cell::new(false) };
828}
829
830/// The candidate geometry: its grid's corners with the photometry of its
831/// attempt, and the stream with the format read from it.
832fn candidate_geometry(candidate: &RescueCandidate) -> Geometry {
833    Geometry {
834        corners: Some((candidate.corners, candidate.inverted)),
835        stream: Some((
836            candidate.stream.clone(),
837            candidate.version,
838            candidate.ec,
839            candidate.mask,
840        )),
841        ec: None,
842    }
843}
844
845/// A footprint (original space) as the observation of a read at `rank`,
846/// measured on a plane whose longest side is `side`: validated in the
847/// `orig` image; nothing when it locates nothing.
848fn observation(
849    footprint: Footprint,
850    rank: Rank,
851    orig: (u32, u32),
852    side: u32,
853) -> Option<Observation> {
854    let footprint = footprint.validated(orig);
855    (footprint.kind != Kind::Unavailable).then_some(Observation {
856        footprint,
857        rank,
858        side,
859    })
860}
861
862/// The footprint of a candidate's grid (rqrr detected it; original-space
863/// bounds) as the observation of its parse or rescue.
864fn candidate_observation(
865    candidate: &RescueCandidate,
866    rank: Rank,
867    orig: (u32, u32),
868    side: u32,
869) -> Option<Observation> {
870    let modules = usize::from(candidate.version) * 4 + 17;
871    observation(
872        occurrence::rqrr_footprint(candidate.corners, modules, candidate.pixel),
873        rank,
874        orig,
875        side,
876    )
877}
878
879/// An engine read the scanner has not parsed, of a QR Code symbol.
880fn unparsed_qr(read: &Read) -> bool {
881    !read.engines.is_empty() && read.symbology == Symbology::QrCode && !read.parsed
882}
883
884impl<'a> Run<'a> {
885    fn new(
886        cancel: &'a CancelToken,
887        deadline: Option<Instant>,
888        orig: (u32, u32),
889        seed: Seed,
890    ) -> Self {
891        let rereads = seed.rereads;
892        Self {
893            cancel,
894            deadline,
895            orig,
896            store: ReadStore::seeded(seed),
897            rescue_candidates: Vec::new(),
898            attempts: 0,
899            rereads,
900            margin_rereads: Vec::new(),
901            confirmations: Vec::new(),
902            panics: 0,
903            cut: false,
904            plane: None,
905            plane_passes: Vec::new(),
906        }
907    }
908}
909
910impl Run<'_> {
911    fn check_cancel(&self) -> Result<()> {
912        if self.cancel.is_cancelled() {
913            return Err(ScanError::Cancelled);
914        }
915        Ok(())
916    }
917
918    fn out_of_budget(&self) -> bool {
919        self.deadline
920            .is_some_and(|deadline| Instant::now() >= deadline)
921    }
922
923    /// Whether the deadline still lets one more planned unit run — a stage,
924    /// an attempt, a rescue candidate. Once it passed, the unit does not run
925    /// and the walk remembers it (`trace.budget_exhausted`).
926    fn admit(&mut self) -> bool {
927        if self.out_of_budget() {
928            self.cut = true;
929            return false;
930        }
931        true
932    }
933
934    /// The next attempt's rank.
935    fn next_attempt(&mut self) -> u32 {
936        let attempt = self.attempts;
937        self.attempts = self.attempts.saturating_add(1);
938        attempt
939    }
940
941    /// An engine hit as a read of this walk: original-space place and
942    /// geometry, the photometry of its attempt travelling with its
943    /// corners, the footprint its reader measured (validated in original
944    /// space); and what its re-read needs (attempt space).
945    fn read_of(
946        &self,
947        hit: RawDetection,
948        rank: Rank,
949        dims: (u32, u32),
950        inverts: bool,
951    ) -> (Read, Option<LocateHint>) {
952        let place = |corners: [Point; 4]| rescaled(corners, dims, self.orig);
953        let stream = match (hit.masked_stream, hit.version, hit.ec, hit.mask) {
954            (Some(stream), Some(version), Some(ec), Some(mask)) => {
955                Some((stream, version, ec, mask))
956            }
957            _ => None,
958        };
959        let geometry = Geometry {
960            corners: hit.corners.map(|corners| (place(corners), inverts)),
961            ec: if stream.is_none() { hit.ec } else { None },
962            stream,
963        };
964        let key = ContentKey {
965            raw: hit.raw,
966            eci: hit.eci,
967            fnc1: hit.fnc1,
968        };
969        let mut read =
970            Read::new(hit.symbology, key, Some(hit.engine), rank).at(hit.location.map(place));
971        read.segments = hit.segments;
972        read.engine_reading = hit.engine_reading;
973        read.parsed = hit.parsed;
974        read.margin = hit.margin;
975        read.needs_confirmation = hit.needs_confirmation;
976        let side = dims.0.max(dims.1);
977        read.scales = Some((side, side));
978        read.geometry = geometry;
979        read.matrix_regions
980            .extend(hit.matrix_region.map(|region| region.mapped(place)));
981        read.observations.extend(observation(
982            hit.footprint.rescaled(dims, self.orig),
983            rank,
984            self.orig,
985            side,
986        ));
987        (read, hit.locate)
988    }
989
990    /// Re-derive grids rqrr detected but did not decode (plain RS, no luma
991    /// sampling — or the re-derivation the engine pass already chose their
992    /// orientation with): a stream that parses is a candidate parse — its
993    /// declarations, FNC1 position, segments, geometry and the correction
994    /// margin of the word it corrected, no engine; one proven malformed is a
995    /// refusal at the grid's place. At most `MAX_RESCUE_CANDIDATES`, in the
996    /// order given (original-space corners, photometry stamped); a parse
997    /// observes its grid's footprint in the `orig` image, measured on a
998    /// plane whose longest side is `side` (0: not known).
999    fn rederive(
1000        candidates: &[RescueCandidate],
1001        attempt: u32,
1002        orig: (u32, u32),
1003        side: u32,
1004    ) -> (Vec<Read>, Vec<Refusal>) {
1005        let mut reads = Vec::new();
1006        let mut refusals = Vec::new();
1007        for (index, candidate) in candidates.iter().take(MAX_RESCUE_CANDIDATES).enumerate() {
1008            let derived = candidate.rederived.clone().unwrap_or_else(|| {
1009                crate::rescue::rederive(
1010                    &candidate.stream,
1011                    candidate.version,
1012                    candidate.ec,
1013                    candidate.mask,
1014                    Acceptance::Engine,
1015                )
1016            });
1017            match derived {
1018                Rederived::Parsed { parsed, margin } => {
1019                    let key = ContentKey {
1020                        raw: parsed.bytes,
1021                        eci: EciEvidence::from_marks(parsed.eci),
1022                        fnc1: parsed.fnc1,
1023                    };
1024                    let rank = Rank {
1025                        attempt,
1026                        source: source::CANDIDATE,
1027                        index: u32::try_from(index).unwrap_or(u32::MAX),
1028                    };
1029                    let mut read =
1030                        Read::new(Symbology::QrCode, key, None, rank).at(Some(candidate.corners));
1031                    read.segments = Segments::Observed(parsed.segments);
1032                    read.parsed = true;
1033                    // the scanner error-corrected this word itself: the
1034                    // acceptance weighs its margin like any read's (an
1035                    // FNC1 or Hanzi symbol has no other measured word)
1036                    read.margin = Margin::Known(margin);
1037                    read.geometry = candidate_geometry(candidate);
1038                    read.observations
1039                        .extend(candidate_observation(candidate, rank, orig, side));
1040                    reads.push(read);
1041                }
1042                Rederived::Malformed { port } => {
1043                    refusals.extend(Refusal::new(port, None, Some(candidate.corners)));
1044                }
1045                Rederived::Unverified(_) => {}
1046            }
1047        }
1048        (reads, refusals)
1049    }
1050
1051    /// The re-read (07-pipeline property 6): each read with a hint is
1052    /// sampled at its engine's corners in the attempt image, while the scan
1053    /// has re-reads left — unless a recorded refusal withholds it (it is
1054    /// withheld anyway) or [`Run::reread_hint`] finds nothing to learn. A
1055    /// located parse records its word's margin and, for a declarations
1056    /// re-read, upgrades the read (declarations, segments — never its bytes,
1057    /// engines or geometry); a declarations re-read that refuses removes it
1058    /// and records the refusal at its place. A margin re-read changes
1059    /// nothing else.
1060    fn reread(
1061        &mut self,
1062        img: &LumaImage,
1063        reads: &mut Vec<(Read, Option<LocateHint>)>,
1064        refusals: &mut Vec<Refusal>,
1065    ) {
1066        let mut i = 0;
1067        while let Some((read, hint)) = reads.get(i) {
1068            let Some(hint) = hint
1069                .as_ref()
1070                .filter(|_| self.rereads < MAX_REREADS && !self.store.withheld(read))
1071                .and_then(|hint| self.reread_hint(read, hint, reads))
1072            else {
1073                i += 1;
1074                continue;
1075            };
1076            self.rereads += 1;
1077            if !hint.declarations {
1078                self.margin_rereads.push((read.symbology, read.key.clone()));
1079            }
1080            match engine::reread(img, &hint, &read.key.raw) {
1081                Located::Parsed {
1082                    eci,
1083                    fnc1,
1084                    segments,
1085                    margin,
1086                    ..
1087                } => {
1088                    if let Some((read, _)) = reads.get_mut(i) {
1089                        read.margin = read.margin.best(Margin::Known(margin));
1090                        if hint.declarations {
1091                            read.key.eci = EciEvidence::from_marks(eci);
1092                            read.key.fnc1 = fnc1;
1093                            read.segments = Segments::Observed(segments);
1094                            read.parsed = true;
1095                        }
1096                    }
1097                    i += 1;
1098                }
1099                Located::Refused { port } if hint.declarations => {
1100                    let (read, _) = reads.remove(i);
1101                    refusals.push(Refusal {
1102                        port: Some(engine::port_key(port)),
1103                        rqrr: None,
1104                        place: read.location,
1105                        grid: None,
1106                    });
1107                }
1108                Located::Refused { .. } | Located::Unverified => i += 1,
1109            }
1110        }
1111    }
1112
1113    /// The re-read a read can still learn from, if any: its declarations
1114    /// re-read unless a parsed read or candidate parse of the attempt
1115    /// carries the read where it lies; otherwise — or once such a parse
1116    /// carries it — the margin re-read of a port read at EC level L or M
1117    /// ([`LocateHint::for_margin`]), once per content, while no read of that
1118    /// content — the attempt's or the walk's — has a known margin of zero or
1119    /// more. The parse that carries the declarations may have corrected its
1120    /// own word past the Annex B reserve (rqrr's sampling of the grid): the
1121    /// port read's word, sampled at its own corners, can still keep the
1122    /// content.
1123    fn reread_hint(
1124        &self,
1125        read: &Read,
1126        hint: &LocateHint,
1127        reads: &[(Read, Option<LocateHint>)],
1128    ) -> Option<LocateHint> {
1129        let content =
1130            |other: &Read| other.symbology == read.symbology && other.key.agrees(&read.key);
1131        let hint = if hint.declarations {
1132            let carried = reads.iter().any(|(other, _)| {
1133                other.parsed && content(other) && inside(read.location, other.location)
1134            });
1135            if !carried {
1136                return Some(hint.clone());
1137            }
1138            hint.for_margin()?
1139        } else {
1140            hint.clone()
1141        };
1142        let measured = self
1143            .margin_rereads
1144            .iter()
1145            .any(|(symbology, key)| *symbology == read.symbology && key.agrees(&read.key))
1146            || reads
1147                .iter()
1148                .any(|(other, _)| content(other) && other.margin.within_reserve())
1149            || self.store.has_margin(read);
1150        (!measured).then_some(hint)
1151    }
1152
1153    /// S5 — try the collected rescue candidates when the walk published
1154    /// nothing (refused and withheld reads do not count); the first success
1155    /// at each place is collected (identically damaged twins are two).
1156    fn rescue_stage(&mut self, luma: &LumaImage, stages: &mut Vec<StageTrace>) -> Result<()> {
1157        if self.rescue_candidates.is_empty() || self.store.found() || !self.admit() {
1158            return Ok(());
1159        }
1160        let started = Instant::now();
1161        let attempt = self.next_attempt();
1162        let mut tried = 0u32;
1163        let mut found = 0u32;
1164        let mut rescued_at: Vec<[Point; 4]> = Vec::new();
1165        for (index, candidate) in self.rescue_candidates.clone().into_iter().enumerate() {
1166            self.check_cancel()?;
1167            if !self.admit() {
1168                break;
1169            }
1170            if rescued_at
1171                .iter()
1172                .any(|&place| same_grid(place, candidate.corners))
1173            {
1174                continue; // another orientation or photometry of a rescued grid
1175            }
1176            tried += 1;
1177            // Reports retain original-space corners. Rescue samples the
1178            // capped working plane, including its bounded inverted view.
1179            let mut sampling = candidate.clone();
1180            if (luma.width(), luma.height()) != self.orig {
1181                #[expect(
1182                    clippy::cast_precision_loss,
1183                    reason = "dimensions bounded by Limits::max_dimension — exact in f32"
1184                )]
1185                let (fx, fy) = (
1186                    luma.width() as f32 / self.orig.0 as f32,
1187                    luma.height() as f32 / self.orig.1 as f32,
1188                );
1189                for corner in &mut sampling.corners {
1190                    corner.x *= fx;
1191                    corner.y *= fy;
1192                }
1193            }
1194            if let Some(rescued) = crate::rescue::attempt(luma, &sampling) {
1195                found += 1;
1196                let key = ContentKey {
1197                    raw: rescued.raw,
1198                    eci: EciEvidence::from_marks(rescued.eci),
1199                    fnc1: rescued.fnc1,
1200                };
1201                let rank = Rank {
1202                    attempt,
1203                    source: source::RESCUE,
1204                    index: u32::try_from(index).unwrap_or(u32::MAX),
1205                };
1206                let mut read = Read::new(Symbology::QrCode, key, Some(EngineKind::Rescue), rank)
1207                    .at(Some(candidate.corners));
1208                read.segments = Segments::Observed(rescued.segments);
1209                read.parsed = true;
1210                read.margin = Margin::Known(rescued.margin);
1211                read.geometry = candidate_geometry(&candidate);
1212                read.observations.extend(candidate_observation(
1213                    &candidate,
1214                    rank,
1215                    self.orig,
1216                    luma.width().max(luma.height()),
1217                ));
1218                self.store.collect(read);
1219                rescued_at.push(candidate.corners);
1220            }
1221        }
1222        stages.push(StageTrace {
1223            stage: "rescue".to_owned(),
1224            transforms_tried: tried,
1225            ms: started.elapsed().as_secs_f64() * 1_000.0,
1226            detections_found: found,
1227        });
1228        Ok(())
1229    }
1230
1231    /// Keep a bounded set of rescue inputs (S5 cost is per-candidate);
1232    /// dedupe by symbol identity (version/ec/mask, photometry, orientation)
1233    /// at one place — the same physical symbol surfaces across many
1234    /// attempts, and an identically damaged twin elsewhere is another input.
1235    fn collect_rescue(
1236        &mut self,
1237        candidates: Vec<RescueCandidate>,
1238        attempt_dims: (u32, u32),
1239        inverts: bool,
1240    ) {
1241        for mut candidate in candidates {
1242            if self.rescue_candidates.len() >= MAX_RESCUE_CANDIDATES {
1243                return;
1244            }
1245            if attempt_dims != self.orig {
1246                candidate.corners = rescaled(candidate.corners, attempt_dims, self.orig);
1247                candidate.pixel = rescaled_pixel(candidate.pixel, attempt_dims, self.orig);
1248            }
1249            if self.rescue_candidates.iter().any(|c| {
1250                (c.version, c.ec, c.mask, c.inverted, c.transposed)
1251                    == (
1252                        candidate.version,
1253                        candidate.ec,
1254                        candidate.mask,
1255                        inverts,
1256                        candidate.transposed,
1257                    )
1258                    && same_grid(c.corners, candidate.corners)
1259            }) {
1260                continue;
1261            }
1262            candidate.inverted = inverts;
1263            self.rescue_candidates.push(candidate);
1264        }
1265    }
1266
1267    /// One attempt's engine pass, collected: its candidates re-derived while
1268    /// an unparsed QR Code read is in play, the refusals they prove
1269    /// recorded, the re-reads (which record their own), then the reads.
1270    /// Returns the reads the adapters delivered — what the trace counts.
1271    fn collect_attempt(
1272        &mut self,
1273        img: &LumaImage,
1274        outcome: engine::EngineOutcome,
1275        inverts: bool,
1276    ) -> u32 {
1277        self.panics = self.panics.saturating_add(outcome.panics);
1278        let delivered = u32::try_from(outcome.detections.len()).unwrap_or(u32::MAX);
1279        let dims = (img.width(), img.height());
1280        let index = self.next_attempt();
1281        let mut reads: Vec<(Read, Option<LocateHint>)> = outcome
1282            .detections
1283            .into_iter()
1284            .enumerate()
1285            .map(|(i, hit)| {
1286                let rank = Rank {
1287                    attempt: index,
1288                    source: match hit.engine {
1289                        EngineKind::Rxing => source::RXING,
1290                        EngineKind::Rqrr => source::RQRR,
1291                        EngineKind::Rescue => source::RESCUE,
1292                    },
1293                    index: u32::try_from(i).unwrap_or(u32::MAX),
1294                };
1295                self.read_of(hit, rank, dims, inverts)
1296            })
1297            .collect();
1298        let mut refusals: Vec<Refusal> = outcome
1299            .refused
1300            .into_iter()
1301            .map(|refusal| Refusal {
1302                place: refusal.place.map(|place| rescaled(place, dims, self.orig)),
1303                grid: refusal
1304                    .grid
1305                    .map(|grid| grid.mapped(|outer| rescaled(outer, dims, self.orig))),
1306                ..refusal
1307            })
1308            .collect();
1309        // the attempt's grids in original space, photometry stamped,
1310        // re-derived while an unparsed QR read is in play
1311        if reads.iter().any(|(read, _)| unparsed_qr(read)) || self.store.unparsed_qr() {
1312            let candidates: Vec<RescueCandidate> = outcome
1313                .rescue
1314                .iter()
1315                .map(|candidate| RescueCandidate {
1316                    corners: rescaled(candidate.corners, dims, self.orig),
1317                    pixel: rescaled_pixel(candidate.pixel, dims, self.orig),
1318                    inverted: inverts,
1319                    ..candidate.clone()
1320                })
1321                .collect();
1322            let (parses, refused) =
1323                Self::rederive(&candidates, index, self.orig, dims.0.max(dims.1));
1324            reads.extend(parses.into_iter().map(|read| (read, None)));
1325            refusals.extend(refused);
1326        }
1327        // recorded before the re-reads: a read they withhold is not re-read
1328        for refusal in refusals {
1329            self.store.refuse(refusal, index);
1330        }
1331        let mut refusals = Vec::new();
1332        self.reread(img, &mut reads, &mut refusals);
1333        for refusal in refusals {
1334            self.store.refuse(refusal, index);
1335        }
1336        for (read, _) in reads {
1337            self.store.collect(read);
1338        }
1339        self.collect_rescue(outcome.rescue, dims, inverts);
1340        delivered
1341    }
1342
1343    /// The confirmation decodes after an attempt (07-pipeline
1344    /// § Acceptance): for each (symbology, bytes) of `pending` — reads of a
1345    /// symbology the readers invent from noise — that no read at an
1346    /// independent scale confirms yet, one decode of that symbology alone on
1347    /// `plane` at three quarters of its size, collected as an attempt of its
1348    /// own (its reads in no stage count). At most one per content and
1349    /// [`MAX_CONFIRMATIONS`] per walk, whatever the budget left, never after
1350    /// cancellation. The pinned rxing includes the RSS-14 padding underflow
1351    /// fix, so small `DataBar` images receive this independent read too.
1352    fn confirm(&mut self, plane: &LumaImage, pending: Vec<(Symbology, Vec<u8>)>, inverts: bool) {
1353        for (symbology, raw) in pending {
1354            if self.cancel.is_cancelled() || self.confirmations.len() >= MAX_CONFIRMATIONS {
1355                return;
1356            }
1357            if self
1358                .confirmations
1359                .iter()
1360                .any(|(own, bytes)| *own == symbology && *bytes == raw)
1361                || self.store.confirmed(symbology, &raw)
1362            {
1363                continue;
1364            }
1365            self.confirmations.push((symbology, raw));
1366            let longest = plane.width().max(plane.height());
1367            let small = transform::downscale_to(plane, longest * 3 / 4);
1368            let mut outcome =
1369                engine::decode_filtered(&small, engine::FormatFilter::Only(symbology));
1370            let _ = self.hold_to_second_line(&small, &mut outcome);
1371            let _ = self.collect_attempt(&small, outcome, inverts);
1372        }
1373    }
1374
1375    /// The second line of each read that needs one (07-pipeline
1376    /// § Acceptance, rule 3): a read of `outcome` whose bytes no second line
1377    /// reads again ([`reads_on_a_second_line`]) leaves the outcome before
1378    /// anything caches, collects or confirms it. Returns how many left:
1379    /// reads the adapters delivered, which the trace still counts. Decoder
1380    /// panics caught on the second lines join those of the pass. Once the
1381    /// walk is cancelled no line is looked for, and a read still held is not
1382    /// kept.
1383    fn hold_to_second_line(&self, img: &LumaImage, outcome: &mut engine::EngineOutcome) -> u32 {
1384        let mut panics = 0u8;
1385        let delivered = outcome.detections.len();
1386        let cancelled = || self.cancel.is_cancelled();
1387        outcome.detections.retain(|hit| {
1388            !needs_second_line(hit.symbology)
1389                || reads_on_a_second_line(img, hit, &cancelled, &mut panics)
1390        });
1391        outcome.panics = outcome.panics.saturating_add(panics);
1392        u32::try_from(delivered - outcome.detections.len()).unwrap_or(u32::MAX)
1393    }
1394
1395    /// The engines' pass over `img` under `filter`, the passes that read
1396    /// no QR-family symbol left out where nothing but QR-family symbols can
1397    /// be read ([`Run::nothing_but_qr_codes`], 07-pipeline property 8), as
1398    /// `narrowed` answers. rqrr's pass over `img` is part of that question,
1399    /// so it runs first ([`engine::decode_narrowed`]).
1400    fn decode(&self, img: &LumaImage, filter: engine::FormatFilter) -> engine::EngineOutcome {
1401        #[cfg(feature = "engine-rxing")]
1402        if let Some(narrowed) = narrowed(filter) {
1403            return engine::decode_narrowed(img, filter, |rqrr| {
1404                if self.nothing_but_qr_codes(img, rqrr) {
1405                    narrowed
1406                } else {
1407                    Some(engine::RxingPass::Whole(filter))
1408                }
1409            });
1410        }
1411        #[cfg(not(feature = "engine-rxing"))]
1412        let _ = self;
1413        engine::decode_filtered(img, filter)
1414    }
1415
1416    /// Whether every pixel of `img` outside the QR-family symbols known in
1417    /// it has one value. The symbols are those the walk admitted
1418    /// ([`ReadStore::qr_regions`]) and the grids rqrr measured in this pass
1419    /// (`rqrr`): read, refused, or located with format information that
1420    /// reads. Each is grown by one of its modules ([`grown`]). Pixels
1421    /// of one value hold no transition, so no reader reads a symbol out of
1422    /// them: whatever another family would read in `img` lies over a
1423    /// QR-family symbol or within one module of its edge.
1424    #[cfg(feature = "engine-rxing")]
1425    fn nothing_but_qr_codes(&self, img: &LumaImage, rqrr: &engine::EngineOutcome) -> bool {
1426        let dims = (img.width(), img.height());
1427        let admitted = self
1428            .store
1429            .qr_regions()
1430            .into_iter()
1431            .map(|region| region.mapped(|corners| rescaled(corners, self.orig, dims)));
1432        let read = rqrr.detections.iter().filter_map(|hit| hit.matrix_region);
1433        let refused = rqrr.refused.iter().filter_map(|refusal| {
1434            refusal.place.map(|corners| engine::MatrixRegion {
1435                corners,
1436                grid: refusal.grid,
1437            })
1438        });
1439        let located = rqrr.rescue.iter().map(located_region);
1440        let regions: Vec<([Point; 4], f32)> = admitted
1441            .chain(read)
1442            .chain(refused)
1443            .chain(located)
1444            .map(grown)
1445            .collect();
1446        flat_outside(img, &regions)
1447    }
1448
1449    /// The engines' pass over one attempt image under `filter`.
1450    ///
1451    /// Several attempts of a walk can build the same image: a contrast
1452    /// stretch leaves a plane that already spans 0 to 255 as it is, a grey
1453    /// source stored as RGB has three channels equal to its luma, a
1454    /// two-level plane is its own binarization. The engines read the image
1455    /// and the filter and nothing else, so the pass over the walk's working
1456    /// plane is made once per filter: an attempt whose image is that plane,
1457    /// byte for byte, gets the outcome the first one read. The attempt is
1458    /// still collected, counted and followed by its confirmation decodes
1459    /// like any other — only the engines' time is not spent twice. (Where a
1460    /// reader is not a function of its image — rxing's PDF417 tie-break,
1461    /// spec/04 § Determinism — the first pass's answer stands for the
1462    /// plane, and so it does where the QR-family symbols the walk had
1463    /// admitted by then left out the passes that read no QR-family symbol
1464    /// ([`Run::decode`]).)
1465    ///
1466    /// The second lines of the pass's reads are part of it
1467    /// ([`Run::hold_to_second_line`]): they are looked for once, before the
1468    /// outcome is kept for the plane, and the number of reads they refused
1469    /// comes back beside it, the first time and every time after.
1470    fn engine_pass(
1471        &mut self,
1472        img: &LumaImage,
1473        filter: engine::FormatFilter,
1474    ) -> (engine::EngineOutcome, u32) {
1475        let plain = self.plane.is_some_and(|plane| plane == img);
1476        #[cfg(test)]
1477        let plain = plain && !EVERY_PASS_RUNS.with(std::cell::Cell::get);
1478        if plain
1479            && let Some((_, outcome, single_line)) =
1480                self.plane_passes.iter().find(|(own, ..)| *own == filter)
1481        {
1482            return (outcome.clone(), *single_line);
1483        }
1484        #[cfg(test)]
1485        ENGINE_PASSES.with(|passes| passes.set(passes.get() + 1));
1486        let mut outcome = self.decode(img, filter);
1487        let single_line = self.hold_to_second_line(img, &mut outcome);
1488        if plain {
1489            self.plane_passes
1490                .push((filter, outcome.clone(), single_line));
1491        }
1492        (outcome, single_line)
1493    }
1494
1495    /// Run one stage as a fixed sequence of lazily-built attempts, each
1496    /// collected ([`Run::collect_attempt`]) and followed by its confirmation
1497    /// decodes ([`Run::confirm`]). Returns `Ok(true)` when the ladder should
1498    /// stop (budget mid-stage: an attempt did not run).
1499    fn stage(
1500        &mut self,
1501        name: &str,
1502        attempts: Vec<Attempt<'_>>,
1503        filter: engine::FormatFilter,
1504        stages: &mut Vec<StageTrace>,
1505    ) -> Result<bool> {
1506        let started = Instant::now();
1507        let mut tried = 0u32;
1508        let mut found_total = 0u32;
1509        let mut stop = false;
1510        for attempt in attempts {
1511            self.check_cancel()?;
1512            if !self.admit() {
1513                stop = true;
1514                break;
1515            }
1516            let img = (attempt.build)();
1517            let (outcome, single_line) = self.engine_pass(&img, filter);
1518            let pending: Vec<(Symbology, Vec<u8>)> = outcome
1519                .detections
1520                .iter()
1521                .filter(|hit| hit.needs_confirmation)
1522                .map(|hit| (hit.symbology, hit.raw.clone()))
1523                .collect();
1524            // the trace counts the reads the adapters delivered, those a
1525            // second line refused included
1526            found_total = found_total
1527                .saturating_add(self.collect_attempt(&img, outcome, attempt.inverts))
1528                .saturating_add(single_line);
1529            tried += 1;
1530            self.confirm(&img, pending, attempt.inverts);
1531        }
1532        stages.push(StageTrace {
1533            stage: name.to_owned(),
1534            transforms_tried: tried,
1535            ms: started.elapsed().as_secs_f64() * 1_000.0,
1536            detections_found: found_total,
1537        });
1538        Ok(stop)
1539    }
1540}
1541
1542/// One lazily-built decode attempt: the transform closure plus whether its
1543/// chain photometrically INVERTS the symbol. The flag travels with adopted
1544/// geometry — structural/ISO sampling on the ORIGINAL luma must flip its
1545/// dark-test for grids that were measured on an inverted attempt (otherwise
1546/// a clean light-on-dark symbol reads finder integrity ≈ 0.33 and earns
1547/// bogus caps + hints — the review-found polarity lie).
1548struct Attempt<'a> {
1549    inverts: bool,
1550    build: Box<dyn Fn() -> LumaImage + 'a>,
1551}
1552
1553impl<'a> Attempt<'a> {
1554    /// A polarity-preserving attempt (the common case).
1555    fn plain(build: impl Fn() -> LumaImage + 'a) -> Self {
1556        Self {
1557            inverts: false,
1558            build: Box::new(build),
1559        }
1560    }
1561
1562    /// An attempt whose chain flips dark/light.
1563    fn inverting(build: impl Fn() -> LumaImage + 'a) -> Self {
1564        Self {
1565            inverts: true,
1566            build: Box::new(build),
1567        }
1568    }
1569}
1570
1571/// S4 attempt list: the deep rungs (boosts + morphological closes), then
1572/// the size × contrast × binarization grid in fixed declared order (grid
1573/// combos duplicating S3 are skipped).
1574fn deep_attempts(luma: &LumaImage, longest: u32) -> Vec<Attempt<'_>> {
1575    type Op = fn(&LumaImage) -> LumaImage;
1576    let mut attempts: Vec<Attempt<'_>> = Vec::new();
1577    for rung in DEEP_RUNGS {
1578        // no deep rung flips polarity (boosts/morph-closes preserve it)
1579        attempts.push(Attempt::plain(move || rung.apply(luma)));
1580    }
1581    for size in [Some(512u32), Some(800), None] {
1582        if let Some(side) = size
1583            && side >= longest
1584        {
1585            continue;
1586        }
1587        for stretch in [false, true] {
1588            if size.is_none() && !stretch {
1589                continue; // duplicates S3 otsu/invert at full res
1590            }
1591            for (op, inverts) in [
1592                (transform::otsu_threshold as Op, false),
1593                (transform::invert as Op, true),
1594            ] {
1595                let build = move || {
1596                    let scaled = match size {
1597                        Some(side) => transform::downscale_to(luma, side),
1598                        None => luma.clone(),
1599                    };
1600                    let based = if stretch {
1601                        transform::contrast_stretch(&scaled)
1602                    } else {
1603                        scaled
1604                    };
1605                    op(&based)
1606                };
1607                attempts.push(Attempt {
1608                    inverts,
1609                    build: Box::new(build),
1610                });
1611            }
1612        }
1613    }
1614    attempts
1615}
1616
1617/// Whether two grids (original-space corners) are one symbol: the centre
1618/// of either inside the other's box.
1619fn same_grid(a: [Point; 4], b: [Point; 4]) -> bool {
1620    inside(Some(a), Some(b)) || inside(Some(b), Some(a))
1621}
1622
1623/// Four corners from one image's coordinate space to another's.
1624fn rescaled(corners: [Point; 4], from: (u32, u32), to: (u32, u32)) -> [Point; 4] {
1625    if from == to {
1626        return corners;
1627    }
1628    corners.map(|p| rescaled_pixel(p, from, to))
1629}
1630
1631/// A point, or a pixel's extent, from one image's coordinate space to
1632/// another's.
1633#[expect(
1634    clippy::cast_precision_loss,
1635    reason = "dimensions bounded by Limits::max_dimension — exact in f32"
1636)]
1637fn rescaled_pixel(p: Point, from: (u32, u32), to: (u32, u32)) -> Point {
1638    if from == to {
1639        return p;
1640    }
1641    Point {
1642        x: p.x * (to.0 as f32 / from.0 as f32),
1643        y: p.y * (to.1 as f32 / from.1 as f32),
1644    }
1645}
1646
1647/// Whether a read of `symbology` is collected only once its bytes read
1648/// again beside its scan line (07-pipeline § Acceptance, rule 3): the
1649/// UPC/EAN symbologies, UPC-E, EAN-8, EAN-13 and UPC-A. rxing reads their
1650/// digits out of one line across a matrix symbol drawn with round or
1651/// heart-shaped modules, and reads them there at every scale of the image:
1652/// a read at an independent scale confirms them, and a check digit is one
1653/// chance in ten.
1654fn needs_second_line(symbology: Symbology) -> bool {
1655    bars(symbology).is_some()
1656}
1657
1658/// What the second line of a read knows of its symbol's bars.
1659#[derive(Debug, Clone, Copy, PartialEq)]
1660struct Bars {
1661    /// Modules between the two points rxing 0.9.4 reports for a read
1662    /// (`upc_ean_reader.rs`): the middle of the start guard, three modules
1663    /// wide, and the middle of the end pattern.
1664    span: f32,
1665}
1666
1667/// UPC-E: 51 modules, the last six its end pattern.
1668const UPCE: Bars = Bars { span: 46.5 };
1669
1670/// EAN-8: 67 modules, the last three its end guard.
1671const EAN8: Bars = Bars { span: 64.0 };
1672
1673/// EAN-13, and UPC-A, which is an EAN-13 led by a zero: 95 modules, the
1674/// last three its end guard.
1675const EAN13: Bars = Bars { span: 92.0 };
1676
1677/// The bars of a read of `symbology`; `None` for every symbology but the
1678/// UPC/EAN ones.
1679fn bars(symbology: Symbology) -> Option<Bars> {
1680    match symbology {
1681        Symbology::UpcE => Some(UPCE),
1682        Symbology::Ean8 => Some(EAN8),
1683        Symbology::Ean13 | Symbology::UpcA => Some(EAN13),
1684        _ => None,
1685    }
1686}
1687
1688/// Where a second line is looked for, in modules of the read.
1689///
1690/// Along the scan line, [`SECOND_LINE_REACH`] modules past each of its
1691/// points: half the end pattern, the quiet zone the reader requires after
1692/// it, and five modules for a symbol turned from the line, which slides
1693/// along it from one line to the next.
1694///
1695/// Beside the line, from [`SECOND_LINE_NEAR`] to [`SECOND_LINE_FAR`]
1696/// modules away, on either side. A line across round or heart-shaped
1697/// modules can read alike on the two sides of a module, so the bands start
1698/// some way from it. Three modules, for every symbology, is a measured
1699/// choice and not a bound (07-pipeline § Acceptance, rule 3): no width of a
1700/// matrix module follows from the bars of the read, since a line can cross
1701/// two lobes of one heart.
1702///
1703/// Through the line, turned about the middle of its points by
1704/// [`SECOND_LINE_TURN`] pixels across per pixel along (six degrees), either
1705/// way. Bars that are short, or turned from the rows, hold no straight line
1706/// three modules from the one that read them; they hold that line turned
1707/// toward them. Across a matrix the turned line ends more than two and a
1708/// half modules of the read from the first; that it then reads none of the
1709/// matrix's digits is measured (07-pipeline § Acceptance, rule 3).
1710const SECOND_LINE_REACH: f32 = 14.0;
1711const SECOND_LINE_NEAR: f32 = 3.0;
1712const SECOND_LINE_FAR: f32 = 8.0;
1713const SECOND_LINE_TURN: f32 = 0.105;
1714
1715/// The second lines of a read, in the order they are tried: the two bands
1716/// beside its scan line, then the line turned either way.
1717const SECOND_LINES: [fn(&ScanLine, &LumaImage) -> Option<LumaImage>; 4] = [
1718    |line, img| line.beside(img, true),
1719    |line, img| line.beside(img, false),
1720    |line, img| line.turned(img, SECOND_LINE_TURN),
1721    |line, img| line.turned(img, -SECOND_LINE_TURN),
1722];
1723
1724/// Whether `hit` reads again on a second line ([`SECOND_LINES`]): a pass of
1725/// its symbology alone over one of them, ended at the first read that
1726/// carries its bytes. The bars of a linear symbol are many modules tall, so
1727/// every line across them reads the same digits; digits read out of the
1728/// modules of a matrix symbol hold on one line, or on two that cross the
1729/// same modules. The scan line is the read's first two points: those of a
1730/// five-digit add-on, when rxing reads one after the symbol, follow them on
1731/// the same line. A read with fewer points, or whose line is no row and no
1732/// column of the image, has no second line and is not kept. Each line is
1733/// cut out of `img` when its turn comes, and none once `cancelled` answers
1734/// yes. Decoder panics caught on the lines are added to `panics`.
1735fn reads_on_a_second_line(
1736    img: &LumaImage,
1737    hit: &RawDetection,
1738    cancelled: &dyn Fn() -> bool,
1739    panics: &mut u8,
1740) -> bool {
1741    let ([a, b, ..], Some(bars)) = (hit.footprint.points.as_slice(), bars(hit.symbology)) else {
1742        return false;
1743    };
1744    let Some(line) = ScanLine::through(*a, *b, bars) else {
1745        return false;
1746    };
1747    SECOND_LINES.iter().any(|second| {
1748        if cancelled() {
1749            return false;
1750        }
1751        second(&line, img).is_some_and(|band| {
1752            let probe = engine::probe(&band, hit.symbology, EngineKind::Rxing, &|read| {
1753                read.raw == hit.raw
1754            });
1755            *panics = panics.saturating_add(probe.panics);
1756            probe.accepted
1757        })
1758    })
1759}
1760
1761/// The scan line of a read in its image: a row or a column, where its two
1762/// points lie along it, and a module of the read.
1763#[derive(Debug, Clone, Copy, PartialEq)]
1764struct ScanLine {
1765    /// A row of the image; a column otherwise.
1766    row: bool,
1767    /// The first point along the line, in pixels.
1768    first: f32,
1769    /// The second point along the line.
1770    last: f32,
1771    /// The row, or the column, the line is.
1772    line: f32,
1773    /// The points' distance over the modules between them
1774    /// ([`Bars::span`]), and no less than a pixel.
1775    module: f32,
1776}
1777
1778impl ScanLine {
1779    /// The line through `a` and `b`, the points of a read of a symbol with
1780    /// these `bars`, when it is a row or a column of the image: rxing's
1781    /// linear readers read the rows of an image and of its quarter turn, and
1782    /// nothing else.
1783    fn through(a: Point, b: Point, bars: Bars) -> Option<Self> {
1784        if ![a.x, a.y, b.x, b.y].iter().all(|v| v.is_finite()) {
1785            return None;
1786        }
1787        let (dx, dy) = ((b.x - a.x).abs(), (b.y - a.y).abs());
1788        let (row, column) = (dy < 1.0 && dx >= 1.0, dx < 1.0 && dy >= 1.0);
1789        if !(row || column) {
1790            return None;
1791        }
1792        let (first, last, line) = if row {
1793            (a.x.min(b.x), a.x.max(b.x), a.y)
1794        } else {
1795            (a.y.min(b.y), a.y.max(b.y), a.x)
1796        };
1797        Some(Self {
1798            row,
1799            first,
1800            last,
1801            line: line.floor(),
1802            module: ((last - first) / bars.span).max(1.0),
1803        })
1804    }
1805
1806    /// The pixels of `img` a second line holds along this one, from
1807    /// [`SECOND_LINE_REACH`] modules before the first point to as many past
1808    /// the second, the latter excluded; then how many pixels the image
1809    /// holds across the line.
1810    fn extent(&self, img: &LumaImage) -> (u32, u32, u32) {
1811        let (along, across) = if self.row {
1812            (img.width(), img.height())
1813        } else {
1814            (img.height(), img.width())
1815        };
1816        let reach = SECOND_LINE_REACH * self.module;
1817        (
1818            within((self.first - reach).floor(), along),
1819            within((self.last + reach).ceil(), along),
1820            across,
1821        )
1822    }
1823
1824    /// The band of `img` beside the line: the rows from
1825    /// [`SECOND_LINE_NEAR`] to [`SECOND_LINE_FAR`] modules away from a
1826    /// row's own, below it when `after` and above it otherwise; the columns
1827    /// to the right of a column, or to its left. `None` when the image
1828    /// holds none of it.
1829    fn beside(&self, img: &LumaImage, after: bool) -> Option<LumaImage> {
1830        let (start, end, across) = self.extent(img);
1831        let near = (SECOND_LINE_NEAR * self.module).ceil();
1832        let far = (SECOND_LINE_FAR * self.module).ceil();
1833        let (from, to) = if after {
1834            (self.line + near, self.line + far)
1835        } else {
1836            (self.line - far + 1.0, self.line - near + 1.0)
1837        };
1838        let (from, to) = (within(from, across), within(to, across));
1839        (start < end && from < to).then(|| {
1840            if self.row {
1841                cropped(img, (start, from), (end, to))
1842            } else {
1843                cropped(img, (from, start), (to, end))
1844            }
1845        })
1846    }
1847
1848    /// The line turned about the middle of its points, `turn` pixels
1849    /// across per pixel along: the pixels of `img` on the turned line and on
1850    /// the lines a module either side of it, laid as the rows of a row's
1851    /// band and the columns of a column's. Where a turned line leaves the
1852    /// image across, it reads the image's edge. `None` when the image holds
1853    /// nothing along the line.
1854    #[expect(
1855        clippy::cast_precision_loss,
1856        clippy::cast_possible_truncation,
1857        clippy::cast_sign_loss,
1858        reason = "finite pixel bounds clamped to the validated, engine-capped image"
1859    )]
1860    fn turned(&self, img: &LumaImage, turn: f32) -> Option<LumaImage> {
1861        let (start, end, across) = self.extent(img);
1862        let middle = f32::midpoint(self.first, self.last);
1863        let depth = self.module.ceil() as u32;
1864        let stride = img.width() as usize;
1865        let pixel = |along: u32, beside: u32| {
1866            let rise = (turn * (along as f32 + 0.5 - middle)).round();
1867            let at = within(
1868                self.line + rise + beside as f32 - depth as f32,
1869                across.saturating_sub(1),
1870            ) as usize;
1871            let (x, y) = if self.row {
1872                (along as usize, at)
1873            } else {
1874                (at, along as usize)
1875            };
1876            img.data()[y * stride + x]
1877        };
1878        (start < end).then(|| {
1879            let (width, height) = if self.row {
1880                (end - start, 2 * depth + 1)
1881            } else {
1882                (2 * depth + 1, end - start)
1883            };
1884            let data = (0..height)
1885                .flat_map(|y| (0..width).map(move |x| (x, y)))
1886                .map(|(x, y)| {
1887                    if self.row {
1888                        pixel(start + x, y)
1889                    } else {
1890                        pixel(start + y, x)
1891                    }
1892                })
1893                .collect();
1894            LumaImage::new(data, width, height)
1895        })
1896    }
1897}
1898
1899/// `v` as a pixel bound: no less than zero, no more than `limit`.
1900#[expect(
1901    clippy::cast_precision_loss,
1902    clippy::cast_possible_truncation,
1903    clippy::cast_sign_loss,
1904    reason = "finite pixel bounds clamped to the validated, engine-capped image"
1905)]
1906fn within(v: f32, limit: u32) -> u32 {
1907    v.clamp(0.0, limit as f32) as u32
1908}
1909
1910/// The pixels of `img` from `(left, top)` to `(right, bottom)`, the latter
1911/// excluded, both inside the image.
1912fn cropped(img: &LumaImage, (left, top): (u32, u32), (right, bottom): (u32, u32)) -> LumaImage {
1913    let stride = img.width() as usize;
1914    let mut data = Vec::with_capacity((right - left) as usize * (bottom - top) as usize);
1915    for y in top as usize..bottom as usize {
1916        data.extend_from_slice(
1917            &img.data()[y * stride + left as usize..y * stride + right as usize],
1918        );
1919    }
1920    LumaImage::new(data, right - left, bottom - top)
1921}
1922
1923/// What is left out of an rxing pass under `filter` where nothing but
1924/// QR-family symbols can be read ([`Run::decode`]), if anything: the whole
1925/// pass (`Some(None)`) when `filter` reads no QR-family symbology; the
1926/// `DataBar` Expanded reader's own pass over the image when `filter` reads
1927/// that symbology and the QR family (that pass reads `DataBar` Expanded
1928/// alone); `None` otherwise. What stays is the pass under `filter`, so
1929/// every QR-family read stays. Single-symbology passes never come here.
1930#[cfg(feature = "engine-rxing")]
1931#[expect(clippy::option_option, reason = "as is (None), no rxing (Some(None))")]
1932fn narrowed(filter: engine::FormatFilter) -> Option<Option<engine::RxingPass>> {
1933    use engine::FormatFilter as F;
1934    match filter {
1935        F::All => Some(Some(engine::RxingPass::WithoutExpanded(filter))),
1936        F::NonQr => Some(None),
1937        F::Set(set) if set.qr_family().is_empty() && !set.non_qr().is_empty() => Some(None),
1938        F::Set(set) if !set.qr_family().is_empty() && set.contains(Symbology::DataBarExpanded) => {
1939            Some(Some(engine::RxingPass::WithoutExpanded(filter)))
1940        }
1941        F::QrFamily | F::Only(_) | F::Set(_) => None,
1942    }
1943}
1944
1945/// The most modules along a side of a QR-family symbol: a version 40 QR
1946/// Code's 177 (an rMQR has at most 139 along its long side, a Micro QR 17).
1947#[cfg(feature = "engine-rxing")]
1948const MOST_MODULES: u16 = 177;
1949
1950/// The QR-family symbol measured at `region` and how far past it one of
1951/// its modules reaches: its grid's outer corners and their mean side over
1952/// its modules, or, where no reader measured a grid, the region's corners
1953/// and their mean side over [`MOST_MODULES`] — never more than one of its
1954/// mean modules, whatever the symbol (under perspective, a module along the
1955/// far edge is smaller than the mean).
1956#[cfg(feature = "engine-rxing")]
1957fn grown(region: engine::MatrixRegion) -> ([Point; 4], f32) {
1958    let (corners, modules) = region.grid.map_or((region.corners, MOST_MODULES), |grid| {
1959        (grid.outer, grid.modules)
1960    });
1961    (corners, mean_side(corners) / f32::from(modules))
1962}
1963
1964/// The grid rqrr located at `candidate` by format information that reads:
1965/// its corners, and its 17 + 4 × version modules along a side.
1966#[cfg(feature = "engine-rxing")]
1967fn located_region(candidate: &crate::rescue::RescueCandidate) -> engine::MatrixRegion {
1968    let modules = 17 + 4 * usize::from(candidate.version);
1969    engine::MatrixRegion {
1970        corners: candidate.corners,
1971        grid: engine::Grid::of_rqrr(candidate.corners, modules, candidate.pixel),
1972    }
1973}
1974
1975/// The mean length of the four sides of `quad`.
1976#[cfg(feature = "engine-rxing")]
1977fn mean_side(quad: [Point; 4]) -> f32 {
1978    (0..4)
1979        .map(|i| {
1980            let (a, b) = (quad[i], quad[(i + 1) % 4]);
1981            (b.x - a.x).hypot(b.y - a.y)
1982        })
1983        .sum::<f32>()
1984        / 4.0
1985}
1986
1987/// Whether every pixel of `img` whose centre lies outside each of `regions`
1988/// has one value — true when none does. A region is a convex quad grown
1989/// outward by its distance: a centre is inside when it is no farther than
1990/// that outside each of the quad's four sides. A region that is no convex
1991/// quad of finite points, or whose distance is not finite, holds no pixel.
1992#[cfg(feature = "engine-rxing")]
1993fn flat_outside(img: &LumaImage, regions: &[([Point; 4], f32)]) -> bool {
1994    let width = img.width() as usize;
1995    let sides: Vec<[[f32; 3]; 4]> = regions
1996        .iter()
1997        .filter_map(|&(quad, grown)| half_planes(quad, grown))
1998        .collect();
1999    let mut value = None;
2000    let mut spans = Vec::new();
2001    for (y, row) in img.data().chunks_exact(width.max(1)).enumerate() {
2002        #[expect(
2003            clippy::cast_precision_loss,
2004            reason = "a row of the validated, engine-capped image: exact in f32"
2005        )]
2006        let centre = y as f32 + 0.5;
2007        spans.clear();
2008        spans.extend(sides.iter().map(|planes| row_span(planes, centre, width)));
2009        spans.push((width, width));
2010        spans.sort_unstable();
2011        let mut x = 0;
2012        for &(start, end) in &spans {
2013            if start > x {
2014                let outside = &row[x..start];
2015                let one = *value.get_or_insert(outside[0]);
2016                if outside.iter().any(|&pixel| pixel != one) {
2017                    return false;
2018                }
2019            }
2020            x = x.max(end);
2021        }
2022    }
2023    true
2024}
2025
2026/// The four sides of a convex quad grown by `grown`, each as `[a, b, c]`: a
2027/// point (x, y) is inside when `a·x + b·y + c ≥ 0` for each. `None` for a
2028/// quad that is not convex, a point or a distance that is not finite.
2029#[cfg(feature = "engine-rxing")]
2030fn half_planes(quad: [Point; 4], grown: f32) -> Option<[[f32; 3]; 4]> {
2031    if !grown.is_finite() {
2032        return None;
2033    }
2034    let turns: [f32; 4] = std::array::from_fn(|i| {
2035        let (a, b, c) = (quad[i], quad[(i + 1) % 4], quad[(i + 2) % 4]);
2036        (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
2037    });
2038    let sign = if turns.iter().all(|v| v.is_finite() && *v > 0.0) {
2039        1.0
2040    } else if turns.iter().all(|v| v.is_finite() && *v < 0.0) {
2041        -1.0
2042    } else {
2043        return None;
2044    };
2045    // no corner is infinite or NaN (its turns would be too), no side a point (two would be 0)
2046    let mut planes = [[0.0; 3]; 4];
2047    for (i, plane) in planes.iter_mut().enumerate() {
2048        let (a, b) = (quad[i], quad[(i + 1) % 4]);
2049        let (dx, dy) = (b.x - a.x, b.y - a.y);
2050        let length = dx.hypot(dy);
2051        // the signed distance of (x, y) to the side, positive inward:
2052        // sign · (dx · (y - a.y) - dy · (x - a.x)) / length
2053        let (along_x, along_y) = (-sign * dy / length, sign * dx / length);
2054        *plane = [along_x, along_y, grown - along_x * a.x - along_y * a.y];
2055    }
2056    Some(planes)
2057}
2058
2059/// The pixels of the row at `centre` whose centres are inside `planes`
2060/// ([`half_planes`]), as `start..end` within `0..width`, empty when none is.
2061#[cfg(feature = "engine-rxing")]
2062#[expect(
2063    clippy::cast_precision_loss,
2064    clippy::cast_possible_truncation,
2065    clippy::cast_sign_loss,
2066    reason = "a column of the validated, engine-capped image, clamped to it"
2067)]
2068fn row_span(planes: &[[f32; 3]; 4], centre: f32, width: usize) -> (usize, usize) {
2069    let (mut low, mut high) = (f32::NEG_INFINITY, f32::INFINITY);
2070    for &[a, b, c] in planes {
2071        // a · x + rest ≥ 0. A side along the row has a = ±0: the bound is
2072        // then -∞ or +∞ (the whole row or none of it), or NaN on the
2073        // boundary itself, which max and min pass over (the row is inside)
2074        let rest = b * centre + c;
2075        if a.is_sign_positive() {
2076            low = low.max(-rest / a);
2077        } else {
2078            high = high.min(-rest / a);
2079        }
2080    }
2081    // a pixel x is inside when low ≤ x + 0.5 ≤ high
2082    let start = (low - 0.5).ceil().clamp(0.0, width as f32) as usize;
2083    let end = ((high - 0.5).floor() + 1.0).clamp(0.0, width as f32) as usize;
2084    (start, end.max(start))
2085}
2086
2087/// The non-QR completion searches outside already decoded QR symbols.
2088/// Preserve every pixel outside the actual convex footprint: its bounding
2089/// rectangle could also contain a genuine adjacent barcode. This plane is
2090/// never used to measure or score the original symbols.
2091#[cfg(feature = "engine-rxing")]
2092#[expect(
2093    clippy::cast_precision_loss,
2094    clippy::cast_possible_truncation,
2095    clippy::cast_sign_loss,
2096    reason = "finite pixel bounds clamped to the validated, engine-capped image"
2097)]
2098fn exclude_matrix_regions(img: &LumaImage, regions: &[[Point; 4]]) -> LumaImage {
2099    let mut data = img.data().to_vec();
2100    for region in regions {
2101        if !region.iter().all(|p| p.x.is_finite() && p.y.is_finite()) {
2102            continue;
2103        }
2104        let turns: [f32; 4] = std::array::from_fn(|i| {
2105            let (a, b, c) = (region[i], region[(i + 1) % 4], region[(i + 2) % 4]);
2106            (b.x - a.x) * (c.y - b.y) - (b.y - a.y) * (c.x - b.x)
2107        });
2108        if !turns.iter().all(|v| v.is_finite() && *v > 0.0)
2109            && !turns.iter().all(|v| v.is_finite() && *v < 0.0)
2110        {
2111            continue;
2112        }
2113        let bounds = |axis: fn(&Point) -> f32, limit: u32| {
2114            let lo = region.iter().map(axis).fold(f32::INFINITY, f32::min);
2115            let hi = region.iter().map(axis).fold(f32::NEG_INFINITY, f32::max);
2116            (
2117                lo.floor().clamp(0.0, limit as f32) as u32,
2118                hi.ceil().clamp(0.0, limit as f32) as u32,
2119            )
2120        };
2121        let (left, right) = bounds(|p| p.x, img.width());
2122        let (top, bottom) = bounds(|p| p.y, img.height());
2123        for y in top..bottom {
2124            for x in left..right {
2125                let (px, py) = (x as f32 + 0.5, y as f32 + 0.5);
2126                let sides: [f32; 4] = std::array::from_fn(|i| {
2127                    let (a, b) = (region[i], region[(i + 1) % 4]);
2128                    (b.x - a.x) * (py - a.y) - (b.y - a.y) * (px - a.x)
2129                });
2130                if sides.iter().all(|v| *v >= 0.0) || sides.iter().all(|v| *v <= 0.0) {
2131                    data[(y * img.width() + x) as usize] = 255;
2132                }
2133            }
2134        }
2135    }
2136    LumaImage::new(data, img.width(), img.height())
2137}
2138
2139/// Execute the ladder over normalized planes. `deadline` is the WHOLE-scan
2140/// wall-clock bound, shared with the scoring stage (computed by the caller).
2141pub(crate) fn run(
2142    planes: &SourcePlanes,
2143    config: &ScanConfig,
2144    cancel: &CancelToken,
2145    deadline: Option<Instant>,
2146) -> Result<LadderOutcome> {
2147    run_seeded(planes, config, cancel, deadline, Seed::default())
2148}
2149
2150/// What each stage of a walk reads: everything, or the listed symbologies
2151/// and their part inside or outside the QR family (`None`: the stage has
2152/// nothing to read and is not planned).
2153struct StageFormats {
2154    /// The symbologies [`ScanConfig::formats`] lists; `None`: unrestricted.
2155    listed: Option<engine::Formats>,
2156    /// The stages that read every family.
2157    every: engine::FormatFilter,
2158    /// The QR-calibrated recovery stage.
2159    qr_family: Option<engine::FormatFilter>,
2160    /// The native-resolution completion after a pyramid read.
2161    #[cfg(feature = "engine-rxing")]
2162    non_qr: Option<engine::FormatFilter>,
2163}
2164
2165impl StageFormats {
2166    fn of(config: &ScanConfig) -> Self {
2167        let listed = (!config.formats.is_empty()).then(|| engine::Formats::of(&config.formats));
2168        Self {
2169            listed,
2170            every: listed.map_or(engine::FormatFilter::All, engine::FormatFilter::Set),
2171            qr_family: match listed {
2172                None => Some(engine::FormatFilter::QrFamily),
2173                Some(set) => (!set.qr_family().is_empty())
2174                    .then(|| engine::FormatFilter::Set(set.qr_family())),
2175            },
2176            #[cfg(feature = "engine-rxing")]
2177            non_qr: match listed {
2178                None => Some(engine::FormatFilter::NonQr),
2179                Some(set) => {
2180                    (!set.non_qr().is_empty()).then(|| engine::FormatFilter::Set(set.non_qr()))
2181                }
2182            },
2183        }
2184    }
2185
2186    /// What the scan looked for, as the trace states it: each listed
2187    /// symbology once, in declaration order (an unrestricted scan says
2188    /// nothing).
2189    fn listed(&self) -> Option<Vec<crate::report::Symbology>> {
2190        self.listed.map(|set| {
2191            crate::report::Symbology::ALL
2192                .into_iter()
2193                .filter(|symbology| set.contains(*symbology))
2194                .collect()
2195        })
2196    }
2197}
2198
2199/// [`run`], starting from another walk's refusals, the contents its parses
2200/// read and the re-reads it spent — the opposite-background walk of an
2201/// alpha fallback.
2202pub(crate) fn run_seeded(
2203    planes: &SourcePlanes,
2204    config: &ScanConfig,
2205    cancel: &CancelToken,
2206    deadline: Option<Instant>,
2207    seed: Seed,
2208) -> Result<LadderOutcome> {
2209    let started = Instant::now();
2210    // Engines never see anything bigger than max_engine_side: one rxing
2211    // TryHarder pass on a huge image is an unbounded, uninterruptible burn.
2212    let work = transform::downscale_to(&planes.luma, config.max_engine_side);
2213    let mut run = Run::new(
2214        cancel,
2215        deadline,
2216        (planes.luma.width(), planes.luma.height()),
2217        seed,
2218    );
2219    let mut stages = Vec::new();
2220    let luma = &work;
2221    run.plane = Some(luma);
2222    let longest = luma.width().max(luma.height());
2223    let reads = StageFormats::of(config);
2224
2225    // Each gate admits a stage the walk reaches and plans (`Run::admit`):
2226    // one the deadline already prevents is a cut, not a skip.
2227    'ladder: {
2228        // S1 — pyramid: a ≤pyramid_side downscale is the cheapest decode AND
2229        // often the most effective one on artistic codes.
2230        if config.pyramid && longest > config.pyramid_side && run.admit() {
2231            let side = config.pyramid_side;
2232            let stop = run.stage(
2233                "pyramid",
2234                vec![Attempt::plain(move || transform::downscale_to(luma, side))],
2235                reads.every,
2236                &mut stages,
2237            )?;
2238            if stop || run.store.settled() {
2239                // A QR surviving the thumbnail says nothing about a nearby
2240                // barcode or matrix code: its narrow bars or small modules
2241                // may have disappeared in that downscale. Complete the enabled
2242                // direct stage for non-QR families before accepting the exit.
2243                // This remains a planned, budgeted attempt, with ordinary
2244                // cancellation and trace accounting. A thumbnail that read
2245                // only other symbologies still ends the walk (07-pipeline
2246                // property 2 states the known loss).
2247                #[cfg(feature = "engine-rxing")]
2248                if let Some(non_qr) = reads.non_qr
2249                    && !stop
2250                    && config.direct
2251                    && run
2252                        .store
2253                        .reconcile()
2254                        .iter()
2255                        .any(|d| d.symbology.is_qr_family())
2256                {
2257                    let regions = run.store.qr_regions();
2258                    let original = run.orig;
2259                    let _ = run.stage(
2260                        "direct",
2261                        vec![Attempt::plain(move || {
2262                            let work = (luma.width(), luma.height());
2263                            let regions: Vec<_> = regions
2264                                .iter()
2265                                .map(|region| rescaled(region.corners, original, work))
2266                                .collect();
2267                            exclude_matrix_regions(luma, &regions)
2268                        })],
2269                        non_qr,
2270                        &mut stages,
2271                    )?;
2272                }
2273                break 'ladder;
2274            }
2275        }
2276
2277        // S2 — direct full resolution.
2278        if config.direct && run.admit() {
2279            let stop = run.stage(
2280                "direct",
2281                vec![Attempt::plain(|| luma.clone())],
2282                reads.every,
2283                &mut stages,
2284            )?;
2285            if stop || run.store.settled() {
2286                break 'ladder;
2287            }
2288        }
2289
2290        // S3 — enhance: fixed transform set at full resolution.
2291        if config.enhance && run.admit() {
2292            let mut attempts: Vec<Attempt<'_>> = vec![
2293                Attempt::plain(|| transform::otsu_threshold(luma)),
2294                Attempt::inverting(|| transform::invert(luma)),
2295                Attempt::plain(|| transform::contrast_stretch(luma)),
2296            ];
2297            if planes.has_color() {
2298                let cap = config.max_engine_side;
2299                for channel in [Channel::R, Channel::G, Channel::B] {
2300                    // LAZY: channel extraction walks the full-res RGB buffer
2301                    // — built only when this attempt actually runs, so the
2302                    // cost lands AFTER the per-attempt budget check
2303                    attempts.push(Attempt::plain(move || {
2304                        let plane = planes.channel(channel).unwrap_or_else(|| luma.clone());
2305                        transform::downscale_to(&plane, cap)
2306                    }));
2307                }
2308            }
2309            let stop = run.stage("enhance", attempts, reads.every, &mut stages)?;
2310            if stop || run.store.settled() {
2311                break 'ladder;
2312            }
2313        }
2314
2315        // S4 — deep: the curated boost rungs (v0.2 empirical known-good)
2316        // first, then the size × contrast × binarization grid.
2317        if let Some(qr_family) = reads.qr_family
2318            && config.deep
2319            && run.admit()
2320        {
2321            // deep is QR-calibrated recovery: the multi-format detectors on
2322            // 17 rungs would starve the budget for nothing
2323            let _ = run.stage("deep", deep_attempts(luma, longest), qr_family, &mut stages)?;
2324        }
2325
2326        // S5 — rescue: erasure-aware RS over grids the engines detected
2327        // but could not decode (the logo-occlusion class). Only when the
2328        // ladder published nothing — a decoded symbol never needs rescuing.
2329        run.rescue_stage(luma, &mut stages)?;
2330    }
2331    let mut outcome = run.finish(stages, started, &planes.luma)?;
2332    outcome.trace.formats = reads.listed();
2333    Ok(outcome)
2334}
2335
2336impl Run<'_> {
2337    /// End of the walk, every early exit included: the candidates collected
2338    /// in other attempts than the reads they locate or refuse (at most
2339    /// `MAX_RESCUE_CANDIDATES` clean re-derivations, no sampling — past the
2340    /// deadline too, after a last cancellation check), then the
2341    /// reconciliation of the whole read set, each content interpreted
2342    /// ONCE and its observations grouped into occurrences over the original
2343    /// `luma` (whatever the deadline: bounded comparisons).
2344    fn finish(
2345        mut self,
2346        stages: Vec<StageTrace>,
2347        started: Instant,
2348        luma: &LumaImage,
2349    ) -> Result<LadderOutcome> {
2350        self.check_cancel()?;
2351        let attempt = self.next_attempt();
2352        let (parses, refusals) = Self::rederive(&self.rescue_candidates, attempt, self.orig, 0);
2353        for refusal in refusals {
2354            self.store.refuse(refusal, attempt);
2355        }
2356        for read in parses {
2357            self.store.collect(read);
2358        }
2359        // PRIMARY-detection contract: QR family first, then by earliest
2360        // read — on a flyer carrying a QR + a retail barcode, the scored
2361        // "primary" (detections[0]) never depends on detector order
2362        let (reconciled, detections_saturated) = self.store.reconcile_counted();
2363        let contents: Vec<(ContentKey, Reading)> = reconciled
2364            .iter()
2365            .map(|detection| {
2366                let reading = content::read(
2367                    &detection.key.raw,
2368                    &detection.key.eci,
2369                    &detection.segments,
2370                    detection.engine_reading,
2371                    detection.symbology.is_qr_family(),
2372                );
2373                (detection.key.clone(), reading)
2374            })
2375            .collect();
2376        let mut occurrences_saturated = false;
2377        let merged = reconciled
2378            .iter()
2379            .zip(&contents)
2380            .map(|(detection, (_, reading))| {
2381                let (occurrences, saturated) =
2382                    occurrence::group(detection.symbology, detection.observations.clone(), luma);
2383                occurrences_saturated |= saturated | detection.observations_dropped;
2384                merged_detection(
2385                    detection,
2386                    reading,
2387                    occurrences.into_iter().map(|o| o.footprint).collect(),
2388                )
2389            })
2390            .collect();
2391        Ok(LadderOutcome {
2392            merged,
2393            contents,
2394            rereads: self.rereads,
2395            trace: PipelineTrace {
2396                stages,
2397                engine_panics: self.panics,
2398                total_ms: started.elapsed().as_secs_f64() * 1_000.0,
2399                budget_exhausted: Some(self.cut),
2400                saturation: Some(Saturation {
2401                    reads: self.store.dropped > 0 || self.store.failed_closed(),
2402                    detections: detections_saturated,
2403                    occurrences: occurrences_saturated,
2404                }),
2405                formats: None,
2406            },
2407            store: self.store,
2408        })
2409    }
2410}
2411
2412#[cfg(test)]
2413impl Run<'_> {
2414    /// [`Run::finish`] over a blank plane of the original size: for walks
2415    /// built from reads without an image. Linear footprints compare as
2416    /// inconclusive there (one symbol); matrix grouping never reads pixels.
2417    fn finish_blank(self, stages: Vec<StageTrace>, started: Instant) -> Result<LadderOutcome> {
2418        let (width, height) = self.orig;
2419        let blank = LumaImage::new(vec![255; width as usize * height as usize], width, height);
2420        self.finish(stages, started, &blank)
2421    }
2422}
2423
2424/// A reconciled content as the score and the report see it, with its
2425/// occurrences (earliest observed first).
2426fn merged_detection(
2427    detection: &Reconciled,
2428    reading: &Reading,
2429    occurrences: Vec<Footprint>,
2430) -> MergedDetection {
2431    let (masked_stream, version, ec, mask) = match &detection.geometry.stream {
2432        Some((stream, version, ec, mask)) => {
2433            (Some(stream.clone()), Some(*version), Some(*ec), Some(*mask))
2434        }
2435        None => (None, None, detection.geometry.ec, None),
2436    };
2437    MergedDetection {
2438        symbology: detection.symbology,
2439        raw: detection.key.raw.clone(),
2440        text: reading.text.clone(),
2441        charset: reading.charset,
2442        masked_stream,
2443        corners: detection.geometry.corners.map(|(corners, _)| corners),
2444        version,
2445        ec,
2446        mask,
2447        fnc1: detection.key.fnc1 == Fnc1::First,
2448        photometric_inverted: detection
2449            .geometry
2450            .corners
2451            .is_some_and(|(_, inverted)| inverted),
2452        engines: detection.engines.clone(),
2453        occurrences,
2454    }
2455}
2456
2457#[cfg(test)]
2458mod tests {
2459    #![allow(clippy::unwrap_used, clippy::expect_used)]
2460
2461    use super::*;
2462    use crate::input::{ImageInput, Limits};
2463    use crate::transform::normalize;
2464
2465    #[test]
2466    fn profile_presets_pinned() {
2467        let full = ScanProfile::Full.config();
2468        assert!(full.pyramid && full.direct && full.enhance && full.deep);
2469        assert_eq!(full.budget_ms, Some(4_000));
2470        assert_eq!(full.pyramid_side, 512);
2471
2472        let fast = ScanProfile::Fast.config();
2473        assert!(fast.pyramid && fast.direct && fast.enhance && !fast.deep);
2474        assert_eq!(fast.budget_ms, Some(800));
2475
2476        let frame = ScanProfile::Frame.config();
2477        assert!(frame.pyramid && frame.direct && !frame.enhance && !frame.deep);
2478        assert_eq!(frame.budget_ms, Some(80));
2479        assert_eq!(full.score_depth, ScoreDepth::Full);
2480        assert_eq!(fast.score_depth, ScoreDepth::Reduced);
2481        assert_eq!(frame.score_depth, ScoreDepth::Off);
2482
2483        assert_eq!(ScanProfile::default(), ScanProfile::Full);
2484    }
2485
2486    /// Arbitrary-angle robustness is a measured engine CAPABILITY — pin it.
2487    /// The 2026-07-08 H-12 probes could not construct a failing synthetic:
2488    /// clean and degraded renders decode at every angle down to 2 px
2489    /// modules (the real-photo qrcode-5 losses at 15–45° need photo noise
2490    /// our synthesis cannot reproduce, and a derotate rung was REFUTED as
2491    /// untestable). This test freezes that capability against engine bumps:
2492    /// if an rqrr/rxing upgrade breaks diagonal detection, this is the
2493    /// tripwire — not a corpus re-run six weeks later.
2494    #[test]
2495    fn rotated_synthetic_decodes_at_arbitrary_angles() {
2496        let text = "arbitrary-angle capability pin";
2497        let code = qrcode::QrCode::with_version(
2498            text.as_bytes(),
2499            qrcode::Version::Normal(5),
2500            qrcode::EcLevel::M,
2501        )
2502        .unwrap();
2503        let img = code
2504            .render::<image::Luma<u8>>()
2505            .module_dimensions(3, 3)
2506            .build();
2507        let base = LumaImage::new(img.to_vec(), img.width(), img.height());
2508        for angle in [15.0_f32, 30.0, 45.0] {
2509            let rotated = crate::score::warp::rotate(&base, angle);
2510            let planes = normalize(
2511                &ImageInput::luma8(rotated.data(), rotated.width(), rotated.height()),
2512                &Limits::default(),
2513            )
2514            .unwrap();
2515            // budget-free: capability, not latency, is what this pins
2516            let mut config = ScanConfig::full();
2517            config.budget_ms = None;
2518            let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
2519            assert!(
2520                outcome.merged.iter().any(|m| m.text == text),
2521                "{angle}°: engines lost arbitrary-angle detection — an engine \
2522                 regression, not an image problem (rotation is synthetic-clean)"
2523            );
2524        }
2525    }
2526
2527    #[test]
2528    fn precancelled_token_short_circuits() {
2529        let data = vec![255u8; 64 * 64];
2530        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
2531        let cancel = CancelToken::new();
2532        cancel.cancel();
2533        let err = run(&planes, &ScanConfig::full(), &cancel, None).unwrap_err();
2534        assert_eq!(err.code(), "QRS-005");
2535    }
2536
2537    #[test]
2538    fn zero_budget_returns_empty_without_attempts() {
2539        let data = vec![255u8; 64 * 64];
2540        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
2541        let mut config = ScanConfig::full();
2542        config.budget_ms = Some(0);
2543        let deadline = Some(Instant::now());
2544        let outcome = run(&planes, &config, &CancelToken::new(), deadline).unwrap();
2545        assert!(outcome.merged.is_empty());
2546        let attempts: u32 = outcome
2547            .trace
2548            .stages
2549            .iter()
2550            .map(|s| s.transforms_tried)
2551            .sum();
2552        assert_eq!(attempts, 0, "zero budget must not run engine attempts");
2553        assert_eq!(
2554            outcome.trace.budget_exhausted,
2555            Some(true),
2556            "every planned stage was cut at its gate: not a final no-QR"
2557        );
2558    }
2559
2560    #[test]
2561    fn white_image_walks_the_whole_ladder_and_stays_empty() {
2562        let data = vec![255u8; 64 * 64];
2563        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
2564        let mut config = ScanConfig::full();
2565        config.budget_ms = None;
2566        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
2567        assert!(outcome.merged.is_empty());
2568        // 64px image: pyramid skipped (≤512), direct + enhance + deep ran.
2569        let names: Vec<&str> = outcome
2570            .trace
2571            .stages
2572            .iter()
2573            .map(|s| s.stage.as_str())
2574            .collect();
2575        assert_eq!(names, vec!["direct", "enhance", "deep"]);
2576        // luma-only source: no channel attempts in enhance.
2577        assert_eq!(outcome.trace.stages[1].transforms_tried, 3);
2578        // deep on a small image: 15 deep rungs (12 boost + 3 morph) +
2579        // full-res stretch×{otsu,invert}.
2580        assert_eq!(outcome.trace.stages[2].transforms_tried, 17);
2581        assert_eq!(
2582            outcome.trace.budget_exhausted,
2583            Some(false),
2584            "an unbounded walk never cuts"
2585        );
2586    }
2587
2588    #[test]
2589    fn profile_wire_names_round_trip() {
2590        // THE cross-language name mapping — bindings and CLI all parse
2591        // through here (drift in any arm breaks a published flag).
2592        assert_eq!(ScanProfile::from_name("full"), Some(ScanProfile::Full));
2593        assert_eq!(ScanProfile::from_name("fast"), Some(ScanProfile::Fast));
2594        assert_eq!(ScanProfile::from_name("frame"), Some(ScanProfile::Frame));
2595        assert_eq!(ScanProfile::from_name("FULL"), None);
2596        assert_eq!(ScanProfile::from_name(""), None);
2597    }
2598
2599    #[test]
2600    fn score_checks_parse_from_their_wire_names_only() {
2601        // the bindings' and the CLI's `score_skip_checks` seam: every
2602        // section from its report field name, nothing from any other
2603        // spelling
2604        for (name, check) in [
2605            ("uec", ScoreCheck::Uec),
2606            ("iso15415", ScoreCheck::Iso15415),
2607            ("alpha_envelope", ScoreCheck::AlphaEnvelope),
2608        ] {
2609            assert_eq!(ScoreCheck::from_name(name), Some(check), "{name}");
2610        }
2611        for name in ["", "UEC", "iso_15415", "alpha-envelope", "envelope"] {
2612            assert_eq!(ScoreCheck::from_name(name), None, "{name}");
2613        }
2614    }
2615
2616    #[test]
2617    fn boost_rung_resize_zero_keeps_native_resolution() {
2618        // resize: 0 means "work at native res" — NOT a 0-px downscale.
2619        let img = LumaImage::new(vec![128u8; 64 * 32], 64, 32);
2620        let rung = Rung::Boost {
2621            resize: 0,
2622            contrast: 2.5,
2623            brightness: 1.0,
2624            blur: 0.0,
2625        };
2626        let out = rung.apply(&img);
2627        assert_eq!((out.width(), out.height()), (64, 32));
2628    }
2629
2630    #[test]
2631    fn boost_rung_blurs_only_above_sigma_point_three() {
2632        let mut pixels = vec![0; 5 * 3];
2633        pixels[7] = 255;
2634        let img = LumaImage::new(pixels, 5, 3);
2635        let apply = |blur| {
2636            Rung::Boost {
2637                resize: 0,
2638                contrast: 1.0,
2639                brightness: 1.0,
2640                blur,
2641            }
2642            .apply(&img)
2643        };
2644
2645        let at_threshold = apply(0.3);
2646        assert_eq!((at_threshold.width(), at_threshold.height()), (5, 3));
2647        assert_eq!(at_threshold.data(), img.data());
2648
2649        // A sharp impulse makes even the smallest admitted blur observable.
2650        let sigma = f32::from_bits(0.3_f32.to_bits() + 1);
2651        let above_threshold = apply(sigma);
2652        let blurred = transform::gaussian_blur(&img, sigma);
2653        assert_eq!((above_threshold.width(), above_threshold.height()), (5, 3));
2654        assert_ne!(blurred.data(), img.data());
2655        assert_eq!(above_threshold.data(), blurred.data());
2656    }
2657
2658    #[test]
2659    fn morph_rungs_close_gaps_and_hit_their_target_size() {
2660        // checkerboard of 2px dark dots with 2px gaps — a close with a
2661        // big-enough kernel turns the dark quadrant solid black.
2662        let side = 840u32;
2663        let mut data = vec![255u8; (side * side) as usize];
2664        for y in 0..side {
2665            for x in 0..side {
2666                if (x / 2 + y / 2) % 2 == 0 {
2667                    data[(y * side + x) as usize] = 0;
2668                }
2669            }
2670        }
2671        let img = LumaImage::new(data, side, side);
2672        let rung = Rung::MorphCloseDark {
2673            divisor: 93, // k = 840/93 = 9 ≥ gap span
2674            target: 360,
2675        };
2676        let out = rung.apply(&img);
2677        assert_eq!((out.width(), out.height()), (360, 360));
2678        assert!(
2679            out.data().iter().all(|&p| p == 0),
2680            "close must merge the dot grid into solid dark"
2681        );
2682    }
2683}
2684
2685#[cfg(test)]
2686mod probe {
2687    //! Dev diagnostics — `cargo nextest run probe_ --run-ignored all --no-capture`.
2688    //! Sweeps the transform space over a corpus image to inform ladder order.
2689    #![allow(clippy::unwrap_used, clippy::expect_used)]
2690
2691    use super::*;
2692    use crate::input::{ImageInput, Limits};
2693    use crate::transform::normalize;
2694
2695    #[test]
2696    #[ignore = "dev diagnostic, not a contract"]
2697    fn probe_artistic_transform_space() {
2698        let path = format!(
2699            "{}/../../fixtures/artistic/OK_1069ms_85_8b6a54b3.png",
2700            env!("CARGO_MANIFEST_DIR")
2701        );
2702        let bytes = std::fs::read(path).unwrap();
2703        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
2704        let luma = &planes.luma;
2705        println!("image {}x{}", luma.width(), luma.height());
2706
2707        let sizes: [Option<u32>; 5] = [None, Some(800), Some(512), Some(384), Some(256)];
2708        let mut planes_set: Vec<(String, LumaImage)> = vec![("luma".into(), luma.clone())];
2709        for channel in [Channel::R, Channel::G, Channel::B] {
2710            if let Some(p) = planes.channel(channel) {
2711                planes_set.push((format!("{channel:?}"), p));
2712            }
2713        }
2714        for (plane_name, plane) in &planes_set {
2715            for size in sizes {
2716                let scaled = match size {
2717                    Some(s) => transform::downscale_to(plane, s),
2718                    None => plane.clone(),
2719                };
2720                let variants: Vec<(&str, LumaImage)> = vec![
2721                    ("plain", scaled.clone()),
2722                    ("otsu", transform::otsu_threshold(&scaled)),
2723                    ("invert", transform::invert(&scaled)),
2724                    ("stretch", transform::contrast_stretch(&scaled)),
2725                    (
2726                        "stretch+otsu",
2727                        transform::otsu_threshold(&transform::contrast_stretch(&scaled)),
2728                    ),
2729                ];
2730                for (op_name, img) in variants {
2731                    let outcome = engine::decode_all(&img);
2732                    if !outcome.detections.is_empty() {
2733                        let engines: Vec<_> = outcome.detections.iter().map(|d| d.engine).collect();
2734                        println!(
2735                            "HIT plane={plane_name} size={size:?} op={op_name} engines={engines:?}"
2736                        );
2737                    }
2738                }
2739            }
2740        }
2741        println!("probe done");
2742    }
2743
2744    #[test]
2745    #[ignore = "dev diagnostic, not a contract"]
2746    fn probe_artistic_v02_known_good_combos() {
2747        let path = format!(
2748            "{}/../../fixtures/artistic/OK_1069ms_85_8b6a54b3.png",
2749            env!("CARGO_MANIFEST_DIR")
2750        );
2751        let bytes = std::fs::read(path).unwrap();
2752        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
2753        let luma = &planes.luma;
2754
2755        // THE canonical rungs — the probe must never drift from the ladder.
2756        for rung in DEEP_RUNGS {
2757            let img = rung.apply(luma);
2758            let outcome = engine::decode_all(&img);
2759            if !outcome.detections.is_empty() {
2760                let engines: Vec<_> = outcome.detections.iter().map(|d| d.engine).collect();
2761                println!("HIT rung={rung:?} engines={engines:?}");
2762            }
2763        }
2764        println!("v02 probe done");
2765    }
2766
2767    #[test]
2768    #[ignore = "dev diagnostic, not a contract"]
2769    fn probe_rescue_viability_occluded_disk() {
2770        // does rqrr still hand us grid + raw stream where decode fails?
2771        for pct in [20u32, 22, 26, 30] {
2772            let path = format!("/tmp/rescue-h-{pct}.png");
2773            let Ok(bytes) = std::fs::read(&path) else {
2774                continue;
2775            };
2776            let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
2777            let luma = &planes.luma;
2778            let width = luma.width() as usize;
2779            let data = luma.data();
2780            let mut prepared = rqrr::PreparedImage::prepare_from_greyscale(
2781                width,
2782                luma.height() as usize,
2783                |x, y| data[y * width + x],
2784            );
2785            for grid in prepared.detect_grids() {
2786                let mut raw = Vec::new();
2787                let decode_ok = grid.decode_to(&mut raw).is_ok();
2788                let raw_data = grid.get_raw_data();
2789                println!(
2790                    "disk {pct}%: decode_to={} get_raw_data={} meta={:?}",
2791                    decode_ok,
2792                    raw_data.is_ok(),
2793                    raw_data
2794                        .as_ref()
2795                        .ok()
2796                        .map(|(m, _)| (m.version.0, m.ecc_level, m.mask)),
2797                );
2798            }
2799        }
2800        println!("probe done");
2801    }
2802
2803    #[test]
2804    #[ignore = "dev diagnostic, not a contract"]
2805    fn probe_monkey_morph_variants() {
2806        let path = format!(
2807            "{}/../../fixtures/artistic/blob-style-monkey-logo.webp",
2808            env!("CARGO_MANIFEST_DIR")
2809        );
2810        let bytes = std::fs::read(path).unwrap();
2811        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
2812        let luma = &planes.luma;
2813        println!("luma {}x{}", luma.width(), luma.height());
2814        for k in [5u32, 7, 9, 11, 13] {
2815            for target in [256u32, 290, 320, 360, 420, 512] {
2816                let closed = transform::min_filter(luma, k);
2817                let img = transform::downscale_to(&closed, target);
2818                let outcome = engine::decode_all(&img);
2819                if !outcome.detections.is_empty() {
2820                    println!(
2821                        "HIT k={k} target={target} engines={:?}",
2822                        outcome
2823                            .detections
2824                            .iter()
2825                            .map(|d| d.engine)
2826                            .collect::<Vec<_>>()
2827                    );
2828                }
2829            }
2830        }
2831        println!("probe done");
2832    }
2833}
2834
2835#[cfg(test)]
2836mod kanji_merge_tests {
2837    #![allow(clippy::unwrap_used, clippy::expect_used)]
2838
2839    use super::*;
2840    use crate::input::{ImageInput, Limits};
2841    use crate::transform::normalize;
2842
2843    /// Kanji-MODE symbols: both engines report the original Shift-JIS
2844    /// bytes (rxing's re-encoded text is never the payload). Same symbol
2845    /// MUST merge into one detection, raw = the original SJIS bytes.
2846    #[test]
2847    fn kanji_mode_merges_across_engines_with_sjis_raw() {
2848        // こんにちは in Shift-JIS — the qrcode crate's optimizer emits
2849        // kanji-mode segments for SJIS pairs.
2850        let sjis: &[u8] = &[0x82, 0xB1, 0x82, 0xF1, 0x82, 0xC9, 0x82, 0xBF, 0x82, 0xCD];
2851        let code = qrcode::QrCode::with_error_correction_level(sjis, qrcode::EcLevel::Q).unwrap();
2852        let img = code
2853            .render::<image::Luma<u8>>()
2854            .module_dimensions(6, 6)
2855            .build();
2856        let mut png = Vec::new();
2857        image::DynamicImage::ImageLuma8(img)
2858            .write_to(&mut std::io::Cursor::new(&mut png), image::ImageFormat::Png)
2859            .unwrap();
2860
2861        let planes = normalize(&ImageInput::encoded(&png), &Limits::default()).unwrap();
2862        let outcome = run(&planes, &ScanConfig::full(), &CancelToken::new(), None).unwrap();
2863
2864        assert_eq!(
2865            outcome.merged.len(),
2866            1,
2867            "one symbol must merge to ONE detection — got {:?}",
2868            outcome
2869                .merged
2870                .iter()
2871                .map(|m| (&m.engines, &m.raw))
2872                .collect::<Vec<_>>()
2873        );
2874        let d = &outcome.merged[0];
2875        assert_eq!(d.raw, sjis, "raw must be the ORIGINAL bytes");
2876        assert_eq!(d.text, "こんにちは");
2877        assert_eq!(d.charset, crate::report::Charset::ShiftJis);
2878        assert_eq!(d.engines, vec![EngineKind::Rxing, EngineKind::Rqrr]);
2879    }
2880}
2881
2882#[cfg(test)]
2883mod content_readings {
2884    //! The ladder's account of each detection's content, on symbols encoded
2885    //! from explicit segment streams: one reading per detection, its label
2886    //! on the wire.
2887    #![allow(clippy::unwrap_used, clippy::expect_used)]
2888
2889    use super::*;
2890    use crate::input::{ImageInput, Limits};
2891    use crate::report::Charset;
2892    use crate::transform::normalize;
2893
2894    /// Walk the camera-frame stages over a v3-M symbol built from `push`.
2895    fn walk(
2896        push: impl FnOnce(&mut qrcode::bits::Bits) -> qrcode::types::QrResult<()>,
2897    ) -> LadderOutcome {
2898        let mut bits = qrcode::bits::Bits::new(qrcode::Version::Normal(3));
2899        push(&mut bits).unwrap();
2900        bits.push_terminator(qrcode::EcLevel::M).unwrap();
2901        let code = qrcode::QrCode::with_bits(bits, qrcode::EcLevel::M).unwrap();
2902        let img = code
2903            .render::<image::Luma<u8>>()
2904            .module_dimensions(6, 6)
2905            .build();
2906        let planes = normalize(
2907            &ImageInput::luma8(img.as_raw(), img.width(), img.height()),
2908            &Limits::default(),
2909        )
2910        .unwrap();
2911        let mut config = ScanConfig::frame();
2912        config.budget_ms = None;
2913        run(&planes, &config, &CancelToken::new(), None).unwrap()
2914    }
2915
2916    /// The one detection of a single-symbol walk, with its content key.
2917    fn single(outcome: &LadderOutcome) -> (&MergedDetection, &ContentKey) {
2918        assert_eq!(outcome.merged.len(), 1, "{:?}", outcome.merged);
2919        assert_eq!(outcome.contents.len(), 1);
2920        let (key, reading) = &outcome.contents[0];
2921        let d = &outcome.merged[0];
2922        // the published triple is the one reading of the reconciled content
2923        assert_eq!(
2924            (&key.raw, &reading.text, reading.charset),
2925            (&d.raw, &d.text, d.charset)
2926        );
2927        (d, key)
2928    }
2929
2930    fn located(marks: &[(u32, usize)]) -> EciEvidence {
2931        EciEvidence::Located(
2932            marks
2933                .iter()
2934                .map(|&(value, start)| content::EciMark { value, start })
2935                .collect(),
2936        )
2937    }
2938
2939    #[test]
2940    fn declared_eci_text_is_labelled_eci_not_legacy() {
2941        let outcome = walk(|b| {
2942            b.push_eci_designator(4)?;
2943            b.push_byte_data(&[0xA1])
2944        });
2945        let (d, key) = single(&outcome);
2946        assert_eq!(
2947            (d.raw.as_slice(), d.text.as_str()),
2948            (&[0xA1][..], "\u{104}")
2949        );
2950        assert_eq!(
2951            key.eci,
2952            located(&[(4, 0)]),
2953            "rqrr's re-derivation located it"
2954        );
2955        assert_eq!(d.charset, Charset::Eci, "no decoder label reads ISO 8859-2");
2956    }
2957
2958    #[test]
2959    fn eci3_c1_bytes_are_eci_without_a_windows_1252_claim() {
2960        let outcome = walk(|b| {
2961            b.push_eci_designator(3)?;
2962            b.push_byte_data(&[0x35, 0x80])
2963        });
2964        let (d, _) = single(&outcome);
2965        assert_eq!(d.text, "5\u{80}");
2966        assert_eq!(d.charset, Charset::Eci, "latin1 would decode 0x80 as '€'");
2967    }
2968
2969    #[test]
2970    fn declarations_without_a_reading_are_marked_unknown() {
2971        let cases: [(&str, u32, &[u8], &str); 3] = [
2972            ("unsupported", 999, &[0xA1], "\u{FFFD}"),
2973            ("undecodable", 26, &[0xA1], "\u{FFFD}"),
2974            (
2975                "binary",
2976                899,
2977                &[0x00, 0xFF, 0x80, 0x7F],
2978                "\u{FFFD}\u{FFFD}\u{FFFD}\u{FFFD}",
2979            ),
2980        ];
2981        for (name, value, bytes, text) in cases {
2982            let outcome = walk(|b| {
2983                b.push_eci_designator(value)?;
2984                b.push_byte_data(bytes)
2985            });
2986            let (d, _) = single(&outcome);
2987            assert_eq!(d.raw, bytes, "{name}");
2988            assert_eq!(d.text, text, "{name}: marked, never transcribed");
2989            assert_eq!(d.charset, Charset::Unknown, "{name}");
2990        }
2991    }
2992
2993    #[test]
2994    fn kanji_after_eci26_is_marked_not_shift_jis() {
2995        let outcome = walk(|b| {
2996            b.push_eci_designator(26)?;
2997            b.push_byte_data("é".as_bytes())?;
2998            b.push_kanji_data(&[0x82, 0xB1, 0x82, 0xF1])
2999        });
3000        let (d, _) = single(&outcome);
3001        assert_eq!(d.raw, vec![0xC3, 0xA9, 0x82, 0xB1, 0x82, 0xF1]);
3002        // WHATWG UTF-8: one U+FFFD per maximal ill-formed subpart
3003        assert_eq!(d.text, String::from_utf8_lossy(&d.raw));
3004        assert!(d.text.starts_with('é') && d.text.contains('\u{FFFD}'));
3005        assert_eq!(d.charset, Charset::Unknown);
3006    }
3007
3008    #[test]
3009    fn kanji_before_the_first_designator_is_iso_8859_1() {
3010        // the Kanji pair travels as Shift_JIS bytes, but a symbol with a
3011        // designator reads every byte before it as ISO/IEC 8859-1
3012        let outcome = walk(|b| {
3013            b.push_kanji_data(&[0x82, 0xB1])?;
3014            b.push_eci_designator(26)?;
3015            b.push_byte_data(b"a")
3016        });
3017        let (d, key) = single(&outcome);
3018        assert_eq!(d.raw, vec![0x82, 0xB1, b'a']);
3019        assert_eq!(key.eci, located(&[(26, 2)]));
3020        assert_eq!(d.text, "\u{82}\u{B1}a");
3021        assert_eq!(d.charset, Charset::Eci, "utf8 cannot reproduce it");
3022    }
3023
3024    #[test]
3025    fn unmarked_payloads_keep_the_legacy_resolver() {
3026        let outcome = walk(|b| b.push_byte_data(&[0x35, 0x80]));
3027        let (d, key) = single(&outcome);
3028        assert_eq!(d.text, "5€");
3029        assert_eq!(key.eci, EciEvidence::NoEci, "both engines observed none");
3030        assert_eq!(d.charset, Charset::Latin1);
3031        assert_eq!(d.engines, vec![EngineKind::Rxing, EngineKind::Rqrr]);
3032    }
3033
3034    #[test]
3035    fn kanji_segments_choose_shift_jis() {
3036        // the parse observes the Kanji segment: Shift_JIS over all of raw
3037        let outcome = walk(|b| {
3038            b.push_byte_data(b"QR:")?;
3039            b.push_kanji_data(&[0x93, 0xFA, 0x96, 0x7B])
3040        });
3041        let (d, key) = single(&outcome);
3042        assert_eq!(key.eci, EciEvidence::NoEci);
3043        assert_eq!((d.text.as_str(), d.charset), ("QR:日本", Charset::ShiftJis));
3044    }
3045}
3046
3047#[cfg(test)]
3048mod ladder_mutant_kills {
3049    //! Surgical traps for the weekly mutation survivors on the decode ladder
3050    //! (the product's critical path). Each test names the mutant(s) it kills
3051    //! by `line:col` where one exists. The candidate, re-read, rescue and
3052    //! book-keeping logic is exercised directly (private methods, reachable
3053    //! from this in-crate child module); the stage-gating booleans in `run`
3054    //! are driven through synthetic in-memory planes with `budget_ms: None`
3055    //! so the walk is deterministic — never wall-clock-dependent.
3056    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::float_cmp)]
3057
3058    use super::*;
3059    use crate::engine::content::EciMark;
3060    use crate::input::{ImageInput, Limits};
3061    use crate::report::EcLevel;
3062    use crate::transform::normalize;
3063
3064    fn fresh_run(cancel: &CancelToken, orig: (u32, u32)) -> Run<'_> {
3065        Run::new(cancel, None, orig, Seed::default())
3066    }
3067
3068    #[test]
3069    #[cfg(feature = "engine-rxing")]
3070    fn matrix_exclusion_preserves_the_pixels_outside_a_rotated_quad() {
3071        let original = LumaImage::new(vec![17; 25], 5, 5);
3072        let diamond = [
3073            Point { x: 2.5, y: 0.5 },
3074            Point { x: 4.5, y: 2.5 },
3075            Point { x: 2.5, y: 4.5 },
3076            Point { x: 0.5, y: 2.5 },
3077        ];
3078        let expected = [
3079            17, 17, 255, 17, 17, 17, 255, 255, 255, 17, 255, 255, 255, 255, 255, 17, 255, 255, 255,
3080            17, 17, 17, 255, 17, 17,
3081        ];
3082        let mut reversed = diamond;
3083        reversed.reverse();
3084        for region in [diamond, reversed] {
3085            assert_eq!(
3086                exclude_matrix_regions(&original, &[region]).data(),
3087                expected
3088            );
3089        }
3090        assert_eq!(original.data(), [17; 25]);
3091    }
3092
3093    #[test]
3094    #[cfg(feature = "engine-rxing")]
3095    fn invalid_matrix_regions_never_exclude_pixels() {
3096        let original = LumaImage::new(vec![17; 25], 5, 5);
3097        for region in [
3098            [Point { x: 1.0, y: 1.0 }; 4],
3099            [
3100                Point { x: 0.0, y: 0.0 },
3101                Point { x: 4.0, y: 4.0 },
3102                Point { x: 4.0, y: 0.0 },
3103                Point { x: 0.0, y: 4.0 },
3104            ],
3105            [Point {
3106                x: f32::NAN,
3107                y: 1.0,
3108            }; 4],
3109        ] {
3110            assert_eq!(exclude_matrix_regions(&original, &[region]), original);
3111        }
3112    }
3113
3114    fn qr_png(content: &str, module: u32) -> Vec<u8> {
3115        let code =
3116            qrcode::QrCode::with_error_correction_level(content, qrcode::EcLevel::Q).unwrap();
3117        let img = code
3118            .render::<image::Luma<u8>>()
3119            .module_dimensions(module, module)
3120            .build();
3121        let mut buf = Vec::new();
3122        image::DynamicImage::ImageLuma8(img)
3123            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
3124            .unwrap();
3125        buf
3126    }
3127
3128    fn stage_names(outcome: &LadderOutcome) -> Vec<&str> {
3129        outcome
3130            .trace
3131            .stages
3132            .iter()
3133            .map(|s| s.stage.as_str())
3134            .collect()
3135    }
3136
3137    fn eci_mark(value: u32, start: usize) -> EciEvidence {
3138        EciEvidence::Located(vec![EciMark { value, start }])
3139    }
3140
3141    /// The engine reads of one decode pass as reads of `run`'s attempt
3142    /// `attempt` (full-resolution, upright).
3143    fn reads_of(
3144        run: &Run<'_>,
3145        detections: Vec<RawDetection>,
3146        attempt: u32,
3147        dims: (u32, u32),
3148    ) -> Vec<(Read, Option<LocateHint>)> {
3149        detections
3150            .into_iter()
3151            .enumerate()
3152            .map(|(i, hit)| {
3153                let rank = Rank {
3154                    attempt,
3155                    source: 0,
3156                    index: u32::try_from(i).unwrap(),
3157                };
3158                run.read_of(hit, rank, dims, false)
3159            })
3160            .collect()
3161    }
3162
3163    // ---- Run::read_of ----
3164
3165    #[test]
3166    fn photometry_travels_with_the_corners_only() {
3167        // `&&` -> `||` on the photometry: an upright attempt with corners is
3168        // not inverted; an inverting one is; a read without corners carries
3169        // no photometry at all
3170        let cancel = CancelToken::new();
3171        let run = fresh_run(&cancel, (100, 100));
3172        let mut hit = RawDetection::qr(b"x", EciEvidence::NoEci, Fnc1::None, EngineKind::Rqrr);
3173        hit.corners = Some([Point { x: 2.0, y: 3.0 }; 4]);
3174        let rank = Rank::default();
3175        let (upright, _) = run.read_of(hit.clone(), rank, (100, 100), false);
3176        let (inverted, _) = run.read_of(hit.clone(), rank, (100, 100), true);
3177        assert_eq!(upright.geometry.corners.map(|(_, i)| i), Some(false));
3178        assert_eq!(inverted.geometry.corners.map(|(_, i)| i), Some(true));
3179        hit.corners = None;
3180        let (bare, _) = run.read_of(hit, rank, (100, 100), true);
3181        assert!(bare.geometry.corners.is_none());
3182    }
3183
3184    #[test]
3185    fn a_read_is_placed_in_original_space() {
3186        // orig 200x100 over an attempt of 50x50: fx = 4, fy = 2
3187        let cancel = CancelToken::new();
3188        let run = fresh_run(&cancel, (200, 100));
3189        let mut hit = RawDetection::qr(b"x", EciEvidence::NoEci, Fnc1::None, EngineKind::Rxing);
3190        hit.location = Some([Point { x: 10.0, y: 10.0 }; 4]);
3191        hit.ec = Some(EcLevel::Q);
3192        let (read, _) = run.read_of(hit, Rank::default(), (50, 50), false);
3193        let corner = read.location.unwrap()[0];
3194        assert!((corner.x - 40.0).abs() < 1e-3 && (corner.y - 20.0).abs() < 1e-3);
3195        assert_eq!(read.places.len(), 1);
3196        assert_eq!(read.geometry.ec, Some(EcLevel::Q), "the port's EC level");
3197    }
3198
3199    // ---- Run::rederive (candidates) ----
3200
3201    /// The ECI 26 + FNC1-first GTIN symbol (rqrr's grid is a candidate).
3202    fn eci26_gs1() -> LumaImage {
3203        crate::rescue::test_symbols::from_segments(
3204            qrcode::Version::Normal(3),
3205            qrcode::EcLevel::M,
3206            |b| {
3207                b.push_eci_designator(26)?;
3208                b.push_fnc1_first_position()?;
3209                b.push_numeric_data(b"0109506000134352")
3210            },
3211        )
3212    }
3213
3214    #[test]
3215    fn a_rederived_candidate_locates_a_signalled_read_and_nothing_else() {
3216        // ECI 26 + FNC1 first: rqrr cannot decode FNC1 (its grid is a
3217        // candidate), rxing's port signals the ECI
3218        let luma = eci26_gs1();
3219        let dims = (luma.width(), luma.height());
3220        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3221        assert_eq!(outcome.rescue.len(), 1, "rqrr's grid");
3222        let (parses, refusals) = Run::rederive(&outcome.rescue, 0, dims, 0);
3223        assert!(refusals.is_empty());
3224        let [parse] = &parses[..] else {
3225            panic!("one candidate parse: {parses:?}");
3226        };
3227        assert_eq!(parse.key.eci, eci_mark(26, 0));
3228        assert_eq!(parse.key.fnc1, Fnc1::First);
3229        assert!(
3230            parse.parsed && parse.engines.is_empty(),
3231            "a parse, no engine"
3232        );
3233        // alone it publishes nothing; with the port's read it locates it
3234        let cancel = CancelToken::new();
3235        let mut run = fresh_run(&cancel, dims);
3236        run.store.collect(parse.clone());
3237        assert!(run.store.reconcile().is_empty());
3238        for (read, _) in reads_of(&run, outcome.detections, 0, dims) {
3239            run.store.collect(read);
3240        }
3241        let found = run.store.reconcile();
3242        assert_eq!(found.len(), 1);
3243        assert_eq!(found[0].key.eci, eci_mark(26, 0), "located over signalled");
3244        assert_eq!(found[0].engines, vec![EngineKind::Rxing]);
3245        assert!(found[0].geometry.corners.is_some() && found[0].geometry.stream.is_some());
3246    }
3247
3248    #[test]
3249    fn at_most_four_candidates_are_re_derived_per_pass() {
3250        // five candidates, only the fifth would parse: nothing is parsed
3251        let luma = eci26_gs1();
3252        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3253        let dud = crate::rescue::RescueCandidate {
3254            stream: engine::MaskedStream {
3255                bits: Vec::new(),
3256                bit_len: 0,
3257            },
3258            corners: [Point { x: 0.0, y: 0.0 }; 4],
3259            pixel: crate::engine::occurrence::UNIT_PIXEL,
3260            version: 0,
3261            ec: EcLevel::M,
3262            mask: 0,
3263            inverted: false,
3264            transposed: false,
3265            rederived: None,
3266        };
3267        let mut candidates = vec![dud; MAX_RESCUE_CANDIDATES];
3268        candidates.push(outcome.rescue[0].clone());
3269        let dims = (luma.width(), luma.height());
3270        let (parses, refusals) = Run::rederive(&candidates, 0, dims, 0);
3271        assert!(parses.is_empty() && refusals.is_empty());
3272        // fourth, it does
3273        candidates.remove(0);
3274        assert_eq!(Run::rederive(&candidates, 0, dims, 0).0.len(), 1);
3275    }
3276
3277    #[test]
3278    fn the_end_of_walk_pass_locates_and_refuses_across_attempts() {
3279        // rqrr's grid collected in one attempt, rxing's read in another:
3280        // only the end-of-walk pass brings them together
3281        let cancel = CancelToken::new();
3282        let luma = eci26_gs1();
3283        let dims = (luma.width(), luma.height());
3284        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3285        let mut run = fresh_run(&cancel, dims);
3286        run.collect_rescue(outcome.rescue, dims, false);
3287        for (read, _) in reads_of(&run, outcome.detections, 1, dims) {
3288            run.store.collect(read);
3289        }
3290        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
3291        assert_eq!(walked.merged.len(), 1);
3292        let d = &walked.merged[0];
3293        assert_eq!(d.text, "0109506000134352");
3294        assert_eq!(d.engines, vec![EngineKind::Rxing]);
3295        assert!(d.fnc1 && d.corners.is_some());
3296        assert_eq!(walked.contents[0].0.eci, eci_mark(26, 0));
3297        // FNC1 second then first: the collected grid proves the stream
3298        // malformed and withholds the port's GS1 read where the grid is
3299        let data = crate::rescue::test_symbols::stream(
3300            "1001 00100101 0101 0100 00000011 01100001 01100010 01100011 0000",
3301        );
3302        let luma = crate::rescue::test_symbols::from_codewords(
3303            qrcode::Version::Normal(1),
3304            qrcode::EcLevel::M,
3305            &data,
3306        );
3307        let dims = (luma.width(), luma.height());
3308        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3309        let mut run = fresh_run(&cancel, dims);
3310        run.collect_rescue(outcome.rescue, dims, false);
3311        for (read, _) in reads_of(&run, outcome.detections, 1, dims) {
3312            run.store.collect(read);
3313        }
3314        assert_eq!(run.store.reconcile().len(), 1, "the port's GS1 read");
3315        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
3316        assert!(walked.merged.is_empty(), "{:?}", walked.merged);
3317        // and a cancel raised by then is honoured first
3318        let cancelled = CancelToken::new();
3319        cancelled.cancel();
3320        let err = fresh_run(&cancelled, dims)
3321            .finish_blank(Vec::new(), Instant::now())
3322            .unwrap_err();
3323        assert_eq!(err.code(), "QRS-005");
3324    }
3325
3326    #[test]
3327    fn a_cancel_is_honoured_before_the_end_of_walk_pass() {
3328        // the end-of-walk re-derivation runs after the last attempt's
3329        // cancel check: a cancel raised by then is honoured first (every
3330        // stage off here, so no attempt checks it at all)
3331        let data = vec![255u8; 64 * 64];
3332        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
3333        let mut config = ScanConfig::full();
3334        (config.pyramid, config.direct, config.enhance, config.deep) = (false, false, false, false);
3335        let cancel = CancelToken::new();
3336        cancel.cancel();
3337        let err = run(&planes, &config, &cancel, None).unwrap_err();
3338        assert_eq!(err.code(), "QRS-005");
3339    }
3340
3341    // ---- Run::reread ----
3342
3343    #[test]
3344    fn the_re_read_locates_a_port_read_no_parse_of_the_attempt_carries() {
3345        // ECI 4 [A1]: rxing's port read signals a designator; the re-read at
3346        // its corners locates it — unless rqrr's parsed read of the same
3347        // attempt carries the content already
3348        let luma = crate::rescue::test_symbols::from_segments(
3349            qrcode::Version::Normal(3),
3350            qrcode::EcLevel::M,
3351            |b| {
3352                b.push_eci_designator(4)?;
3353                b.push_byte_data(&[0xA1])
3354            },
3355        );
3356        let dims = (luma.width(), luma.height());
3357        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3358        let cancel = CancelToken::new();
3359        let port: Vec<RawDetection> = outcome
3360            .detections
3361            .iter()
3362            .filter(|d| d.engine == EngineKind::Rxing)
3363            .cloned()
3364            .collect();
3365        let mut run = fresh_run(&cancel, dims);
3366        let mut reads = reads_of(&run, port.clone(), 0, dims);
3367        let mut refusals = Vec::new();
3368        run.reread(&luma, &mut reads, &mut refusals);
3369        assert_eq!(run.rereads, 1);
3370        assert!(refusals.is_empty());
3371        let (read, _) = &reads[0];
3372        assert_eq!(read.key.eci, eci_mark(4, 0));
3373        assert!(read.parsed && read.engines == vec![(EngineKind::Rxing, read.rank)]);
3374        assert!(
3375            read.geometry.corners.is_none(),
3376            "its geometry stays internal"
3377        );
3378        // carried by rqrr's parse of the same attempt: no re-read spent
3379        let mut run = fresh_run(&cancel, dims);
3380        let mut reads = reads_of(&run, outcome.detections, 0, dims);
3381        run.reread(&luma, &mut reads, &mut refusals);
3382        assert_eq!(run.rereads, 0);
3383        // the scan's re-reads are bounded
3384        let mut run = fresh_run(&cancel, dims);
3385        run.rereads = MAX_REREADS;
3386        let mut reads = reads_of(&run, port, 0, dims);
3387        run.reread(&luma, &mut reads, &mut refusals);
3388        assert_eq!(reads[0].0.key.eci, EciEvidence::Signalled, "none left");
3389        assert_eq!(run.rereads, MAX_REREADS);
3390    }
3391
3392    /// v1-M: ECI 1000000 (above the register) then byte "abc" — rqrr
3393    /// decodes "abc", rxing's port signals a designator and reads "abc",
3394    /// the scanner's parser refuses the stream.
3395    fn eci_above_the_register_abc() -> LumaImage {
3396        let data = crate::rescue::test_symbols::stream(
3397            "0111 11001111 01000010 01000000 0100 00000011 01100001 01100010 01100011 0000",
3398        );
3399        crate::rescue::test_symbols::from_codewords(
3400            qrcode::Version::Normal(1),
3401            qrcode::EcLevel::M,
3402            &data,
3403        )
3404    }
3405
3406    #[test]
3407    fn a_read_a_recorded_refusal_withholds_is_not_re_read() {
3408        // the port read of a refused symbol is withheld anyway — re-reading
3409        // it in every attempt would spend the scan's re-reads on one
3410        // malformed symbol. rqrr's refused decode is recorded (the port's
3411        // reading and rqrr's bytes, at rqrr's bounds); a later attempt's
3412        // port read lies inside: no re-read is spent on it
3413        let luma = eci_above_the_register_abc();
3414        let dims = (luma.width(), luma.height());
3415        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3416        let [refusal] = &outcome.refused[..] else {
3417            panic!("rqrr's refused decode: {:?}", outcome.refused);
3418        };
3419        let port: Vec<RawDetection> = outcome
3420            .detections
3421            .into_iter()
3422            .filter(|d| d.engine == EngineKind::Rxing)
3423            .collect();
3424        assert!(
3425            !port.is_empty() && port.iter().all(|d| d.locate.is_some()),
3426            "the port's read is a re-read candidate: {port:?}"
3427        );
3428        let cancel = CancelToken::new();
3429        let mut run = fresh_run(&cancel, dims);
3430        run.store.refuse(refusal.clone(), 0);
3431        let mut reads = reads_of(&run, port.clone(), 1, dims);
3432        let mut refusals = Vec::new();
3433        run.reread(&luma, &mut reads, &mut refusals);
3434        assert_eq!(run.rereads, 0, "withheld anyway");
3435        assert!(refusals.is_empty() && reads.len() == port.len());
3436        // without that record, the re-read runs — and refuses it
3437        let mut run = fresh_run(&cancel, dims);
3438        let mut reads = reads_of(&run, port, 1, dims);
3439        run.reread(&luma, &mut reads, &mut refusals);
3440        assert_eq!(run.rereads, 1);
3441        assert_eq!(refusals.len(), 1, "{refusals:?}");
3442    }
3443
3444    #[test]
3445    fn a_low_version_port_read_is_re_read_once_for_its_margin() {
3446        // v2-L, no ECI: rxing's port read has nothing to locate, but its
3447        // word's margin is unknown. One re-read at its corners measures it,
3448        // ⌊(10 − 2)/2⌋ − 0 = 4, and changes nothing else of the read
3449        let luma = crate::rescue::test_symbols::from_segments(
3450            qrcode::Version::Normal(2),
3451            qrcode::EcLevel::L,
3452            |b| b.push_byte_data(b"https://qrc-ai.com/v2l"),
3453        );
3454        let dims = (luma.width(), luma.height());
3455        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3456        let port: Vec<RawDetection> = outcome
3457            .detections
3458            .iter()
3459            .filter(|d| d.engine == EngineKind::Rxing)
3460            .cloned()
3461            .collect();
3462        let cancel = CancelToken::new();
3463        let mut run = fresh_run(&cancel, dims);
3464        let mut reads = reads_of(&run, port.clone(), 0, dims);
3465        let before = reads[0].0.clone();
3466        let mut refusals = Vec::new();
3467        run.reread(&luma, &mut reads, &mut refusals);
3468        assert_eq!(run.rereads, 1);
3469        assert!(refusals.is_empty());
3470        let (read, _) = &reads[0];
3471        assert_eq!(read.margin, Margin::Known(4));
3472        assert_eq!(
3473            (&read.key, read.parsed, &read.segments),
3474            (&before.key, before.parsed, &before.segments)
3475        );
3476        // once per content: the next attempt's read of it is not re-read
3477        let mut again = reads_of(&run, port.clone(), 1, dims);
3478        run.reread(&luma, &mut again, &mut refusals);
3479        assert_eq!((run.rereads, again[0].0.margin), (1, Margin::Unknown));
3480        // rqrr's read of the same attempt measured its own word: none spent
3481        let mut run = fresh_run(&cancel, dims);
3482        let mut reads = reads_of(&run, outcome.detections, 0, dims);
3483        run.reread(&luma, &mut reads, &mut refusals);
3484        assert_eq!(run.rereads, 0);
3485        // nor when the walk holds a read of the content with a known margin
3486        let mut run = fresh_run(&cancel, dims);
3487        let mut measured = before;
3488        measured.margin = Margin::Known(0);
3489        run.store.collect(measured);
3490        let mut reads = reads_of(&run, port, 1, dims);
3491        run.reread(&luma, &mut reads, &mut refusals);
3492        assert_eq!(run.rereads, 0);
3493    }
3494
3495    #[test]
3496    fn a_symbol_refused_in_every_attempt_spends_no_re_read() {
3497        // the whole walk over that symbol: rqrr refuses it wherever it
3498        // decodes it and the port reads it in every attempt — the refusal is
3499        // recorded before the attempt's re-reads, so none is spent on it
3500        let luma = eci_above_the_register_abc();
3501        let planes = normalize(
3502            &ImageInput::luma8(luma.data(), luma.width(), luma.height()),
3503            &Limits::default(),
3504        )
3505        .unwrap();
3506        let mut config = ScanConfig::full();
3507        config.budget_ms = None;
3508        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
3509        assert!(outcome.merged.is_empty(), "{:?}", outcome.merged);
3510        assert_eq!(outcome.rereads, 0, "{:?}", outcome.trace.stages);
3511        // refused at every attempt scale, one record
3512        assert_eq!(outcome.store.records(), 1, "{:?}", outcome.trace.stages);
3513    }
3514
3515    /// A 100 px square at `x`.
3516    fn square_at(x: f32) -> [Point; 4] {
3517        [
3518            Point { x, y: 0.0 },
3519            Point {
3520                x: x + 100.0,
3521                y: 0.0,
3522            },
3523            Point {
3524                x: x + 100.0,
3525                y: 100.0,
3526            },
3527            Point { x, y: 100.0 },
3528        ]
3529    }
3530
3531    #[test]
3532    fn only_a_parse_where_the_read_lies_carries_it() {
3533        // a parsed read of the attempt carries a port read only where it
3534        // contains it. ECI 4 [A1]: a parse of the same content made
3535        // elsewhere (another symbol) leaves the port read to its own
3536        // re-read, which locates it; a parse where the read lies carries it
3537        let luma = crate::rescue::test_symbols::from_segments(
3538            qrcode::Version::Normal(3),
3539            qrcode::EcLevel::M,
3540            |b| {
3541                b.push_eci_designator(4)?;
3542                b.push_byte_data(&[0xA1])
3543            },
3544        );
3545        let dims = (luma.width(), luma.height());
3546        let port: Vec<RawDetection> = engine::decode_filtered(&luma, engine::FormatFilter::All)
3547            .detections
3548            .into_iter()
3549            .filter(|d| d.engine == EngineKind::Rxing)
3550            .collect();
3551        let parse_at = |place: Option<[Point; 4]>| {
3552            let key = ContentKey {
3553                raw: vec![0xA1],
3554                eci: eci_mark(4, 0),
3555                fnc1: Fnc1::None,
3556            };
3557            let rank = Rank {
3558                attempt: 0,
3559                source: source::RQRR,
3560                index: 0,
3561            };
3562            let mut parse =
3563                Read::new(Symbology::QrCode, key, Some(EngineKind::Rqrr), rank).at(place);
3564            parse.parsed = true;
3565            // a parse measures its own word: v3-M, no error, ⌊26/2⌋ = 13
3566            parse.margin = Margin::Known(13);
3567            (parse, None)
3568        };
3569        let cancel = CancelToken::new();
3570        let mut refusals = Vec::new();
3571        let mut run = fresh_run(&cancel, dims);
3572        let mut reads = reads_of(&run, port.clone(), 0, dims);
3573        reads.push(parse_at(Some(square_at(5_000.0))));
3574        run.reread(&luma, &mut reads, &mut refusals);
3575        assert_eq!(run.rereads, 1, "a parse elsewhere carries nothing");
3576        assert_eq!(reads[0].0.key.eci, eci_mark(4, 0), "located by its re-read");
3577        let mut run = fresh_run(&cancel, dims);
3578        let mut reads = reads_of(&run, port, 0, dims);
3579        let here = reads[0].0.location;
3580        reads.push(parse_at(here));
3581        run.reread(&luma, &mut reads, &mut refusals);
3582        assert_eq!(run.rereads, 0, "the parse where it lies carries it");
3583        assert!(refusals.is_empty());
3584    }
3585
3586    /// v1-M: FNC1 in first position, then the GTIN element string
3587    /// 0109506000134352 in numeric mode, its data codewords at `corrupt`
3588    /// inverted after the RS parity was computed.
3589    fn fnc1_gtin_v1m(corrupt: &[usize]) -> LumaImage {
3590        let data = crate::rescue::test_symbols::stream(
3591            "0101 0001 0000010000 0000001010 1110110110 1001011000 0000001101 0110110011 0010 0000",
3592        );
3593        crate::rescue::test_symbols::from_corrupted_codewords(
3594            qrcode::Version::Normal(1),
3595            qrcode::EcLevel::M,
3596            &data,
3597            corrupt,
3598        )
3599    }
3600
3601    #[test]
3602    fn a_port_read_its_candidate_carries_is_still_re_read_for_its_margin() {
3603        // rqrr cannot decode FNC1: its grid is re-derived (a candidate parse)
3604        // that carries the port read's declarations and measures its own
3605        // word. Five corrected errors at v1-M leave that word one error past
3606        // the reserve (⌊(10 − 2)/2⌋ − 5 = −1): no read of the content keeps a
3607        // margin of zero or more, so the port read is still re-read at its
3608        // corners, for its margin only, once. Four errors leave the candidate
3609        // a margin of zero: no re-read is spent.
3610        for (corrupt, margin, rereads) in [
3611            (&[6, 8, 10, 12, 14][..], -1, 1),
3612            (&[6, 8, 10, 12][..], 0, 0),
3613        ] {
3614            let luma = fnc1_gtin_v1m(corrupt);
3615            let dims = (luma.width(), luma.height());
3616            let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3617            let (parses, refusals) = Run::rederive(&outcome.rescue, 0, dims, 0);
3618            assert!(refusals.is_empty(), "{refusals:?}");
3619            let [parse] = &parses[..] else {
3620                panic!("one candidate parse: {parses:?}");
3621            };
3622            assert_eq!(parse.margin, Margin::Known(margin), "{corrupt:?}");
3623            let cancel = CancelToken::new();
3624            let mut run = fresh_run(&cancel, dims);
3625            let mut reads = reads_of(&run, outcome.detections, 0, dims);
3626            let [(port, Some(hint))] = &reads[..] else {
3627                panic!("the port's read alone: {reads:?}");
3628            };
3629            assert!(
3630                hint.declarations && port.key.fnc1 == Fnc1::First,
3631                "{hint:?}"
3632            );
3633            let before = port.clone();
3634            reads.push((parse.clone(), None));
3635            let mut refused = Vec::new();
3636            run.reread(&luma, &mut reads, &mut refused);
3637            assert!(refused.is_empty(), "{refused:?}");
3638            assert_eq!(run.rereads, rereads, "{corrupt:?}");
3639            let (port, _) = &reads[0];
3640            let measured = if rereads == 1 {
3641                Margin::Known(-1)
3642            } else {
3643                Margin::Unknown
3644            };
3645            assert_eq!(port.margin, measured, "{corrupt:?}");
3646            assert_eq!(
3647                (&port.key, port.parsed, &port.segments),
3648                (&before.key, before.parsed, &before.segments),
3649                "a margin re-read changes nothing else"
3650            );
3651        }
3652    }
3653
3654    /// v3-M, ECI 4 then byte A1: rxing's port signals the designator.
3655    fn eci4_a1() -> LumaImage {
3656        crate::rescue::test_symbols::from_segments(
3657            qrcode::Version::Normal(3),
3658            qrcode::EcLevel::M,
3659            |b| {
3660                b.push_eci_designator(4)?;
3661                b.push_byte_data(&[0xA1])
3662            },
3663        )
3664    }
3665
3666    #[test]
3667    fn an_unverified_re_read_spends_one_re_read_and_moves_on() {
3668        // 921:68: the port read's hint two modules off the symbol — nothing
3669        // verifies there: one re-read is spent and the read stays as read
3670        let luma = eci4_a1();
3671        let dims = (luma.width(), luma.height());
3672        let port: Vec<RawDetection> = engine::decode_filtered(&luma, engine::FormatFilter::All)
3673            .detections
3674            .into_iter()
3675            .filter(|d| d.engine == EngineKind::Rxing)
3676            .collect();
3677        let cancel = CancelToken::new();
3678        let mut run = fresh_run(&cancel, dims);
3679        let mut reads = reads_of(&run, port, 0, dims);
3680        let Some((_, Some(hint))) = reads.first_mut() else {
3681            panic!("the port's read is a re-read candidate");
3682        };
3683        for point in &mut hint.points {
3684            point.x += 12.0;
3685            point.y += 12.0;
3686        }
3687        let mut refusals = Vec::new();
3688        run.reread(&luma, &mut reads, &mut refusals);
3689        assert_eq!(run.rereads, 1);
3690        assert!(refusals.is_empty());
3691        assert_eq!(reads[0].0.key.eci, EciEvidence::Signalled);
3692        assert!(!reads[0].0.parsed);
3693    }
3694
3695    #[test]
3696    fn a_located_re_read_is_not_repeated_for_its_negative_margin() {
3697        // 911:23: ECI 4 then A1 at v1-M, five codewords corrected — one past
3698        // the reserve, ⌊(10 − 2)/2⌋ − 5 = −1. The declarations re-read
3699        // locates the designator and measures that word: one re-read, the
3700        // margin measured once
3701        let data = crate::rescue::test_symbols::stream("0111 00000100 0100 00000001 10100001 0000");
3702        let luma = crate::rescue::test_symbols::from_corrupted_codewords(
3703            qrcode::Version::Normal(1),
3704            qrcode::EcLevel::M,
3705            &data,
3706            &[6, 8, 10, 12, 14],
3707        );
3708        let dims = (luma.width(), luma.height());
3709        let port: Vec<RawDetection> = engine::decode_filtered(&luma, engine::FormatFilter::All)
3710            .detections
3711            .into_iter()
3712            .filter(|d| d.engine == EngineKind::Rxing)
3713            .collect();
3714        let cancel = CancelToken::new();
3715        let mut run = fresh_run(&cancel, dims);
3716        let mut reads = reads_of(&run, port, 0, dims);
3717        assert!(
3718            matches!(&reads[..], [(_, Some(hint))] if hint.declarations),
3719            "{reads:?}"
3720        );
3721        let mut refusals = Vec::new();
3722        run.reread(&luma, &mut reads, &mut refusals);
3723        assert_eq!(run.rereads, 1);
3724        assert!(refusals.is_empty());
3725        let (read, _) = &reads[0];
3726        assert_eq!(read.key.eci, eci_mark(4, 0));
3727        assert_eq!(read.margin, Margin::Known(-1));
3728        assert!(run.margin_rereads.is_empty(), "no margin re-read");
3729    }
3730
3731    #[test]
3732    fn a_margin_re_read_that_refuses_changes_nothing() {
3733        // 913:46: the port's read of the ECI-above-the-register symbol,
3734        // carried by a parse of its content where it lies, is re-read for its
3735        // margin only — at v1-M the stream it samples refuses, and a margin
3736        // re-read changes nothing: no read removed, no refusal recorded
3737        let luma = eci_above_the_register_abc();
3738        let dims = (luma.width(), luma.height());
3739        let port: Vec<RawDetection> = engine::decode_filtered(&luma, engine::FormatFilter::All)
3740            .detections
3741            .into_iter()
3742            .filter(|d| d.engine == EngineKind::Rxing)
3743            .collect();
3744        let cancel = CancelToken::new();
3745        let mut run = fresh_run(&cancel, dims);
3746        let mut reads = reads_of(&run, port, 0, dims);
3747        assert!(
3748            matches!(&reads[..], [(read, Some(hint))] if hint.declarations
3749                && read.key.eci == EciEvidence::Signalled),
3750            "{reads:?}"
3751        );
3752        let mut parse = Read::new(
3753            Symbology::QrCode,
3754            ContentKey {
3755                raw: b"abc".to_vec(),
3756                eci: eci_mark(3, 0),
3757                fnc1: Fnc1::None,
3758            },
3759            Some(EngineKind::Rqrr),
3760            Rank {
3761                source: source::RQRR,
3762                ..Rank::default()
3763            },
3764        )
3765        .at(reads[0].0.location);
3766        parse.parsed = true;
3767        reads.push((parse, None));
3768        let mut refusals = Vec::new();
3769        run.reread(&luma, &mut reads, &mut refusals);
3770        assert_eq!(run.rereads, 1, "its margin re-read");
3771        assert_eq!(run.margin_rereads.len(), 1);
3772        assert!(refusals.is_empty(), "{refusals:?}");
3773        assert_eq!(reads.len(), 2, "nothing removed");
3774        assert_eq!(reads[0].0.key.eci, EciEvidence::Signalled);
3775    }
3776
3777    #[test]
3778    fn a_re_read_learns_from_its_own_content_only() {
3779        // 943:62 · 958:66: a parse of other bytes where the port read lies
3780        // carries nothing, and a margin measured for other bytes measures
3781        // nothing — each content is asked about on its own
3782        let cancel = CancelToken::new();
3783        let mut run = fresh_run(&cancel, (400, 400));
3784        let at = square_at(100.0);
3785        let key = |raw: &[u8], eci| ContentKey {
3786            raw: raw.to_vec(),
3787            eci,
3788            fnc1: Fnc1::None,
3789        };
3790        let port = Read::new(
3791            Symbology::QrCode,
3792            key(b"abc", EciEvidence::Signalled),
3793            Some(EngineKind::Rxing),
3794            Rank::default(),
3795        )
3796        .at(Some(at));
3797        let declarations = LocateHint {
3798            points: at,
3799            frame: crate::engine::locate::Frame::OuterCorners,
3800            inverted: false,
3801            ec: EcLevel::L,
3802            versions: 1..=40,
3803            modifier: Some(2),
3804            declarations: true,
3805        };
3806        let mut other = Read::new(
3807            Symbology::QrCode,
3808            key(b"xyz", eci_mark(4, 0)),
3809            Some(EngineKind::Rqrr),
3810            Rank {
3811                source: source::RQRR,
3812                ..Rank::default()
3813            },
3814        )
3815        .at(Some(at));
3816        other.parsed = true;
3817        other.margin = Margin::Known(0);
3818        let reads = vec![(port.clone(), Some(declarations.clone())), (other, None)];
3819        assert_eq!(
3820            run.reread_hint(&port, &declarations, &reads),
3821            Some(declarations.clone())
3822        );
3823        // a margin re-read: another content's earlier one leaves it to run
3824        let margin = LocateHint {
3825            versions: crate::engine::locate::MARGIN_VERSIONS,
3826            modifier: Some(1),
3827            declarations: false,
3828            ..declarations
3829        };
3830        let plain = Read::new(
3831            Symbology::QrCode,
3832            key(b"abc", EciEvidence::NoEci),
3833            Some(EngineKind::Rxing),
3834            Rank::default(),
3835        )
3836        .at(Some(at));
3837        run.margin_rereads
3838            .push((Symbology::QrCode, key(b"xyz", EciEvidence::NoEci)));
3839        let alone = vec![(plain.clone(), Some(margin.clone()))];
3840        assert_eq!(
3841            run.reread_hint(&plain, &margin, &alone),
3842            Some(margin.clone())
3843        );
3844        // its own content's: none
3845        run.margin_rereads
3846            .push((Symbology::QrCode, key(b"abc", EciEvidence::NoEci)));
3847        assert_eq!(run.reread_hint(&plain, &margin, &alone), None);
3848    }
3849
3850    // ---- unparsed_qr ----
3851
3852    #[test]
3853    fn an_unparsed_qr_read_is_an_engine_read_of_a_qr_code_no_parse_read() {
3854        // 715: what keeps an attempt's candidates re-derived
3855        let read = |symbology, engine, parsed| {
3856            let key = ContentKey {
3857                raw: b"abc".to_vec(),
3858                eci: EciEvidence::NoEci,
3859                fnc1: Fnc1::None,
3860            };
3861            let mut read = Read::new(symbology, key, engine, Rank::default());
3862            read.parsed = parsed;
3863            read
3864        };
3865        assert!(unparsed_qr(&read(
3866            Symbology::QrCode,
3867            Some(EngineKind::Rxing),
3868            false
3869        )));
3870        assert!(unparsed_qr(&read(
3871            Symbology::QrCode,
3872            Some(EngineKind::Rqrr),
3873            false
3874        )));
3875        assert!(
3876            !unparsed_qr(&read(Symbology::QrCode, Some(EngineKind::Rxing), true)),
3877            "parsed"
3878        );
3879        assert!(
3880            !unparsed_qr(&read(Symbology::QrCode, None, false)),
3881            "no engine"
3882        );
3883        assert!(
3884            !unparsed_qr(&read(
3885                Symbology::MicroQrCode,
3886                Some(EngineKind::Rxing),
3887                false
3888            )),
3889            "another symbology"
3890        );
3891    }
3892
3893    // ---- LadderOutcome::fold_fallback ----
3894
3895    #[test]
3896    fn a_folded_fallback_walk_adds_its_time_and_keeps_either_cut() {
3897        // 659:29: the two walks' times add up — whichever found the content
3898        let outcome = |total_ms, cut| LadderOutcome {
3899            merged: Vec::new(),
3900            contents: Vec::new(),
3901            store: ReadStore::default(),
3902            rereads: 0,
3903            trace: PipelineTrace {
3904                stages: Vec::new(),
3905                engine_panics: 1,
3906                total_ms,
3907                budget_exhausted: Some(cut),
3908                saturation: Some(Saturation::default()),
3909                formats: None,
3910            },
3911        };
3912        let mut first = outcome(1.5, false);
3913        assert!(!first.fold_fallback(outcome(2.25, true)), "nothing found");
3914        assert_eq!(first.trace.total_ms, 3.75);
3915        assert_eq!(first.trace.engine_panics, 2);
3916        assert_eq!(first.trace.budget_exhausted, Some(true));
3917        let mut cut = outcome(4.0, true);
3918        cut.fold_fallback(outcome(0.5, false));
3919        assert_eq!(cut.trace.total_ms, 4.5);
3920        assert_eq!(cut.trace.budget_exhausted, Some(true));
3921    }
3922
3923    // ---- Run::collect_attempt ----
3924
3925    #[test]
3926    fn an_attempt_s_refusals_and_candidates_are_placed_in_original_space() {
3927        // 1099:17 · 1105:60 · 1110:21 · 1111:21: the ECI 26 GS1 symbol seen
3928        // by an inverting attempt at half the original size — rxing's port
3929        // read is unparsed, rqrr's grid a candidate. The attempt's own
3930        // unparsed QR read has the candidate re-derived (no read stands yet):
3931        // its parse lies at the grid's corners in original space, stamped
3932        // with the attempt's photometry, and lends them to the detection; a
3933        // refusal of the attempt is recorded at its place in original space
3934        let luma = eci26_gs1();
3935        let dims = (luma.width(), luma.height());
3936        let mut outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
3937        let [candidate] = &outcome.rescue[..] else {
3938            panic!("rqrr's grid: {:?}", outcome.rescue);
3939        };
3940        let grid = candidate.corners;
3941        let elsewhere = [
3942            Point { x: 1.0, y: 2.0 },
3943            Point { x: 3.0, y: 2.0 },
3944            Point { x: 3.0, y: 4.0 },
3945            Point { x: 1.0, y: 4.0 },
3946        ];
3947        let zzz = ContentKey {
3948            raw: b"zzz".to_vec(),
3949            eci: EciEvidence::Signalled,
3950            fnc1: Fnc1::None,
3951        };
3952        outcome.refused.push(Refusal {
3953            port: Some(zzz.clone()),
3954            rqrr: None,
3955            place: Some(elsewhere),
3956            grid: None,
3957        });
3958        let doubled = |corners: [Point; 4]| {
3959            corners.map(|p| Point {
3960                x: p.x * 2.0,
3961                y: p.y * 2.0,
3962            })
3963        };
3964        let cancel = CancelToken::new();
3965        let mut run = fresh_run(&cancel, (dims.0 * 2, dims.1 * 2));
3966        run.collect_attempt(&luma, outcome, true);
3967        let places: Vec<_> = run
3968            .store
3969            .seed(0)
3970            .refusals
3971            .into_iter()
3972            .filter(|refusal| refusal.port.as_ref() == Some(&zzz))
3973            .map(|refusal| refusal.place)
3974            .collect();
3975        assert_eq!(places, [Some(doubled(elsewhere))]);
3976        let found = run.store.reconcile();
3977        let [detection] = &found[..] else {
3978            panic!("one detection: {found:?}");
3979        };
3980        assert_eq!(detection.key.eci, eci_mark(26, 0), "the candidate's parse");
3981        assert_eq!(detection.geometry.corners, Some((doubled(grid), true)));
3982    }
3983
3984    // ---- Run::collect_rescue ----
3985
3986    #[test]
3987    fn collect_rescue_dedupes_by_symbol_identity() {
3988        // `==` -> `!=` (dedup identity). Two candidates with identical
3989        // (version, ec, mask, inverts) collapse to one.
3990        let cancel = CancelToken::new();
3991        let mut run = fresh_run(&cancel, (100, 100));
3992        let twin = || crate::rescue::RescueCandidate {
3993            stream: engine::MaskedStream {
3994                bits: vec![0u8; 8],
3995                bit_len: 64,
3996            },
3997            corners: [Point { x: 5.0, y: 5.0 }; 4],
3998            pixel: crate::engine::occurrence::UNIT_PIXEL,
3999            version: 3,
4000            ec: EcLevel::Q,
4001            mask: 2,
4002            inverted: false,
4003            transposed: false,
4004            rederived: None,
4005        };
4006        run.collect_rescue(vec![twin(), twin()], (100, 100), false);
4007        assert_eq!(run.rescue_candidates.len(), 1, "`!=` keeps the duplicate");
4008        // the same identity at another place is a twin: another input
4009        let mut elsewhere = twin();
4010        elsewhere.corners = [Point { x: 60.0, y: 60.0 }; 4];
4011        run.collect_rescue(vec![elsewhere], (100, 100), false);
4012        assert_eq!(run.rescue_candidates.len(), 2, "a twin elsewhere is kept");
4013    }
4014
4015    #[test]
4016    fn collect_rescue_rescales_corners_into_original_space() {
4017        // orig 200x100 over an attempt of 50x50 gives fx=4, fy=2
4018        // (deliberately distinct); a (10,10) corner must land at (40,20).
4019        let cancel = CancelToken::new();
4020        let mut run = fresh_run(&cancel, (200, 100));
4021        let candidate = crate::rescue::RescueCandidate {
4022            stream: engine::MaskedStream {
4023                bits: vec![0u8; 8],
4024                bit_len: 64,
4025            },
4026            corners: [Point { x: 10.0, y: 10.0 }; 4],
4027            pixel: crate::engine::occurrence::UNIT_PIXEL,
4028            version: 1,
4029            ec: EcLevel::M,
4030            mask: 0,
4031            inverted: false,
4032            transposed: false,
4033            rederived: None,
4034        };
4035        run.collect_rescue(vec![candidate], (50, 50), false);
4036        assert_eq!(run.rescue_candidates.len(), 1);
4037        let corner = run.rescue_candidates[0].corners[0];
4038        assert!((corner.x - 40.0).abs() < 1e-3, "{}", corner.x);
4039        assert!((corner.y - 20.0).abs() < 1e-3, "{}", corner.y);
4040    }
4041
4042    #[test]
4043    fn collect_rescue_leaves_full_res_corners_untouched() {
4044        let cancel = CancelToken::new();
4045        let mut run = fresh_run(&cancel, (120, 90));
4046        let candidate = crate::rescue::RescueCandidate {
4047            stream: engine::MaskedStream {
4048                bits: vec![0u8; 8],
4049                bit_len: 64,
4050            },
4051            corners: [Point { x: 12.0, y: 7.0 }; 4],
4052            pixel: crate::engine::occurrence::UNIT_PIXEL,
4053            version: 1,
4054            ec: EcLevel::M,
4055            mask: 0,
4056            inverted: false,
4057            transposed: false,
4058            rederived: None,
4059        };
4060        run.collect_rescue(vec![candidate], (120, 90), false);
4061        let corner = run.rescue_candidates[0].corners[0];
4062        assert!((corner.x - 12.0).abs() < 1e-3 && (corner.y - 7.0).abs() < 1e-3);
4063    }
4064
4065    // ---- Run::rescue_stage ----
4066
4067    #[test]
4068    fn rescue_stage_counts_and_times_every_candidate() {
4069        // `tried += 1` -> `*=` (freezes at 0) + `ms * 1000` -> `+ 1000`.
4070        // Three version-0 candidates fail `rescue::attempt` at its 1..=40
4071        // range check (no parsing, no panic): each TRIED, none FOUND.
4072        let cancel = CancelToken::new();
4073        let luma = LumaImage::new(vec![255u8; 100 * 100], 100, 100);
4074        let dud = || crate::rescue::RescueCandidate {
4075            stream: engine::MaskedStream {
4076                bits: Vec::new(),
4077                bit_len: 0,
4078            },
4079            corners: [Point { x: 0.0, y: 0.0 }; 4],
4080            pixel: crate::engine::occurrence::UNIT_PIXEL,
4081            version: 0,
4082            ec: EcLevel::M,
4083            mask: 0,
4084            inverted: false,
4085            transposed: false,
4086            rederived: None,
4087        };
4088        let mut run = fresh_run(&cancel, (100, 100));
4089        run.rescue_candidates = vec![dud(), dud(), dud()];
4090        let mut stages = Vec::new();
4091        run.rescue_stage(&luma, &mut stages).unwrap();
4092        let rescue = stages
4093            .iter()
4094            .find(|s| s.stage == "rescue")
4095            .expect("rescue stage pushed");
4096        assert_eq!(rescue.transforms_tried, 3, "`*=` freezes tried at 0");
4097        assert_eq!(rescue.detections_found, 0);
4098        assert!(rescue.ms < 100.0, "`+ 1000` reads ~1000ms ({})", rescue.ms);
4099        // a walk that published something never runs it
4100        let mut run = fresh_run(&cancel, (100, 100));
4101        run.rescue_candidates = vec![dud()];
4102        let rank = Rank::default();
4103        let key = ContentKey {
4104            raw: b"x".to_vec(),
4105            eci: EciEvidence::NoEci,
4106            fnc1: Fnc1::None,
4107        };
4108        run.store.collect(Read::new(
4109            Symbology::QrCode,
4110            key,
4111            Some(EngineKind::Rxing),
4112            rank,
4113        ));
4114        let mut stages = Vec::new();
4115        run.rescue_stage(&luma, &mut stages).unwrap();
4116        assert_eq!(stages.len(), 0);
4117    }
4118
4119    #[test]
4120    fn rescue_stage_reports_a_real_recovery() {
4121        // `found += 1` -> `*=` (freezes at 0). The occluded fixture is
4122        // recovered ONLY by S5 rescue; with budget_ms None the walk is fully
4123        // deterministic (no wall-clock cut).
4124        let bytes = std::fs::read(format!(
4125            "{}/../../fixtures/degraded/logo-occluded-rescue.png",
4126            env!("CARGO_MANIFEST_DIR")
4127        ))
4128        .unwrap();
4129        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
4130        let mut config = ScanConfig::full();
4131        config.budget_ms = None;
4132        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4133        assert_eq!(outcome.merged.len(), 1, "S5 recovers the occluded symbol");
4134        assert_eq!(outcome.merged[0].engines, vec![EngineKind::Rescue]);
4135        let rescue = outcome
4136            .trace
4137            .stages
4138            .iter()
4139            .find(|s| s.stage == "rescue")
4140            .expect("rescue stage ran");
4141        assert_eq!(rescue.detections_found, 1, "`*=` freezes found at 0");
4142        assert!(
4143            rescue.transforms_tried >= 1,
4144            "the winning candidate was tried"
4145        );
4146    }
4147
4148    // ---- Run::stage ----
4149
4150    #[test]
4151    fn stage_accumulates_raw_detections_found() {
4152        // `found_total += ..` -> `*=` (freezes at 0). A clean QR decodes,
4153        // so the deciding stage reports at least one raw hit.
4154        let bytes = qr_png("https://qrcode-ai.com/found-count-pin", 6);
4155        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
4156        let mut config = ScanConfig::full();
4157        config.budget_ms = None;
4158        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4159        assert_eq!(outcome.merged.len(), 1);
4160        let found: u32 = outcome
4161            .trace
4162            .stages
4163            .iter()
4164            .map(|s| s.detections_found)
4165            .sum();
4166        assert!(
4167            found >= 1,
4168            "`*=` freezes every stage's detections_found at 0"
4169        );
4170    }
4171
4172    #[test]
4173    fn the_trace_counts_every_hit_past_the_read_bound() {
4174        // one attempt delivering 65 distinct hits — the trace counts
4175        // all 65 (what `stage` adds to `detections_found`), 64 distinct
4176        // reads are reconciled (the 65th counted), at most 16 published
4177        let cancel = CancelToken::new();
4178        let img = LumaImage::new(vec![255u8; 64 * 64], 64, 64);
4179        let mut run = fresh_run(&cancel, (64, 64));
4180        let outcome = engine::EngineOutcome {
4181            detections: (0..65)
4182                .map(|i| {
4183                    RawDetection::qr(
4184                        format!("symbol-{i}").as_bytes(),
4185                        EciEvidence::NoEci,
4186                        Fnc1::None,
4187                        EngineKind::Rxing,
4188                    )
4189                })
4190                .collect(),
4191            ..engine::EngineOutcome::default()
4192        };
4193        assert_eq!(run.collect_attempt(&img, outcome, false), 65);
4194        assert_eq!(run.store.dropped, 1, "the 65th distinct read is counted");
4195        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4196        assert_eq!(
4197            walked.merged.len(),
4198            crate::engine::reconcile::MAX_DETECTIONS
4199        );
4200    }
4201
4202    #[test]
4203    fn stage_ms_stays_within_total_ms() {
4204        // stage `ms * 1000` -> `+ 1000` and total `ms * 1000` -> `+ 1000` /
4205        // `/ 1000`. Structural invariant: every stage is a sub-interval of
4206        // the whole run.
4207        let data = vec![255u8; 96 * 96];
4208        let planes = normalize(&ImageInput::luma8(&data, 96, 96), &Limits::default()).unwrap();
4209        let mut config = ScanConfig::full();
4210        config.budget_ms = None;
4211        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4212        let total = outcome.trace.total_ms;
4213        assert!((0.0..1_000.0).contains(&total), "{total}");
4214        for s in &outcome.trace.stages {
4215            assert!(
4216                s.ms >= 0.0 && s.ms <= total,
4217                "stage {} ms {} must sit within total {}",
4218                s.stage,
4219                s.ms,
4220                total
4221            );
4222        }
4223    }
4224
4225    // ---- LadderOutcome::fold_fallback ----
4226
4227    #[test]
4228    fn the_fallback_walk_starts_from_the_first_walks_refusals() {
4229        // walk 1 refused "abc" (its port content); walk 2 reads only a port
4230        // read of it there, and a plain detection — the refused one is not
4231        // published, the plain one replaces the empty walk 1
4232        let cancel = CancelToken::new();
4233        let place = [
4234            Point { x: 0.0, y: 0.0 },
4235            Point { x: 100.0, y: 0.0 },
4236            Point { x: 100.0, y: 100.0 },
4237            Point { x: 0.0, y: 100.0 },
4238        ];
4239        let mut walk1 = fresh_run(&cancel, (100, 100));
4240        walk1.store.refuse(
4241            engine::Refusal {
4242                port: Some(ContentKey {
4243                    raw: b"abc".to_vec(),
4244                    eci: EciEvidence::Signalled,
4245                    fnc1: Fnc1::None,
4246                }),
4247                rqrr: None,
4248                place: Some(place),
4249                grid: None,
4250            },
4251            0,
4252        );
4253        let mut first = walk1.finish_blank(Vec::new(), Instant::now()).unwrap();
4254        let mut walk2 = Run::new(&cancel, None, (100, 100), first.seed());
4255        let signalled = ContentKey {
4256            raw: b"abc".to_vec(),
4257            eci: EciEvidence::Signalled,
4258            fnc1: Fnc1::None,
4259        };
4260        let plain = ContentKey {
4261            raw: b"hello".to_vec(),
4262            eci: EciEvidence::NoEci,
4263            fnc1: Fnc1::None,
4264        };
4265        let rank = |index| Rank {
4266            attempt: 0,
4267            source: 0,
4268            index,
4269        };
4270        let at = Some([Point { x: 50.0, y: 50.0 }; 4]);
4271        walk2.store.collect(
4272            Read::new(
4273                Symbology::QrCode,
4274                signalled.clone(),
4275                Some(EngineKind::Rxing),
4276                rank(0),
4277            )
4278            .at(at),
4279        );
4280        walk2.store.collect(Read::new(
4281            Symbology::QrCode,
4282            plain,
4283            Some(EngineKind::Rxing),
4284            rank(1),
4285        ));
4286        let second = walk2.finish_blank(Vec::new(), Instant::now()).unwrap();
4287        assert_eq!(
4288            second.merged.len(),
4289            1,
4290            "the seed withholds the refused read"
4291        );
4292        assert!(first.fold_fallback(second));
4293        assert_eq!(first.merged.len(), 1);
4294        assert_eq!(first.merged[0].raw, b"hello");
4295        assert_eq!(first.contents[0].0.raw, b"hello", "aligned");
4296        // a walk-2 parse protecting that content keeps it: walk 2's own
4297        // seeded protection
4298        let mut walk1 = fresh_run(&cancel, (100, 100));
4299        walk1.store.refuse(
4300            engine::Refusal {
4301                port: Some(signalled.clone()),
4302                rqrr: None,
4303                place: None,
4304                grid: None,
4305            },
4306            0,
4307        );
4308        let mut first = walk1.finish_blank(Vec::new(), Instant::now()).unwrap();
4309        let mut walk2 = Run::new(&cancel, None, (100, 100), first.seed());
4310        walk2.store.collect(Read::new(
4311            Symbology::QrCode,
4312            signalled,
4313            Some(EngineKind::Rxing),
4314            rank(0),
4315        ));
4316        let mut located = Read::new(
4317            Symbology::QrCode,
4318            ContentKey {
4319                raw: b"abc".to_vec(),
4320                eci: eci_mark(26, 0),
4321                fnc1: Fnc1::None,
4322            },
4323            Some(EngineKind::Rqrr),
4324            rank(1),
4325        );
4326        located.parsed = true;
4327        walk2.store.collect(located);
4328        let second = walk2.finish_blank(Vec::new(), Instant::now()).unwrap();
4329        assert!(first.fold_fallback(second));
4330        assert_eq!(
4331            first.merged[0].engines,
4332            vec![EngineKind::Rxing, EngineKind::Rqrr]
4333        );
4334    }
4335
4336    #[test]
4337    fn a_fallback_read_made_outside_the_refused_symbol_stands() {
4338        // walk 1 refused "abc" at A; walk 2 reads it at A first, then at B
4339        // outside it — one folded read, which stands there. Folding the
4340        // fallback walk in keeps it: walk 2 already applied walk 1's
4341        // refusals and protection, place by place, so the fold needs no
4342        // guard of its own
4343        let cancel = CancelToken::new();
4344        let signalled = ContentKey {
4345            raw: b"abc".to_vec(),
4346            eci: EciEvidence::Signalled,
4347            fnc1: Fnc1::None,
4348        };
4349        let mut walk1 = fresh_run(&cancel, (400, 100));
4350        walk1.store.refuse(
4351            engine::Refusal {
4352                port: Some(signalled.clone()),
4353                rqrr: None,
4354                place: Some(square_at(0.0)),
4355                grid: None,
4356            },
4357            0,
4358        );
4359        let mut first = walk1.finish_blank(Vec::new(), Instant::now()).unwrap();
4360        assert!(first.merged.is_empty());
4361        let mut walk2 = Run::new(&cancel, None, (400, 100), first.seed());
4362        for (attempt, x) in [(0, 1.0), (1, 250.0)] {
4363            let rank = Rank {
4364                attempt,
4365                source: source::RXING,
4366                index: 0,
4367            };
4368            walk2.store.collect(
4369                Read::new(
4370                    Symbology::QrCode,
4371                    signalled.clone(),
4372                    Some(EngineKind::Rxing),
4373                    rank,
4374                )
4375                .at(Some(square_at(x))),
4376            );
4377        }
4378        let second = walk2.finish_blank(Vec::new(), Instant::now()).unwrap();
4379        assert_eq!(second.merged.len(), 1, "walk 2 publishes it");
4380        assert!(first.fold_fallback(second), "and the fold keeps it");
4381        assert_eq!(first.merged.len(), 1);
4382        assert_eq!(first.contents[0].0, signalled);
4383    }
4384
4385    #[test]
4386    fn a_walk_the_deadline_cut_leaves_the_folded_trace_partial() {
4387        // a walk whose deadline already passed plans an attempt it cannot
4388        // run (no wall clock decides it): folded with another walk, the
4389        // trace says the report is partial, whichever of the two was cut
4390        let cancel = CancelToken::new();
4391        let blank = LumaImage::new(vec![255u8; 64 * 64], 64, 64);
4392        let walk = |late: bool| {
4393            let mut run = if late {
4394                late_run(&cancel, (64, 64))
4395            } else {
4396                fresh_run(&cancel, (64, 64))
4397            };
4398            let mut stages = Vec::new();
4399            let attempts = vec![Attempt::plain(|| blank.clone())];
4400            run.stage("direct", attempts, engine::FormatFilter::All, &mut stages)
4401                .unwrap();
4402            run.finish_blank(stages, Instant::now()).unwrap()
4403        };
4404        for (first_cut, second_cut) in [(false, true), (true, false), (false, false), (true, true)]
4405        {
4406            let mut first = walk(first_cut);
4407            let second = walk(second_cut);
4408            assert_eq!(
4409                (first.trace.budget_exhausted, second.trace.budget_exhausted),
4410                (Some(first_cut), Some(second_cut))
4411            );
4412            assert!(!first.fold_fallback(second), "a blank plane: nothing found");
4413            assert_eq!(
4414                first.trace.budget_exhausted,
4415                Some(first_cut || second_cut),
4416                "first walk cut {first_cut}, second walk cut {second_cut}"
4417            );
4418            assert_eq!(first.trace.stages.len(), 2, "both walks stay in the trace");
4419        }
4420    }
4421
4422    // ---- deep_attempts ----
4423
4424    #[test]
4425    fn deep_attempts_full_res_grid_uses_the_stretch_variant() {
4426        // delete `!`. The (size=None, stretch=false) grid combo is SKIPPED
4427        // (it duplicates the S3 otsu/invert at full res); only (None,
4428        // stretch=true) survives. The lone inverting full-res grid attempt
4429        // must therefore build invert(contrast_stretch(luma)).
4430        let side = 64u32;
4431        let mut data = vec![0u8; (side * side) as usize];
4432        for (i, px) in data.iter_mut().enumerate() {
4433            *px = if i % 2 == 0 { 60 } else { 190 }; // bimodal, NOT full range
4434        }
4435        let luma = LumaImage::new(data, side, side);
4436        let attempts = deep_attempts(&luma, side);
4437        let inverting: Vec<&Attempt<'_>> = attempts.iter().filter(|a| a.inverts).collect();
4438        assert_eq!(
4439            inverting.len(),
4440            1,
4441            "one inverting full-res grid combo survives"
4442        );
4443        let got = (inverting[0].build)();
4444        let expected = transform::invert(&transform::contrast_stretch(&luma));
4445        assert_eq!(got.data(), expected.data());
4446    }
4447
4448    // ---- run: stage gating + early exit ----
4449
4450    #[test]
4451    fn pyramid_skipped_when_image_not_larger_than_pyramid_side() {
4452        // `>` -> `==`/`>=`. longest == pyramid_side means downscaling to
4453        // pyramid_side is a no-op, so the strict `>` skips the pyramid.
4454        let data = vec![255u8; 128 * 128];
4455        let planes = normalize(&ImageInput::luma8(&data, 128, 128), &Limits::default()).unwrap();
4456        let mut config = ScanConfig::full();
4457        config.pyramid_side = 128; // == longest
4458        config.budget_ms = None;
4459        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4460        assert!(
4461            !stage_names(&outcome).contains(&"pyramid"),
4462            "{:?}",
4463            stage_names(&outcome)
4464        );
4465    }
4466
4467    #[test]
4468    fn pyramid_runs_when_image_exceeds_pyramid_side() {
4469        // the gate's `run.admit()` replaced by `false`: with an available
4470        // budget the pyramid MUST run on an oversized image.
4471        let data = vec![255u8; 700 * 700];
4472        let planes = normalize(&ImageInput::luma8(&data, 700, 700), &Limits::default()).unwrap();
4473        let mut config = ScanConfig::full(); // pyramid_side = 512
4474        config.budget_ms = None;
4475        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4476        assert_eq!(stage_names(&outcome).first().copied(), Some("pyramid"));
4477    }
4478
4479    #[test]
4480    fn ladder_completes_linear_reads_after_pyramid_qr_then_stops() {
4481        // A successful QR thumbnail still requires the enabled linear-only
4482        // direct pass, then ends the walk without artistic QR recovery.
4483        let bytes = qr_png("https://qrcode-ai.com/pyr", 24); // > 512px longest
4484        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
4485        let mut config = ScanConfig::full();
4486        config.budget_ms = None;
4487        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4488        assert_eq!(outcome.merged.len(), 1, "pyramid decodes the symbol");
4489        #[cfg(feature = "engine-rxing")]
4490        assert_eq!(stage_names(&outcome), ["pyramid", "direct"]);
4491        #[cfg(not(feature = "engine-rxing"))]
4492        assert_eq!(stage_names(&outcome), ["pyramid"]);
4493    }
4494
4495    #[test]
4496    fn ladder_stops_after_direct_finds_a_symbol() {
4497        let bytes = qr_png("https://qrcode-ai.com/direct-stop-pin", 6); // < 512px
4498        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
4499        let mut config = ScanConfig::full();
4500        config.budget_ms = None;
4501        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4502        assert_eq!(outcome.merged.len(), 1);
4503        assert!(
4504            !stage_names(&outcome).contains(&"pyramid"),
4505            "{:?}",
4506            stage_names(&outcome)
4507        );
4508        assert!(
4509            !stage_names(&outcome).contains(&"enhance"),
4510            "{:?}",
4511            stage_names(&outcome)
4512        );
4513    }
4514
4515    #[test]
4516    fn enhance_stage_is_gated_by_its_config_flag() {
4517        let data = vec![255u8; 64 * 64];
4518        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
4519        let mut config = ScanConfig::full();
4520        config.enhance = false;
4521        config.budget_ms = None;
4522        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4523        assert!(
4524            !stage_names(&outcome).contains(&"enhance"),
4525            "{:?}",
4526            stage_names(&outcome)
4527        );
4528    }
4529
4530    #[test]
4531    fn ladder_stops_after_enhance_finds_a_symbol() {
4532        let bytes = qr_png("https://qrcode-ai.com/enhance-stop-pin", 6);
4533        let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
4534        let mut config = ScanConfig::full();
4535        config.pyramid = false;
4536        config.direct = false;
4537        config.budget_ms = None;
4538        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4539        assert_eq!(outcome.merged.len(), 1, "enhance decodes the symbol");
4540        assert!(
4541            !stage_names(&outcome).contains(&"deep"),
4542            "{:?}",
4543            stage_names(&outcome)
4544        );
4545    }
4546
4547    #[test]
4548    fn deep_stage_is_gated_by_its_config_flag() {
4549        let data = vec![255u8; 64 * 64];
4550        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
4551        let mut config = ScanConfig::full();
4552        config.deep = false;
4553        config.budget_ms = None;
4554        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4555        assert!(
4556            !stage_names(&outcome).contains(&"deep"),
4557            "{:?}",
4558            stage_names(&outcome)
4559        );
4560    }
4561
4562    // ---- the budget flag (trace.budget_exhausted) ----
4563
4564    /// A walk whose deadline has already passed.
4565    fn late_run(cancel: &CancelToken, orig: (u32, u32)) -> Run<'_> {
4566        Run::new(cancel, Some(Instant::now()), orig, Seed::default())
4567    }
4568
4569    /// A rescue candidate `rescue::attempt` rejects at its version check.
4570    fn dud_candidate() -> crate::rescue::RescueCandidate {
4571        crate::rescue::RescueCandidate {
4572            stream: engine::MaskedStream {
4573                bits: Vec::new(),
4574                bit_len: 0,
4575            },
4576            corners: [Point { x: 0.0, y: 0.0 }; 4],
4577            pixel: crate::engine::occurrence::UNIT_PIXEL,
4578            version: 0,
4579            ec: EcLevel::M,
4580            mask: 0,
4581            inverted: false,
4582            transposed: false,
4583            rederived: None,
4584        }
4585    }
4586
4587    #[test]
4588    fn an_attempt_the_deadline_prevents_is_flagged() {
4589        // the stage stops before its first attempt and the walk says so
4590        let cancel = CancelToken::new();
4591        let luma = LumaImage::new(vec![255u8; 64 * 64], 64, 64);
4592        let mut run = late_run(&cancel, (64, 64));
4593        let mut stages = Vec::new();
4594        let stop = run
4595            .stage(
4596                "direct",
4597                vec![Attempt::plain(|| luma.clone())],
4598                engine::FormatFilter::All,
4599                &mut stages,
4600            )
4601            .unwrap();
4602        assert!(stop, "a cut stage stops the ladder");
4603        assert_eq!(stages[0].transforms_tried, 0);
4604        let walked = run.finish_blank(stages, Instant::now()).unwrap();
4605        assert_eq!(walked.trace.budget_exhausted, Some(true));
4606    }
4607
4608    #[test]
4609    fn a_rescue_candidate_the_deadline_skips_is_flagged() {
4610        let cancel = CancelToken::new();
4611        let luma = LumaImage::new(vec![255u8; 100 * 100], 100, 100);
4612        let mut run = late_run(&cancel, (100, 100));
4613        run.rescue_candidates = vec![dud_candidate()];
4614        let mut stages = Vec::new();
4615        run.rescue_stage(&luma, &mut stages).unwrap();
4616        assert!(stages.is_empty(), "no candidate was tried: {stages:?}");
4617        let walked = run.finish_blank(stages, Instant::now()).unwrap();
4618        assert_eq!(walked.trace.budget_exhausted, Some(true));
4619        // nothing planned, nothing cut: S5 has no candidate to try
4620        let mut run = late_run(&cancel, (100, 100));
4621        run.rescue_stage(&luma, &mut Vec::new()).unwrap();
4622        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4623        assert_eq!(walked.trace.budget_exhausted, Some(false));
4624    }
4625
4626    #[test]
4627    fn the_reread_never_sets_the_flag() {
4628        // the re-read belongs to the attempt that read: past the deadline it
4629        // still runs, locates the declaration, and leaves the report final
4630        let luma = crate::rescue::test_symbols::from_segments(
4631            qrcode::Version::Normal(3),
4632            qrcode::EcLevel::M,
4633            |b| {
4634                b.push_eci_designator(4)?;
4635                b.push_byte_data(&[0xA1])
4636            },
4637        );
4638        let dims = (luma.width(), luma.height());
4639        let port: Vec<RawDetection> = engine::decode_filtered(&luma, engine::FormatFilter::All)
4640            .detections
4641            .into_iter()
4642            .filter(|d| d.engine == EngineKind::Rxing)
4643            .collect();
4644        assert!(!port.is_empty(), "precondition: the port reads the symbol");
4645        let cancel = CancelToken::new();
4646        let mut run = late_run(&cancel, dims);
4647        let outcome = engine::EngineOutcome {
4648            detections: port,
4649            ..engine::EngineOutcome::default()
4650        };
4651        run.collect_attempt(&luma, outcome, false);
4652        assert_eq!(run.rereads, 1, "the re-read ran past the deadline");
4653        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4654        assert_eq!(walked.contents[0].0.eci, eci_mark(4, 0));
4655        assert_eq!(walked.trace.budget_exhausted, Some(false));
4656    }
4657
4658    #[test]
4659    fn the_end_of_walk_pass_runs_past_the_deadline_unflagged() {
4660        // rqrr's grid from one attempt, rxing's read from another: the pass
4661        // that brings them together has no budget and cuts nothing
4662        let cancel = CancelToken::new();
4663        let luma = eci26_gs1();
4664        let dims = (luma.width(), luma.height());
4665        let outcome = engine::decode_filtered(&luma, engine::FormatFilter::All);
4666        let mut run = late_run(&cancel, dims);
4667        run.collect_rescue(outcome.rescue, dims, false);
4668        for (read, _) in reads_of(&run, outcome.detections, 1, dims) {
4669            run.store.collect(read);
4670        }
4671        let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4672        assert_eq!(walked.merged.len(), 1);
4673        assert!(walked.merged[0].fnc1 && walked.merged[0].corners.is_some());
4674        assert_eq!(walked.trace.budget_exhausted, Some(false));
4675    }
4676
4677    // ---- acceptance (07-pipeline § Acceptance) ----
4678
4679    #[test]
4680    fn a_read_one_error_past_the_reserve_publishes_nothing_and_reaches_s5() {
4681        // v1-L with three corrupted codewords at contrast 120/150: its reads
4682        // correct three errors, one past the reserve (⌊(7 − 3)/2⌋ − 3 = −1).
4683        // The stage that reads it does not end the walk, nothing is
4684        // published, and S5 tries its grid (no erasure there: the rescue's
4685        // guard refuses it too)
4686        let data =
4687            crate::rescue::test_symbols::stream("0100 00000011 01100001 01100010 01100011 0000");
4688        let sharp = crate::rescue::test_symbols::from_corrupted_codewords(
4689            qrcode::Version::Normal(1),
4690            qrcode::EcLevel::L,
4691            &data,
4692            &[0, 2, 4],
4693        );
4694        let low = LumaImage::new(
4695            sharp
4696                .data()
4697                .iter()
4698                .map(|&px| if px < 128 { 120 } else { 150 })
4699                .collect(),
4700            sharp.width(),
4701            sharp.height(),
4702        );
4703        let planes = normalize(
4704            &ImageInput::luma8(low.data(), low.width(), low.height()),
4705            &Limits::default(),
4706        )
4707        .unwrap();
4708        let mut config = ScanConfig::full();
4709        config.budget_ms = None;
4710        let outcome = run(&planes, &config, &CancelToken::new(), None).unwrap();
4711        assert!(outcome.merged.is_empty(), "{:?}", outcome.merged);
4712        let names = stage_names(&outcome);
4713        assert!(names.contains(&"enhance"), "{names:?}");
4714        let rescue = outcome
4715            .trace
4716            .stages
4717            .iter()
4718            .find(|s| s.stage == "rescue")
4719            .expect("S5 runs");
4720        assert!(rescue.transforms_tried >= 1, "{:?}", outcome.trace);
4721        // the stages counted the hits they delivered: read, not published
4722        let delivered: u32 = outcome
4723            .trace
4724            .stages
4725            .iter()
4726            .map(|s| s.detections_found)
4727            .sum();
4728        assert!(delivered >= 1, "{:?}", outcome.trace);
4729    }
4730
4731    #[test]
4732    fn confirmation_decodes_are_bounded_clock_free_and_cancellable() {
4733        // At most one per content and four per walk, including DataBar;
4734        // past the deadline too, never after cancellation.
4735        let plane = LumaImage::new(vec![255; 64 * 64], 64, 64);
4736        let upce = |raw: &[u8]| (Symbology::UpcE, raw.to_vec());
4737        let cancel = CancelToken::new();
4738        let mut run = Run::new(&cancel, Some(Instant::now()), (64, 64), Seed::default());
4739        assert!(run.out_of_budget());
4740        let pending = vec![
4741            upce(b"1"),
4742            upce(b"1"),
4743            (Symbology::DataBar, b"2".to_vec()),
4744            upce(b"3"),
4745            upce(b"4"),
4746            upce(b"5"),
4747            upce(b"6"),
4748        ];
4749        let attempts = run.attempts;
4750        run.confirm(&plane, pending, false);
4751        assert_eq!(
4752            run.confirmations,
4753            [
4754                upce(b"1"),
4755                (Symbology::DataBar, b"2".to_vec()),
4756                upce(b"3"),
4757                upce(b"4")
4758            ]
4759        );
4760        assert_eq!(run.attempts, attempts + 4, "one rank per decode");
4761        cancel.cancel();
4762        let mut run = fresh_run(&cancel, (64, 64));
4763        run.confirm(&plane, vec![upce(b"7")], false);
4764        assert_eq!(run.confirmations.len(), 0);
4765    }
4766
4767    #[test]
4768    fn a_retail_read_on_the_pyramid_settles_with_no_confirmation_decode() {
4769        // EAN-13 is no symbology the readers invent: its attempt ends the
4770        // walk and no confirmation decode runs
4771        let bytes = std::fs::read(format!(
4772            "{}/../../fixtures/symbology/ean13.png",
4773            env!("CARGO_MANIFEST_DIR")
4774        ))
4775        .unwrap();
4776        let img = image::load_from_memory(&bytes).unwrap().to_luma8();
4777        let img = image::imageops::resize(
4778            &img,
4779            img.width() * 2,
4780            img.height() * 2,
4781            image::imageops::FilterType::Nearest,
4782        );
4783        let luma = LumaImage::new(img.as_raw().clone(), img.width(), img.height());
4784        let cancel = CancelToken::new();
4785        let mut run = fresh_run(&cancel, (luma.width(), luma.height()));
4786        let mut stages = Vec::new();
4787        let attempts = vec![Attempt::plain(|| transform::downscale_to(&luma, 512))];
4788        run.stage("pyramid", attempts, engine::FormatFilter::All, &mut stages)
4789            .unwrap();
4790        assert!(run.store.settled());
4791        assert_eq!(run.confirmations.len(), 0);
4792    }
4793
4794    #[test]
4795    #[cfg(feature = "engine-rxing")]
4796    fn matrix_exclusion_whitens_the_covered_pixels_of_convex_regions_only() {
4797        // an upright square (the port's usual corners) on a plane wider than
4798        // high: exactly the pixels whose centres it covers, in rows of the
4799        // plane's own width; regions past the plane's edges are clipped to
4800        // it, and every region of the call applies. A concave or a flat
4801        // outline is no symbol's and excludes nothing
4802        let at = |pairs: [(f32, f32); 4]| pairs.map(|(x, y)| Point { x, y });
4803        let original = LumaImage::new(vec![17; 7 * 5], 7, 5);
4804        let upright = at([(1.0, 1.0), (5.0, 1.0), (5.0, 4.0), (1.0, 4.0)]);
4805        #[rustfmt::skip]
4806        let covered = [
4807            17, 17, 17, 17, 17, 17, 17,
4808            17, 255, 255, 255, 255, 17, 17,
4809            17, 255, 255, 255, 255, 17, 17,
4810            17, 255, 255, 255, 255, 17, 17,
4811            17, 17, 17, 17, 17, 17, 17,
4812        ];
4813        assert_eq!(
4814            exclude_matrix_regions(&original, &[upright]).data(),
4815            covered
4816        );
4817        let past_top_left = at([(-3.0, -2.0), (2.0, -2.0), (2.0, 2.0), (-3.0, 2.0)]);
4818        let past_bottom_right = at([(4.0, 2.0), (9.0, 2.0), (9.0, 8.0), (4.0, 8.0)]);
4819        #[rustfmt::skip]
4820        let clipped = [
4821            255, 255, 17, 17, 17, 17, 17,
4822            255, 255, 17, 17, 17, 17, 17,
4823            17, 17, 17, 17, 255, 255, 255,
4824            17, 17, 17, 17, 255, 255, 255,
4825            17, 17, 17, 17, 255, 255, 255,
4826        ];
4827        let both = [past_top_left, past_bottom_right];
4828        assert_eq!(exclude_matrix_regions(&original, &both).data(), clipped);
4829        let concave = at([(0.0, 0.0), (4.0, 2.0), (0.0, 4.0), (1.0, 2.0)]);
4830        let flat = at([(0.0, 0.0), (1.0, 1.0), (4.0, 4.0), (2.0, 2.0)]);
4831        for region in [concave, flat] {
4832            assert_eq!(exclude_matrix_regions(&original, &[region]), original);
4833        }
4834    }
4835
4836    // ---- Run::finish ----
4837
4838    #[test]
4839    fn the_reads_saturate_when_a_read_was_dropped_or_the_walk_failed_closed() {
4840        // (01-report § PipelineTrace) distinct reads past the walk's
4841        // capacity, or refused streams past every record (the walk failed
4842        // closed), leave reads unreconciled: what they held is unknown, not
4843        // absent. Neither: not saturated
4844        let cancel = CancelToken::new();
4845        let saturation = |dropped: u32, closed: bool| {
4846            let seed = Seed {
4847                closed,
4848                ..Seed::default()
4849            };
4850            let mut run = Run::new(&cancel, None, (8, 8), seed);
4851            run.store.dropped = dropped;
4852            let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4853            walked.trace.saturation
4854        };
4855        let reads = |reads| {
4856            Some(Saturation {
4857                reads,
4858                detections: false,
4859                occurrences: false,
4860            })
4861        };
4862        assert_eq!(saturation(0, false), reads(false));
4863        assert_eq!(saturation(1, false), reads(true));
4864        assert_eq!(saturation(0, true), reads(true));
4865        assert_eq!(saturation(3, true), reads(true));
4866    }
4867
4868    #[test]
4869    fn the_occurrences_saturate_past_sixteen_copies_whatever_the_footprints_kept() {
4870        // (01-report § Occurrences) one content read at more places than it
4871        // publishes occurrences (16) is flagged, and still flagged when its
4872        // footprints also passed what one read keeps (128): either capacity
4873        // leaves copies unknown. A single copy is complete
4874        let cancel = CancelToken::new();
4875        let plane = LumaImage::new(vec![255; 200 * 120], 200, 120);
4876        let walk = |copies: u16| {
4877            let mut run = fresh_run(&cancel, (200, 120));
4878            let detections = (0..copies)
4879                .map(|i| {
4880                    // ten-pixel squares twelve pixels apart, sixteen a row
4881                    let x = f32::from(i % 16) * 12.0 + 1.0;
4882                    let y = f32::from(i / 16) * 12.0 + 1.0;
4883                    let corners = vec![
4884                        Point { x, y },
4885                        Point { x: x + 10.0, y },
4886                        Point {
4887                            x: x + 10.0,
4888                            y: y + 10.0,
4889                        },
4890                        Point { x, y: y + 10.0 },
4891                    ];
4892                    let mut hit = RawDetection::qr(
4893                        b"copy",
4894                        EciEvidence::NoEci,
4895                        Fnc1::None,
4896                        EngineKind::Rxing,
4897                    );
4898                    hit.footprint = Footprint::candidate(Kind::Quad, corners, EngineKind::Rxing);
4899                    hit
4900                })
4901                .collect();
4902            let outcome = engine::EngineOutcome {
4903                detections,
4904                ..engine::EngineOutcome::default()
4905            };
4906            run.collect_attempt(&plane, outcome, false);
4907            let walked = run.finish_blank(Vec::new(), Instant::now()).unwrap();
4908            assert_eq!(walked.merged.len(), 1, "{copies} copies of one content");
4909            let occurrences = walked.merged[0].occurrences.len();
4910            (occurrences, walked.trace.saturation.map(|s| s.occurrences))
4911        };
4912        assert_eq!(walk(1), (1, Some(false)));
4913        assert_eq!(walk(17), (16, Some(true)));
4914        assert_eq!(walk(129), (16, Some(true)));
4915    }
4916
4917    /// The axis-aligned box from `(from, from)` to `(to, to)`, its corners
4918    /// in order from the first.
4919    fn axis_box(from: f32, to: f32) -> [Point; 4] {
4920        [
4921            Point { x: from, y: from },
4922            Point { x: to, y: from },
4923            Point { x: to, y: to },
4924            Point { x: from, y: to },
4925        ]
4926    }
4927
4928    /// A grid of `version` rqrr bounded at `bounds` on its unit pixel, not
4929    /// re-derived by the engine pass.
4930    fn grid_candidate(version: u8, bounds: [Point; 4]) -> RescueCandidate {
4931        RescueCandidate {
4932            stream: engine::MaskedStream {
4933                bits: Vec::new(),
4934                bit_len: 0,
4935            },
4936            corners: bounds,
4937            pixel: occurrence::UNIT_PIXEL,
4938            version,
4939            ec: EcLevel::M,
4940            mask: 0,
4941            inverted: false,
4942            transposed: false,
4943            rederived: None,
4944        }
4945    }
4946
4947    /// A quadrilateral footprint rqrr's grid measured.
4948    fn rqrr_quad(corners: [Point; 4]) -> Footprint {
4949        Footprint {
4950            kind: Kind::Quad,
4951            points: corners.to_vec(),
4952            detector: Some(EngineKind::Rqrr),
4953        }
4954    }
4955
4956    // ---- candidate_observation ----
4957
4958    #[test]
4959    fn a_candidate_observes_the_outer_corners_of_its_version_s_grid() {
4960        // rqrr's bounds frame one module past an N-module symbol, N = 4 ·
4961        // version + 17; the observation keeps the symbol's own N modules.
4962        // Upright at four pixels a module from (40, 40), version 1 (21
4963        // modules, bounds to 128) ends at 124, version 7 (45, to 224) at 220
4964        let rank = Rank {
4965            attempt: 3,
4966            source: source::CANDIDATE,
4967            index: 1,
4968        };
4969        for (version, bounds_end, symbol_end) in [(1, 128.0, 124.0), (7, 224.0, 220.0)] {
4970            let candidate = grid_candidate(version, axis_box(40.0, bounds_end));
4971            let observation = candidate_observation(&candidate, rank, (400, 400), 300)
4972                .expect("a grid inside the image is observed");
4973            assert_eq!(
4974                observation,
4975                Observation {
4976                    footprint: rqrr_quad(axis_box(40.0, symbol_end)),
4977                    rank,
4978                    side: 300,
4979                },
4980                "version {version}"
4981            );
4982        }
4983    }
4984
4985    // ---- Run::collect_attempt (candidate geometry) ----
4986
4987    #[test]
4988    fn a_re_derived_grid_is_observed_off_rqrr_s_anchor_in_original_pixels() {
4989        // rqrr anchors a half-turned grid one pixel of its plane short of
4990        // the symbol's corner along each axis, and the observation moves the
4991        // bounds back by that pixel in original space. An attempt at half
4992        // the original size bounds the grid from (61, 61) back to (17, 17):
4993        // (122, 122) to (34, 34) in the original, moved back by two original
4994        // pixels to (124, 124) and (36, 36), of which the version 1 symbol
4995        // keeps 21 of 22 modules: (124, 124) to (40, 40)
4996        let half_turned = [
4997            Point { x: 61.0, y: 61.0 },
4998            Point { x: 17.0, y: 61.0 },
4999            Point { x: 17.0, y: 17.0 },
5000            Point { x: 61.0, y: 17.0 },
5001        ];
5002        let mut candidate = grid_candidate(1, half_turned);
5003        candidate.rederived = Some(Rederived::Parsed {
5004            parsed: crate::rescue::bitstream::Parsed {
5005                bytes: b"abc".to_vec(),
5006                eci: Vec::new(),
5007                fnc1: Fnc1::None,
5008                structured_append: false,
5009                segments: Vec::new(),
5010                byte_segments: std::iter::once(0..3).collect(),
5011            },
5012            margin: 13,
5013        });
5014        let outcome = engine::EngineOutcome {
5015            detections: vec![RawDetection::qr(
5016                b"abc",
5017                EciEvidence::NoEci,
5018                Fnc1::None,
5019                EngineKind::Rxing,
5020            )],
5021            rescue: vec![candidate],
5022            ..engine::EngineOutcome::default()
5023        };
5024        let cancel = CancelToken::new();
5025        let mut run = fresh_run(&cancel, (200, 200));
5026        let plane = LumaImage::new(vec![255; 100 * 100], 100, 100);
5027        run.collect_attempt(&plane, outcome, false);
5028        let found = run.store.reconcile();
5029        let [detection] = &found[..] else {
5030            panic!("one detection: {found:?}");
5031        };
5032        let observed: Vec<(&Footprint, u32)> = detection
5033            .observations
5034            .iter()
5035            .map(|observation| (&observation.footprint, observation.side))
5036            .collect();
5037        let symbol = [
5038            Point { x: 124.0, y: 124.0 },
5039            Point { x: 40.0, y: 124.0 },
5040            Point { x: 40.0, y: 40.0 },
5041            Point { x: 124.0, y: 40.0 },
5042        ];
5043        assert_eq!(observed, [(&rqrr_quad(symbol), 100)]);
5044    }
5045
5046    // ---- Run::collect_rescue (one symbol) ----
5047
5048    #[test]
5049    fn a_grid_centred_in_a_collected_grid_of_its_identity_is_that_symbol() {
5050        // whichever of a large grid and a small one inside it comes first,
5051        // only the centre of the small one lies in the other's box: they are
5052        // one symbol, and the first is kept; a grid beside them is another
5053        let (large, small, beside) = (
5054            axis_box(0.0, 100.0),
5055            axis_box(0.0, 20.0),
5056            axis_box(150.0, 170.0),
5057        );
5058        let cancel = CancelToken::new();
5059        for (first, second) in [(large, small), (small, large)] {
5060            let mut run = fresh_run(&cancel, (200, 200));
5061            let both = vec![grid_candidate(2, first), grid_candidate(2, second)];
5062            run.collect_rescue(both, (200, 200), false);
5063            run.collect_rescue(vec![grid_candidate(2, beside)], (200, 200), false);
5064            let kept: Vec<[Point; 4]> = run.rescue_candidates.iter().map(|c| c.corners).collect();
5065            assert_eq!(kept, [first, beside]);
5066        }
5067    }
5068}
5069
5070#[cfg(test)]
5071mod plane_pass_reuse {
5072    //! An attempt that rebuilds the walk's working plane reuses the engine
5073    //! pass made over it ([`Run::engine_pass`]): the walk reads, counts and
5074    //! traces what the walk that runs every pass does, in fewer passes.
5075    #![allow(clippy::unwrap_used, clippy::expect_used)]
5076
5077    use super::*;
5078    use crate::input::{ImageInput, Limits};
5079    use crate::transform::normalize;
5080    use pretty_assertions::assert_eq;
5081
5082    /// An unbounded walk as it ends, wall time left out, and the engine
5083    /// passes it ran. `every_pass`: no attempt reuses one.
5084    fn walked(planes: &SourcePlanes, config: &ScanConfig, every_pass: bool) -> (String, u32) {
5085        EVERY_PASS_RUNS.with(|flag| flag.set(every_pass));
5086        ENGINE_PASSES.with(|passes| passes.set(0));
5087        let outcome = run(planes, config, &CancelToken::new(), None);
5088        EVERY_PASS_RUNS.with(|flag| flag.set(false));
5089        let mut outcome = outcome.unwrap();
5090        outcome.trace.total_ms = 0.0;
5091        for stage in &mut outcome.trace.stages {
5092            stage.ms = 0.0;
5093        }
5094        (
5095            format!("{outcome:#?}"),
5096            ENGINE_PASSES.with(std::cell::Cell::get),
5097        )
5098    }
5099
5100    fn unbounded() -> ScanConfig {
5101        let mut config = ScanConfig::full();
5102        config.budget_ms = None;
5103        config
5104    }
5105
5106    /// A 64 px plane no reader decodes, spanning 0 to 255.
5107    fn full_range_noise() -> Vec<u8> {
5108        let data: Vec<u8> = (0..64u32 * 64)
5109            .map(|i| u8::try_from((i % 64 * 7 + i / 64 * 13) % 256).unwrap())
5110            .collect();
5111        assert!(data.contains(&0) && data.contains(&255));
5112        data
5113    }
5114
5115    #[test]
5116    fn a_stretch_that_changes_nothing_reuses_the_direct_pass() {
5117        let data = full_range_noise();
5118        let planes = normalize(&ImageInput::luma8(&data, 64, 64), &Limits::default()).unwrap();
5119        // the identity the reuse stands on: this stretch is the plane itself
5120        assert_eq!(transform::contrast_stretch(&planes.luma), planes.luma);
5121        let (reference, every) = walked(&planes, &unbounded(), true);
5122        let (reused, fewer) = walked(&planes, &unbounded(), false);
5123        assert_eq!(reused, reference);
5124        // one attempt in the walk rebuilds the plane: the enhance stretch
5125        assert_eq!(every - fewer, 1, "{fewer} of {every}");
5126    }
5127
5128    #[test]
5129    fn a_grey_source_stored_as_rgb_reads_its_plane_once() {
5130        let grey = full_range_noise();
5131        let rgba: Vec<u8> = grey.iter().flat_map(|&v| [v, v, v, 255]).collect();
5132        let planes = normalize(&ImageInput::rgba8(&rgba, 64, 64), &Limits::default()).unwrap();
5133        assert!(planes.has_color());
5134        assert_eq!(planes.channel(Channel::G).unwrap(), planes.luma);
5135        let (reference, every) = walked(&planes, &unbounded(), true);
5136        let (reused, fewer) = walked(&planes, &unbounded(), false);
5137        assert_eq!(reused, reference);
5138        // the stretch and the three channels are the plane the direct
5139        // stage read
5140        assert_eq!(every - fewer, 4, "{fewer} of {every}");
5141    }
5142
5143    /// One stage of `attempts` under `filter`: the attempts and the reads
5144    /// its trace counts.
5145    fn staged(
5146        run: &mut Run<'_>,
5147        attempts: Vec<Attempt<'_>>,
5148        filter: engine::FormatFilter,
5149    ) -> (u32, u32) {
5150        let mut stages = Vec::new();
5151        run.stage("pin", attempts, filter, &mut stages).unwrap();
5152        (stages[0].transforms_tried, stages[0].detections_found)
5153    }
5154
5155    fn passes() -> u32 {
5156        ENGINE_PASSES.with(std::cell::Cell::get)
5157    }
5158
5159    #[test]
5160    fn a_pass_is_reused_for_the_same_plane_under_the_same_filter_only() {
5161        let code = qrcode::QrCode::with_error_correction_level(
5162            "https://qrcode-ai.com/plane-pass-pin",
5163            qrcode::EcLevel::Q,
5164        )
5165        .unwrap();
5166        let img = code
5167            .render::<image::Luma<u8>>()
5168            .module_dimensions(4, 4)
5169            .build();
5170        let dims = (img.width(), img.height());
5171        let plane = LumaImage::new(img.into_raw(), dims.0, dims.1);
5172        let other = transform::invert(&plane);
5173        let twice = || {
5174            vec![
5175                Attempt::plain(|| plane.clone()),
5176                Attempt::plain(|| plane.clone()),
5177            ]
5178        };
5179        let cancel = CancelToken::new();
5180
5181        // the walk held to: no working plane, every attempt runs the engines
5182        ENGINE_PASSES.with(|count| count.set(0));
5183        let mut bare = Run::new(&cancel, None, dims, Seed::default());
5184        let every = staged(&mut bare, twice(), engine::FormatFilter::All);
5185        assert_eq!(passes(), 2);
5186        assert_eq!(every.0, 2);
5187        assert!(every.1 >= 2, "each attempt delivers the symbol: {every:?}");
5188
5189        ENGINE_PASSES.with(|count| count.set(0));
5190        let mut run = Run::new(&cancel, None, dims, Seed::default());
5191        run.plane = Some(&plane);
5192        // the second attempt is collected and counted from the first's pass
5193        assert_eq!(staged(&mut run, twice(), engine::FormatFilter::All), every);
5194        assert_eq!(passes(), 1);
5195        assert_eq!(run.attempts, 2);
5196        // another filter is another pass over the plane, made once as well
5197        let family = staged(&mut run, twice(), engine::FormatFilter::QrFamily);
5198        assert_eq!(passes(), 2);
5199        assert_eq!(family.0, 2);
5200        assert!(
5201            family.1 >= 2,
5202            "each attempt delivers the symbol: {family:?}"
5203        );
5204        // another image never takes the plane's pass
5205        let inverted = staged(
5206            &mut run,
5207            vec![Attempt::inverting(|| other.clone())],
5208            engine::FormatFilter::All,
5209        );
5210        assert_eq!(passes(), 3);
5211        assert_eq!(inverted.0, 1);
5212        // and both filters' passes are still the plane's
5213        assert_eq!(staged(&mut run, twice(), engine::FormatFilter::All), every);
5214        assert_eq!(
5215            staged(&mut run, twice(), engine::FormatFilter::QrFamily),
5216            family
5217        );
5218        assert_eq!(passes(), 3);
5219    }
5220
5221    /// The committed fixtures under `dir`, the PDF417 ones left out: rxing's
5222    /// PDF417 reader is the one documented reader that is not a function of
5223    /// its image (spec/04 § Determinism).
5224    fn fixtures(dir: &str) -> Vec<std::path::PathBuf> {
5225        let dir = format!("{}/../../fixtures/{dir}", env!("CARGO_MANIFEST_DIR"));
5226        let mut paths: Vec<std::path::PathBuf> = std::fs::read_dir(&dir)
5227            .unwrap()
5228            .map(|entry| entry.unwrap().path())
5229            .filter(|path| {
5230                let image = path.extension().is_some_and(|ext| {
5231                    ["png", "jpg", "webp"]
5232                        .iter()
5233                        .any(|own| ext.eq_ignore_ascii_case(own))
5234                });
5235                let pdf417 = path
5236                    .file_name()
5237                    .is_some_and(|name| name.to_string_lossy().starts_with("pdf417"));
5238                image && !pdf417
5239            })
5240            .collect();
5241        paths.sort();
5242        assert!(!paths.is_empty(), "no fixture under {dir}");
5243        paths
5244    }
5245
5246    /// Both walks of every fixture under `dir` agree; returns the engine
5247    /// passes of (the walk that runs every pass, the walk that reuses).
5248    fn walks_agree(dir: &str, config: &ScanConfig) -> (u32, u32) {
5249        let (mut every_total, mut fewer_total) = (0, 0);
5250        for path in fixtures(dir) {
5251            let bytes = std::fs::read(&path).unwrap();
5252            let planes = normalize(&ImageInput::encoded(&bytes), &Limits::default()).unwrap();
5253            let (reference, every) = walked(&planes, config, true);
5254            let (reused, fewer) = walked(&planes, config, false);
5255            assert_eq!(reused, reference, "{}", path.display());
5256            assert!(fewer <= every, "{}", path.display());
5257            every_total += every;
5258            fewer_total += fewer;
5259        }
5260        (every_total, fewer_total)
5261    }
5262
5263    #[test]
5264    fn symbology_fixtures_walk_the_same_with_and_without_reuse() {
5265        let (every, fewer) = walks_agree("symbology", &unbounded());
5266        assert!(fewer <= every, "{fewer} of {every}");
5267        // read as QR Code only, most of these walk the whole ladder: the
5268        // comparison covers reused passes
5269        let qr_only = ScanConfig {
5270            formats: vec![Symbology::QrCode],
5271            ..unbounded()
5272        };
5273        let (every, fewer) = walks_agree("symbology", &qr_only);
5274        assert!(fewer < every, "{fewer} of {every}");
5275    }
5276
5277    #[test]
5278    fn qr_fixtures_walk_the_same_with_and_without_reuse() {
5279        let qr_only = ScanConfig {
5280            formats: vec![Symbology::QrCode],
5281            ..unbounded()
5282        };
5283        for dir in ["clean", "degraded", "eci", "payloads"] {
5284            walks_agree(dir, &qr_only);
5285        }
5286    }
5287}
5288
5289#[cfg(test)]
5290mod second_line {
5291    //! A UPC-E, EAN-8, EAN-13 or UPC-A read is held to a second scan line
5292    //! (07-pipeline § Acceptance, rule 3): where the two bands lie, and what
5293    //! they keep and refuse.
5294    #![allow(clippy::unwrap_used, clippy::expect_used)]
5295
5296    use super::*;
5297    use pretty_assertions::assert_eq;
5298
5299    /// A plane whose every pixel says where it is: `x + 16 * y`, modulo 251.
5300    fn addressed(width: u32, height: u32) -> LumaImage {
5301        let data = (0..height)
5302            .flat_map(|y| (0..width).map(move |x| u8::try_from((x + 16 * y) % 251).unwrap()))
5303            .collect();
5304        LumaImage::new(data, width, height)
5305    }
5306
5307    /// The rectangle of `plane` from `(left, top)`, `width` by `height`.
5308    fn rectangle(plane: &LumaImage, left: u32, top: u32, width: u32, height: u32) -> LumaImage {
5309        let data = (top..top + height)
5310            .flat_map(|y| (left..left + width).map(move |x| (x, y)))
5311            .map(|(x, y)| plane.data()[(y * plane.width() + x) as usize])
5312            .collect();
5313        LumaImage::new(data, width, height)
5314    }
5315
5316    fn at(x: f32, y: f32) -> Point {
5317        Point { x, y }
5318    }
5319
5320    /// The pixel of `plane` at `(x, y)`.
5321    fn pixel(plane: &LumaImage, x: u32, y: u32) -> u8 {
5322        plane.data()[(y * plane.width() + x) as usize]
5323    }
5324
5325    /// The two bands beside the scan line through `a` and `b`: after it,
5326    /// then before it.
5327    fn second_line_bands(plane: &LumaImage, a: Point, b: Point) -> [Option<LumaImage>; 2] {
5328        let line = ScanLine::through(a, b, UPCE).unwrap();
5329        [line.beside(plane, true), line.beside(plane, false)]
5330    }
5331
5332    #[test]
5333    fn the_bands_lie_three_to_eight_modules_from_a_row_and_fourteen_past_its_points() {
5334        // points 93 px apart: a module of 2 px. Along the row, 28 px before
5335        // the first point and 28 px past the second; across it, the rows 6
5336        // to 15 below row 50 and the rows 6 to 15 above it
5337        let plane = addressed(200, 100);
5338        let [below, above] = second_line_bands(&plane, at(40.0, 50.5), at(133.0, 50.5));
5339        assert_eq!(below.unwrap(), rectangle(&plane, 12, 56, 149, 10));
5340        assert_eq!(above.unwrap(), rectangle(&plane, 12, 35, 149, 10));
5341        // the points in the other order: the same bands
5342        let [below, above] = second_line_bands(&plane, at(133.0, 50.5), at(40.0, 50.5));
5343        assert_eq!(below.unwrap(), rectangle(&plane, 12, 56, 149, 10));
5344        assert_eq!(above.unwrap(), rectangle(&plane, 12, 35, 149, 10));
5345    }
5346
5347    #[test]
5348    fn the_bands_of_a_column_lie_to_its_right_and_to_its_left() {
5349        let plane = addressed(100, 200);
5350        let [right, left] = second_line_bands(&plane, at(50.5, 40.0), at(50.5, 133.0));
5351        assert_eq!(right.unwrap(), rectangle(&plane, 56, 12, 10, 149));
5352        assert_eq!(left.unwrap(), rectangle(&plane, 35, 12, 10, 149));
5353    }
5354
5355    #[test]
5356    fn a_band_stops_at_the_edges_of_the_plane_and_a_band_outside_it_is_none() {
5357        // row 9, a module of 2 px: the band above would hold rows -6 to 3,
5358        // and holds rows 0 to 3; along the row the plane ends first
5359        let plane = addressed(100, 30);
5360        let [below, above] = second_line_bands(&plane, at(3.0, 9.5), at(96.0, 9.5));
5361        assert_eq!(below.unwrap(), rectangle(&plane, 0, 15, 100, 10));
5362        assert_eq!(above.unwrap(), rectangle(&plane, 0, 0, 100, 4));
5363        // row 20: the band below would hold rows 26 to 35, and holds 26 to 29
5364        let [below, above] = second_line_bands(&plane, at(3.0, 20.5), at(96.0, 20.5));
5365        assert_eq!(below.unwrap(), rectangle(&plane, 0, 26, 100, 4));
5366        assert_eq!(above.unwrap(), rectangle(&plane, 0, 5, 100, 10));
5367        // row 5: no row lies six rows above it
5368        let [below, above] = second_line_bands(&plane, at(3.0, 5.5), at(96.0, 5.5));
5369        assert_eq!(below.unwrap(), rectangle(&plane, 0, 11, 100, 10));
5370        assert_eq!(above, None);
5371        // row 6: one does
5372        let [_, above] = second_line_bands(&plane, at(3.0, 6.5), at(96.0, 6.5));
5373        assert_eq!(above.unwrap(), rectangle(&plane, 0, 0, 100, 1));
5374        // row 24: none lies six rows below it; row 23: one does
5375        let [below, above] = second_line_bands(&plane, at(3.0, 24.5), at(96.0, 24.5));
5376        assert_eq!(below, None);
5377        assert_eq!(above.unwrap(), rectangle(&plane, 0, 9, 100, 10));
5378        let [below, _] = second_line_bands(&plane, at(3.0, 23.5), at(96.0, 23.5));
5379        assert_eq!(below.unwrap(), rectangle(&plane, 0, 29, 100, 1));
5380    }
5381
5382    #[test]
5383    fn a_module_counts_for_one_pixel_at_least() {
5384        // points 20 px apart: under half a pixel per module, counted as one
5385        let plane = addressed(100, 30);
5386        let [below, above] = second_line_bands(&plane, at(40.0, 10.5), at(60.0, 10.5));
5387        assert_eq!(below.unwrap(), rectangle(&plane, 26, 13, 48, 5));
5388        assert_eq!(above.unwrap(), rectangle(&plane, 26, 3, 48, 5));
5389    }
5390
5391    #[test]
5392    fn a_line_that_is_no_row_and_no_column_is_no_scan_line() {
5393        for (a, b) in [
5394            // a slope
5395            (at(10.0, 10.5), at(60.0, 40.5)),
5396            // one pixel off the row at its far end
5397            (at(10.0, 10.5), at(60.0, 11.5)),
5398            // one pixel off the column at its far end
5399            (at(10.5, 10.0), at(11.5, 60.0)),
5400            // no length
5401            (at(10.0, 10.5), at(10.5, 10.5)),
5402            (at(f32::NAN, 10.5), at(60.0, 10.5)),
5403            (at(10.0, 10.5), at(f32::INFINITY, 10.5)),
5404        ] {
5405            assert_eq!(ScanLine::through(a, b, UPCE), None, "{a:?} {b:?}");
5406        }
5407    }
5408
5409    /// The 51 modules of the UPC-E symbol `01234565`.
5410    #[cfg(feature = "engine-rxing")]
5411    const UPCE_01234565: &str = "101011001100100110111101001110101110010101111010101";
5412
5413    /// The 47 modules of the five-digit add-on `12345`: its guard, then the
5414    /// digits with a separator between them, in the parities of its check
5415    /// value 1 (even, odd, even, odd, odd).
5416    #[cfg(feature = "engine-rxing")]
5417    const ADD_ON_12345: &str = "10110110011010010011010100001010100011010110001";
5418
5419    /// A plane of `height` rows whose rows `bars` hold `modules`, 4 px per
5420    /// module, 40 px of white before and after them.
5421    #[cfg(feature = "engine-rxing")]
5422    fn barred(modules: &str, height: u32, bars: std::ops::Range<u32>) -> LumaImage {
5423        let width = u32::try_from(modules.len()).unwrap() * 4 + 80;
5424        let data = (0..height)
5425            .flat_map(|y| {
5426                let bars = bars.clone();
5427                (0..width).map(move |x| {
5428                    let module = x.checked_sub(40).map(|inside| (inside / 4) as usize);
5429                    let bar = bars.contains(&y)
5430                        && module.and_then(|i| modules.as_bytes().get(i)) == Some(&b'1');
5431                    if bar { 0 } else { 255 }
5432                })
5433            })
5434            .collect();
5435        LumaImage::new(data, width, height)
5436    }
5437
5438    /// That plane for the UPC-E symbol alone.
5439    #[cfg(feature = "engine-rxing")]
5440    fn upce(height: u32, bars: std::ops::Range<u32>) -> LumaImage {
5441        barred(UPCE_01234565, height, bars)
5442    }
5443
5444    /// The UPC-E reads of a pass over `plane`.
5445    #[cfg(feature = "engine-rxing")]
5446    fn upce_reads(plane: &LumaImage) -> Vec<RawDetection> {
5447        engine::decode_filtered(plane, engine::FormatFilter::Only(Symbology::UpcE)).detections
5448    }
5449
5450    #[test]
5451    #[cfg(feature = "engine-rxing")]
5452    fn a_upce_with_bars_reads_beside_its_line_and_one_drawn_on_a_single_row_does_not() {
5453        // 100 rows of bars: every row reads, the bands beside the first too
5454        let tall = upce(140, 20..120);
5455        let reads = upce_reads(&tall);
5456        assert_eq!(reads.len(), 1);
5457        assert_eq!(reads[0].raw, b"01234565");
5458        assert_eq!(reads[0].footprint.kind, Kind::Segment);
5459        let mut panics = 0;
5460        assert!(reads_on_a_second_line(
5461            &tall,
5462            &reads[0],
5463            &|| false,
5464            &mut panics
5465        ));
5466        // the same symbol on the one row the reader starts with: it reads
5467        // there, and no band holds it
5468        let flat = upce(140, 70..71);
5469        let reads = upce_reads(&flat);
5470        assert_eq!(reads.len(), 1);
5471        assert_eq!(reads[0].raw, b"01234565");
5472        assert!(!reads_on_a_second_line(
5473            &flat,
5474            &reads[0],
5475            &|| false,
5476            &mut panics
5477        ));
5478        // bars thirteen rows tall around that row, three modules and a
5479        // quarter: the rows that read lie under two modules from the first,
5480        // as the two sides of a round module do, and the bands start past
5481        // them
5482        let low = upce(140, 64..77);
5483        let reads = upce_reads(&low);
5484        assert_eq!(reads.len(), 1);
5485        assert_eq!(reads[0].raw, b"01234565");
5486        assert!(!reads_on_a_second_line(
5487            &low,
5488            &reads[0],
5489            &|| false,
5490            &mut panics
5491        ));
5492        // a band that reads other digits keeps nothing: the read's own bytes
5493        // are asked for
5494        let mut other = reads[0].clone();
5495        other.raw = b"01234572".to_vec();
5496        assert!(!reads_on_a_second_line(
5497            &tall,
5498            &other,
5499            &|| false,
5500            &mut panics
5501        ));
5502        // nothing measured, nothing kept
5503        let mut unmeasured = upce_reads(&tall).remove(0);
5504        unmeasured.footprint = Footprint::unavailable();
5505        assert!(!reads_on_a_second_line(
5506            &tall,
5507            &unmeasured,
5508            &|| false,
5509            &mut panics
5510        ));
5511        assert_eq!(panics, 0);
5512    }
5513
5514    /// The 95 modules of the EAN-13 symbol `4006381333931`.
5515    #[cfg(feature = "engine-rxing")]
5516    const EAN13_4006381333931: &str = "10100011010100111010111101111010001001011001101010100001010000101000010111010010000101100110101";
5517
5518    /// The 67 modules of the EAN-8 symbol `96385074`.
5519    #[cfg(feature = "engine-rxing")]
5520    const EAN8_96385074: &str =
5521        "1010001011010111101111010110111010101001110111001010001001011100101";
5522
5523    #[test]
5524    #[cfg(feature = "engine-rxing")]
5525    fn an_ean_with_bars_reads_beside_its_line_and_one_drawn_on_a_single_row_does_not() {
5526        // the module of an EAN-13 and of an EAN-8 read is their points'
5527        // distance over their own span: 4 px, as drawn
5528        for (symbology, modules, text) in [
5529            (Symbology::Ean13, EAN13_4006381333931, "4006381333931"),
5530            (Symbology::Ean8, EAN8_96385074, "96385074"),
5531        ] {
5532            let reads_of = |plane: &LumaImage| {
5533                engine::decode_filtered(plane, engine::FormatFilter::Only(symbology)).detections
5534            };
5535            let tall = barred(modules, 140, 20..120);
5536            let reads = reads_of(&tall);
5537            assert_eq!(reads.len(), 1, "{symbology:?}");
5538            assert_eq!(reads[0].raw, text.as_bytes(), "{symbology:?}");
5539            let [a, b] = reads[0].footprint.points[..] else {
5540                panic!("{symbology:?}: a scan line has two points");
5541            };
5542            let line = ScanLine::through(a, b, bars(symbology).unwrap()).unwrap();
5543            assert!((line.module - 4.0).abs() < 0.1, "{symbology:?}: {line:?}");
5544            let mut panics = 0;
5545            assert!(reads_on_a_second_line(
5546                &tall,
5547                &reads[0],
5548                &|| false,
5549                &mut panics
5550            ));
5551            // on the one row the reader starts with: no band holds it
5552            let flat = barred(modules, 140, 70..71);
5553            let reads = reads_of(&flat);
5554            assert_eq!(reads.len(), 1, "{symbology:?}");
5555            assert!(!reads_on_a_second_line(
5556                &flat,
5557                &reads[0],
5558                &|| false,
5559                &mut panics
5560            ));
5561            assert_eq!(panics, 0);
5562        }
5563    }
5564
5565    #[test]
5566    #[cfg(feature = "engine-rxing")]
5567    fn a_upce_turned_a_quarter_reads_beside_its_column() {
5568        let tall = upce(140, 20..120);
5569        // the transpose: bars along the rows, read down a column
5570        let turned = LumaImage::new(
5571            (0..tall.width())
5572                .flat_map(|x| (0..tall.height()).map(move |y| (x, y)))
5573                .map(|(x, y)| tall.data()[(y * tall.width() + x) as usize])
5574                .collect(),
5575            tall.height(),
5576            tall.width(),
5577        );
5578        let reads = upce_reads(&turned);
5579        assert_eq!(reads.len(), 1);
5580        let [a, b] = reads[0].footprint.points[..] else {
5581            panic!("a scan line has two points");
5582        };
5583        assert!((a.x - b.x).abs() < 1.0 && (a.y - b.y).abs() > 100.0);
5584        assert!(reads_on_a_second_line(
5585            &turned,
5586            &reads[0],
5587            &|| false,
5588            &mut 0
5589        ));
5590    }
5591
5592    #[test]
5593    #[cfg(feature = "engine-rxing")]
5594    fn only_upc_ean_reads_are_held_to_a_second_line_and_a_refused_read_is_still_counted() {
5595        let held = [
5596            (Symbology::UpcE, UPCE),
5597            (Symbology::Ean8, EAN8),
5598            (Symbology::Ean13, EAN13),
5599            (Symbology::UpcA, EAN13),
5600        ];
5601        for symbology in crate::report::Symbology::ALL {
5602            let own = held.iter().find(|(s, _)| *s == symbology).map(|(_, b)| *b);
5603            assert_eq!(bars(symbology), own, "{symbology:?}");
5604            assert_eq!(needs_second_line(symbology), own.is_some(), "{symbology:?}");
5605        }
5606        // the modules between the points of each symbology's reads
5607        assert_eq!((UPCE.span, EAN8.span, EAN13.span), (46.5, 64.0, 92.0));
5608        // a pass that delivered the single-row UPC-E and another read: the
5609        // first leaves the outcome and is counted, the second stays
5610        let flat = upce(140, 70..71);
5611        let mut outcome = engine::decode_filtered(&flat, engine::FormatFilter::All);
5612        assert_eq!(outcome.detections.len(), 1);
5613        let mut kept = outcome.detections[0].clone();
5614        kept.symbology = Symbology::Code128;
5615        outcome.detections.push(kept);
5616        let cancel = CancelToken::new();
5617        let run = Run::new(
5618            &cancel,
5619            None,
5620            (flat.width(), flat.height()),
5621            Seed::default(),
5622        );
5623        assert_eq!(run.hold_to_second_line(&flat, &mut outcome), 1);
5624        assert_eq!(outcome.detections.len(), 1);
5625        assert_eq!(outcome.detections[0].symbology, Symbology::Code128);
5626        // a read that has its second line is not counted out
5627        let tall = upce(140, 20..120);
5628        let mut outcome = engine::decode_filtered(&tall, engine::FormatFilter::All);
5629        assert_eq!(run.hold_to_second_line(&tall, &mut outcome), 0);
5630        assert_eq!(outcome.detections.len(), 1);
5631    }
5632
5633    #[test]
5634    #[cfg(feature = "engine-rxing")]
5635    fn a_stage_counts_a_read_its_second_line_refused_and_confirms_nothing_for_it() {
5636        // the single-row UPC-E, read on the stage's plane: counted in the
5637        // trace, never collected, and no confirmation decode is spent on it
5638        let flat = upce(140, 70..71);
5639        let cancel = CancelToken::new();
5640        let mut run = Run::new(
5641            &cancel,
5642            None,
5643            (flat.width(), flat.height()),
5644            Seed::default(),
5645        );
5646        let mut stages = Vec::new();
5647        let attempts = vec![Attempt::plain(|| flat.clone())];
5648        run.stage("direct", attempts, engine::FormatFilter::All, &mut stages)
5649            .unwrap();
5650        assert_eq!(stages[0].detections_found, 1);
5651        assert_eq!(run.confirmations.len(), 0);
5652        assert!(!run.store.settled());
5653        assert!(!run.store.confirmed(Symbology::UpcE, b"01234565"));
5654        // with its bars, the same stage collects it and confirms it
5655        let tall = upce(140, 20..120);
5656        let mut run = Run::new(
5657            &cancel,
5658            None,
5659            (tall.width(), tall.height()),
5660            Seed::default(),
5661        );
5662        let mut stages = Vec::new();
5663        let attempts = vec![Attempt::plain(|| tall.clone())];
5664        run.stage("direct", attempts, engine::FormatFilter::All, &mut stages)
5665            .unwrap();
5666        assert_eq!(stages[0].detections_found, 1);
5667        assert_eq!(run.confirmations.len(), 1);
5668        assert!(run.store.confirmed(Symbology::UpcE, b"01234565"));
5669        assert!(run.store.settled());
5670    }
5671
5672    #[test]
5673    #[cfg(feature = "engine-rxing")]
5674    fn a_upce_read_with_its_add_on_keeps_its_second_line() {
5675        // rxing appends the two points of a five-digit add-on to the
5676        // symbol's own: four points, no scan line by their count. The
5677        // symbol's line is the first two, and the bands beside it stop
5678        // before the add-on: they read the symbol's digits
5679        let modules = format!("{UPCE_01234565}000000000{ADD_ON_12345}");
5680        let tall = barred(&modules, 140, 20..120);
5681        let reads = upce_reads(&tall);
5682        assert_eq!(reads.len(), 1);
5683        assert_eq!(reads[0].raw, b"01234565");
5684        assert_eq!(reads[0].footprint.kind, Kind::Partial);
5685        assert_eq!(reads[0].footprint.points.len(), 4);
5686        assert!(reads_on_a_second_line(&tall, &reads[0], &|| false, &mut 0));
5687        // on a single row it has none, add-on or not
5688        let flat = barred(&modules, 140, 70..71);
5689        let reads = upce_reads(&flat);
5690        assert_eq!(reads.len(), 1);
5691        assert_eq!(reads[0].footprint.points.len(), 4);
5692        assert!(!reads_on_a_second_line(&flat, &reads[0], &|| false, &mut 0));
5693        // one point is no line
5694        let mut pointed = upce_reads(&tall).remove(0);
5695        pointed.footprint.points.truncate(1);
5696        assert!(!reads_on_a_second_line(&tall, &pointed, &|| false, &mut 0));
5697    }
5698
5699    #[test]
5700    fn a_line_past_the_plane_has_no_second_line() {
5701        // both points past the last column: the plane holds nothing along
5702        // the line
5703        let plane = addressed(100, 30);
5704        let line = ScanLine::through(at(300.0, 10.5), at(393.0, 10.5), UPCE).unwrap();
5705        assert_eq!(line.beside(&plane, true), None);
5706        assert_eq!(line.beside(&plane, false), None);
5707        assert_eq!(line.turned(&plane, 0.125), None);
5708    }
5709
5710    #[test]
5711    fn a_turned_line_rises_about_the_middle_of_its_points_a_module_deep_either_way() {
5712        // points 93 px apart on row 50: a module of 2 px, the middle at
5713        // column 86.5, the columns 12 to 160 of the bands. Five lines, from
5714        // two rows above the turned one to two below it, an eighth of a
5715        // pixel across per pixel along
5716        let plane = addressed(200, 100);
5717        let line = ScanLine::through(at(40.0, 50.5), at(133.0, 50.5), UPCE).unwrap();
5718        for (turn, way) in [(0.125f32, 1i64), (-0.125, -1)] {
5719            let band = line.turned(&plane, turn).unwrap();
5720            assert_eq!((band.width(), band.height()), (149, 5));
5721            for (x, y) in (0..149u32).flat_map(|x| (0..5u32).map(move |y| (x, y))) {
5722                // eighths of the distance to the middle, rounded away from it
5723                let along = i64::from(x) - 74;
5724                let rise = way * along.signum() * ((along.abs() + 4) / 8);
5725                let row = u32::try_from(48 + i64::from(y) + rise).unwrap();
5726                assert_eq!(
5727                    pixel(&band, x, y),
5728                    pixel(&plane, 12 + x, row),
5729                    "{turn} {x} {y}"
5730                );
5731            }
5732        }
5733        // the middle line of the five: nine rows up at its first column,
5734        // on the row at its middle, nine rows down at its last
5735        let down = line.turned(&plane, 0.125).unwrap();
5736        assert_eq!(pixel(&down, 0, 2), pixel(&plane, 12, 41));
5737        assert_eq!(pixel(&down, 74, 2), pixel(&plane, 86, 50));
5738        assert_eq!(pixel(&down, 148, 2), pixel(&plane, 160, 59));
5739        assert_eq!(pixel(&down, 74, 0), pixel(&plane, 86, 48));
5740        assert_eq!(pixel(&down, 74, 4), pixel(&plane, 86, 52));
5741        let up = line.turned(&plane, -0.125).unwrap();
5742        assert_eq!(pixel(&up, 0, 2), pixel(&plane, 12, 59));
5743        assert_eq!(pixel(&up, 148, 2), pixel(&plane, 160, 41));
5744    }
5745
5746    #[test]
5747    fn a_turned_column_leans_about_the_middle_of_its_points() {
5748        let plane = addressed(100, 200);
5749        let line = ScanLine::through(at(50.5, 40.0), at(50.5, 133.0), UPCE).unwrap();
5750        for (turn, way) in [(0.125f32, 1i64), (-0.125, -1)] {
5751            let band = line.turned(&plane, turn).unwrap();
5752            assert_eq!((band.width(), band.height()), (5, 149));
5753            for (x, y) in (0..5u32).flat_map(|x| (0..149u32).map(move |y| (x, y))) {
5754                let along = i64::from(y) - 74;
5755                let lean = way * along.signum() * ((along.abs() + 4) / 8);
5756                let column = u32::try_from(48 + i64::from(x) + lean).unwrap();
5757                assert_eq!(
5758                    pixel(&band, x, y),
5759                    pixel(&plane, column, 12 + y),
5760                    "{turn} {x} {y}"
5761                );
5762            }
5763        }
5764    }
5765
5766    #[test]
5767    fn a_turned_line_is_a_module_deep_on_either_side() {
5768        // points 186 px apart: a module of 4 px, nine lines. Points 20 px
5769        // apart: a module counted as one pixel, three lines
5770        let plane = addressed(300, 60);
5771        let line = ScanLine::through(at(57.0, 30.5), at(243.0, 30.5), UPCE).unwrap();
5772        let band = line.turned(&plane, 0.125).unwrap();
5773        assert_eq!((band.width(), band.height()), (298, 9));
5774        let line = ScanLine::through(at(140.0, 30.5), at(160.0, 30.5), UPCE).unwrap();
5775        let band = line.turned(&plane, 0.125).unwrap();
5776        assert_eq!((band.width(), band.height()), (48, 3));
5777        // the same down a column
5778        let plane = addressed(60, 300);
5779        let line = ScanLine::through(at(30.5, 57.0), at(30.5, 243.0), UPCE).unwrap();
5780        let band = line.turned(&plane, 0.125).unwrap();
5781        assert_eq!((band.width(), band.height()), (9, 298));
5782        let line = ScanLine::through(at(30.5, 140.0), at(30.5, 160.0), UPCE).unwrap();
5783        let band = line.turned(&plane, 0.125).unwrap();
5784        assert_eq!((band.width(), band.height()), (3, 48));
5785    }
5786
5787    #[test]
5788    fn a_turned_line_reads_the_edge_of_the_plane_where_it_leaves_it() {
5789        // row 5 of twelve: nine rows up at the first column of the line and
5790        // nine down at its last, both past the plane
5791        let plane = addressed(200, 12);
5792        let line = ScanLine::through(at(40.0, 5.5), at(133.0, 5.5), UPCE).unwrap();
5793        let band = line.turned(&plane, 0.125).unwrap();
5794        assert_eq!((band.width(), band.height()), (149, 5));
5795        for y in 0..5 {
5796            assert_eq!(pixel(&band, 0, y), pixel(&plane, 12, 0), "{y}");
5797            assert_eq!(pixel(&band, 148, y), pixel(&plane, 160, 11), "{y}");
5798        }
5799    }
5800
5801    /// The UPC-E symbol `01234565`, 4 px per module in a plane of 284 by
5802    /// 140, its bars cut to a strip 27 rows deep that crosses the plane
5803    /// 21 rows per 200 columns: downward to the right when `way` is 1,
5804    /// upward when it is -1.
5805    #[cfg(feature = "engine-rxing")]
5806    fn slanted(way: i64) -> LumaImage {
5807        let data = (0..140u32)
5808            .flat_map(|y| (0..284u32).map(move |x| (x, y)))
5809            .map(|(x, y)| {
5810                let centre = 70 + way * (i64::from(x) - 142) * 21 / 200;
5811                let module = x.checked_sub(40).map(|inside| (inside / 4) as usize);
5812                let bar = (i64::from(y) - centre).abs() <= 13
5813                    && module.and_then(|i| UPCE_01234565.as_bytes().get(i)) == Some(&b'1');
5814                if bar { 0 } else { 255 }
5815            })
5816            .collect();
5817        LumaImage::new(data, 284, 140)
5818    }
5819
5820    #[test]
5821    #[cfg(feature = "engine-rxing")]
5822    fn bars_that_hold_no_line_beside_the_first_hold_it_turned_their_way() {
5823        for (way, turn) in [(1, SECOND_LINE_TURN), (-1, -SECOND_LINE_TURN)] {
5824            // five rows cross every bar of the strip, and no row three
5825            // modules from one of them does
5826            let plane = slanted(way);
5827            let reads = upce_reads(&plane);
5828            assert!(!reads.is_empty(), "{way}");
5829            for read in &reads {
5830                assert_eq!(read.raw, b"01234565");
5831                let [a, b] = read.footprint.points[..] else {
5832                    panic!("a scan line has two points");
5833                };
5834                let line = ScanLine::through(a, b, UPCE).unwrap();
5835                let holds = |band: Option<LumaImage>| {
5836                    upce_reads(&band.unwrap())
5837                        .iter()
5838                        .any(|again| again.raw == read.raw)
5839                };
5840                assert!(!holds(line.beside(&plane, true)), "{way}");
5841                assert!(!holds(line.beside(&plane, false)), "{way}");
5842                // the line turned the strip's way reads it, the other does
5843                // not
5844                assert!(holds(line.turned(&plane, turn)), "{way}");
5845                assert!(!holds(line.turned(&plane, -turn)), "{way}");
5846                assert!(reads_on_a_second_line(&plane, read, &|| false, &mut 0));
5847            }
5848        }
5849    }
5850
5851    #[test]
5852    #[cfg(feature = "engine-rxing")]
5853    fn the_first_line_that_reads_ends_the_search_and_a_cancelled_walk_looks_for_none() {
5854        // the question is asked before each line: once when the first band
5855        // reads, four times when no line does
5856        let asked = std::cell::Cell::new(0u32);
5857        let ask = || {
5858            asked.set(asked.get() + 1);
5859            false
5860        };
5861        let tall = upce(140, 20..120);
5862        let reads = upce_reads(&tall);
5863        assert!(reads_on_a_second_line(&tall, &reads[0], &ask, &mut 0));
5864        assert_eq!(asked.replace(0), 1);
5865        let flat = upce(140, 70..71);
5866        let single = upce_reads(&flat);
5867        assert!(!reads_on_a_second_line(&flat, &single[0], &ask, &mut 0));
5868        assert_eq!(asked.replace(0), 4);
5869        // cancelled: no line is looked for, and the read is not kept
5870        assert!(!reads_on_a_second_line(&tall, &reads[0], &|| true, &mut 0));
5871        let cancel = CancelToken::new();
5872        cancel.cancel();
5873        let run = Run::new(
5874            &cancel,
5875            None,
5876            (tall.width(), tall.height()),
5877            Seed::default(),
5878        );
5879        let mut outcome = engine::decode_filtered(&tall, engine::FormatFilter::All);
5880        assert_eq!(outcome.detections.len(), 1);
5881        assert_eq!(run.hold_to_second_line(&tall, &mut outcome), 1);
5882        assert_eq!(outcome.detections.len(), 0);
5883    }
5884
5885    #[test]
5886    #[cfg(feature = "engine-rxing")]
5887    fn a_pass_kept_for_the_plane_keeps_what_its_second_lines_left_and_their_count() {
5888        // the single-row UPC-E on the walk's working plane: the pass is made
5889        // once, its read refused once, and the pass an attempt reuses says
5890        // the same as the first
5891        let flat = upce(140, 70..71);
5892        let cancel = CancelToken::new();
5893        let mut run = Run::new(
5894            &cancel,
5895            None,
5896            (flat.width(), flat.height()),
5897            Seed::default(),
5898        );
5899        run.plane = Some(&flat);
5900        let before = ENGINE_PASSES.with(std::cell::Cell::get);
5901        let (first, refused) = run.engine_pass(&flat, engine::FormatFilter::All);
5902        assert_eq!((first.detections.len(), refused), (0, 1));
5903        assert_eq!(run.plane_passes.len(), 1);
5904        assert_eq!(run.plane_passes[0].1.detections.len(), 0);
5905        assert_eq!(run.plane_passes[0].2, 1);
5906        let (again, refused) = run.engine_pass(&flat, engine::FormatFilter::All);
5907        assert_eq!((again.detections.len(), refused), (0, 1));
5908        assert_eq!(ENGINE_PASSES.with(std::cell::Cell::get), before + 1);
5909        // an image that is not the plane is read for itself, and kept for
5910        // no one
5911        let tall = upce(140, 20..120);
5912        let (other, refused) = run.engine_pass(&tall, engine::FormatFilter::All);
5913        assert_eq!((other.detections.len(), refused), (1, 0));
5914        assert_eq!(run.plane_passes.len(), 1);
5915    }
5916}
5917
5918#[cfg(all(test, feature = "engine-rxing"))]
5919mod qr_codes_alone {
5920    //! An attempt runs the rxing passes that read no QR-family symbol only
5921    //! where something else than QR-family symbols can be read
5922    //! ([`Run::decode`]): outside the QR Codes known in it, a plane of one
5923    //! value holds nothing.
5924    #![allow(clippy::unwrap_used, clippy::expect_used)]
5925
5926    use super::*;
5927    use crate::input::{ImageInput, Limits};
5928    use crate::transform::normalize;
5929    use engine::FormatFilter as F;
5930    use engine::RxingPass::{Whole, WithoutExpanded};
5931    use pretty_assertions::assert_eq;
5932
5933    fn point(x: f32, y: f32) -> Point {
5934        Point { x, y }
5935    }
5936
5937    /// A `width` x `height` plane of `value`, the listed pixels at 0.
5938    fn plane(width: u32, height: u32, value: u8, dark: &[(u32, u32)]) -> LumaImage {
5939        let mut data = vec![value; (width * height) as usize];
5940        for &(x, y) in dark {
5941            data[(y * width + x) as usize] = 0;
5942        }
5943        LumaImage::new(data, width, height)
5944    }
5945
5946    /// The square from (10, 10) to (30, 30).
5947    fn square() -> [Point; 4] {
5948        [
5949            point(10.0, 10.0),
5950            point(30.0, 10.0),
5951            point(30.0, 30.0),
5952            point(10.0, 30.0),
5953        ]
5954    }
5955
5956    #[test]
5957    fn a_region_reaches_its_distance_past_each_side_and_no_farther() {
5958        let square = square();
5959        let reversed = [square[3], square[2], square[1], square[0]];
5960        for quad in [square, reversed] {
5961            // grown by 1.5: a pixel centre exactly that far out is inside,
5962            // the corners grow square
5963            let holds = |x, y| flat_outside(&plane(40, 40, 255, &[(x, y)]), &[(quad, 1.5)]);
5964            for (x, y) in [
5965                (20, 20),
5966                (10, 10),
5967                (31, 20),
5968                (8, 20),
5969                (20, 8),
5970                (20, 31),
5971                (31, 31),
5972                (8, 8),
5973            ] {
5974                assert!(holds(x, y), "({x}, {y}) is inside {quad:?}");
5975            }
5976            for (x, y) in [
5977                (32, 20),
5978                (7, 20),
5979                (20, 7),
5980                (20, 32),
5981                (0, 0),
5982                (39, 39),
5983                (39, 20),
5984                (20, 0),
5985            ] {
5986                assert!(!holds(x, y), "({x}, {y}) is outside {quad:?}");
5987            }
5988        }
5989    }
5990
5991    #[test]
5992    fn a_turned_region_holds_the_pixels_of_its_own_shape() {
5993        let diamond = [
5994            point(20.0, 4.0),
5995            point(36.0, 20.0),
5996            point(20.0, 36.0),
5997            point(4.0, 20.0),
5998        ];
5999        let holds = |x, y, grown| flat_outside(&plane(40, 40, 255, &[(x, y)]), &[(diamond, grown)]);
6000        // the centre and a pixel by each corner
6001        for (x, y) in [(20, 20), (20, 5), (34, 19), (19, 34), (5, 20)] {
6002            assert!(holds(x, y, 0.0), "({x}, {y}) is inside");
6003        }
6004        // the corners of its bounding box
6005        for (x, y) in [(5, 5), (34, 5), (34, 34), (5, 34)] {
6006            assert!(!holds(x, y, 0.0), "({x}, {y}) is outside");
6007        }
6008        // the centre of (5, 5) is 13 / √2 ≈ 9.19 px out of its nearest side
6009        assert!(holds(5, 5, 9.5));
6010        assert!(!holds(5, 5, 9.0));
6011    }
6012
6013    #[test]
6014    fn a_plane_is_flat_outside_its_regions_when_the_pixels_left_have_one_value() {
6015        // no region: the whole plane, whatever its one value
6016        assert!(flat_outside(&plane(16, 9, 255, &[]), &[]));
6017        assert!(flat_outside(&plane(16, 9, 7, &[]), &[]));
6018        for pixel in [(0, 0), (15, 0), (0, 8), (15, 8), (7, 4)] {
6019            assert!(!flat_outside(&plane(16, 9, 7, &[pixel]), &[]), "{pixel:?}");
6020        }
6021        // a region over the whole plane leaves no pixel to compare
6022        let noise: Vec<u8> = (0..16u32 * 9)
6023            .map(|i| u8::try_from(i * 37 % 256).unwrap())
6024            .collect();
6025        let everything = [
6026            point(-1.0, -1.0),
6027            point(17.0, -1.0),
6028            point(17.0, 10.0),
6029            point(-1.0, 10.0),
6030        ];
6031        assert!(flat_outside(
6032            &LumaImage::new(noise, 16, 9),
6033            &[(everything, 0.0)]
6034        ));
6035        // two regions apart, in either order, and a third over both
6036        let left = [
6037            point(2.0, 2.0),
6038            point(6.0, 2.0),
6039            point(6.0, 7.0),
6040            point(2.0, 7.0),
6041        ];
6042        let right = [
6043            point(9.0, 2.0),
6044            point(13.0, 2.0),
6045            point(13.0, 7.0),
6046            point(9.0, 7.0),
6047        ];
6048        let over = [
6049            point(4.0, 2.0),
6050            point(11.0, 2.0),
6051            point(11.0, 7.0),
6052            point(4.0, 7.0),
6053        ];
6054        let inside = plane(16, 9, 255, &[(3, 3), (10, 5), (12, 6)]);
6055        assert!(flat_outside(&inside, &[(left, 0.0), (right, 0.0)]));
6056        assert!(flat_outside(&inside, &[(right, 0.0), (left, 0.0)]));
6057        for pixel in [(7, 4), (1, 4), (0, 4), (14, 4), (15, 4), (3, 8), (3, 1)] {
6058            let one = plane(16, 9, 255, &[pixel]);
6059            assert!(
6060                !flat_outside(&one, &[(left, 0.0), (right, 0.0)]),
6061                "{pixel:?}"
6062            );
6063        }
6064        let regions = [(left, 0.0), (over, 0.0), (right, 0.0)];
6065        assert!(flat_outside(
6066            &plane(16, 9, 255, &[(5, 3), (8, 4)]),
6067            &regions
6068        ));
6069        assert!(!flat_outside(&plane(16, 9, 255, &[(14, 4)]), &regions));
6070    }
6071
6072    #[test]
6073    fn a_region_that_is_no_convex_quad_of_finite_points_holds_no_pixel() {
6074        let dark = plane(40, 40, 255, &[(14, 25)]);
6075        let square = square();
6076        assert!(flat_outside(&dark, &[(square, 0.0)]));
6077        let bowtie = [square[0], square[2], square[1], square[3]];
6078        // three points on one line, or one point twice
6079        let triangle = [square[0], point(10.0, 20.0), square[3], square[2]];
6080        let repeated = [square[0], square[0], square[2], square[3]];
6081        let infinite = [square[0], square[1], point(f32::INFINITY, 30.0), square[3]];
6082        let unknown = [square[0], square[1], point(f32::NAN, 30.0), square[3]];
6083        for quad in [bowtie, triangle, repeated, infinite, unknown] {
6084            assert!(!flat_outside(&dark, &[(quad, 0.0)]), "{quad:?}");
6085        }
6086        for grown in [f32::NAN, f32::INFINITY, f32::NEG_INFINITY] {
6087            assert!(!flat_outside(&dark, &[(square, grown)]), "{grown}");
6088        }
6089    }
6090
6091    #[test]
6092    fn a_symbol_is_grown_by_the_mean_side_of_its_grid_over_its_modules() {
6093        let close = |a: f32, b: f32| (a - b).abs() < 1e-4;
6094        let square = [
6095            point(0.0, 0.0),
6096            point(290.0, 0.0),
6097            point(290.0, 290.0),
6098            point(0.0, 290.0),
6099        ];
6100        // rqrr's frame, one module of 10 px past the last row and column
6101        let frame = [
6102            point(0.0, 0.0),
6103            point(300.0, 0.0),
6104            point(300.0, 300.0),
6105            point(0.0, 300.0),
6106        ];
6107        let measured = |outer, modules| engine::MatrixRegion {
6108            corners: frame,
6109            grid: Some(engine::Grid { outer, modules }),
6110        };
6111        let (corners, grown_by) = grown(measured(square, 29));
6112        assert_eq!(corners, square);
6113        assert!(close(grown_by, 10.0));
6114        // no grid measured: the region's corners, over the most modules a
6115        // QR-family symbol has
6116        let outline = engine::MatrixRegion {
6117            corners: square,
6118            grid: None,
6119        };
6120        let (corners, grown_by) = grown(outline);
6121        assert_eq!(corners, square);
6122        assert!(close(grown_by, 290.0 / 177.0));
6123        let oblong = [
6124            point(0.0, 0.0),
6125            point(290.0, 0.0),
6126            point(290.0, 145.0),
6127            point(0.0, 145.0),
6128        ];
6129        assert!(close(grown(measured(oblong, 29)).1, 7.5));
6130        // four sides of 500 px, turned
6131        let turned = [
6132            point(0.0, 0.0),
6133            point(300.0, 400.0),
6134            point(-100.0, 700.0),
6135            point(-400.0, 300.0),
6136        ];
6137        assert!(close(grown(measured(turned, 177)).1, 500.0 / 177.0));
6138        assert!(close(grown(measured(turned, 25)).1, 20.0));
6139        assert!(close(mean_side(turned), 500.0));
6140    }
6141
6142    #[test]
6143    fn only_the_passes_that_read_no_qr_family_symbol_are_left_out() {
6144        let qr = engine::Formats::of(&[Symbology::QrCode]);
6145        let both = engine::Formats::of(&[Symbology::QrCode, Symbology::Ean13]);
6146        let expanded = engine::Formats::of(&[Symbology::QrCode, Symbology::DataBarExpanded]);
6147        let micro = engine::Formats::of(&[Symbology::MicroQrCode, Symbology::DataBarExpanded]);
6148        let linear = engine::Formats::of(&[Symbology::Ean13]);
6149        let linears = engine::Formats::of(&[Symbology::Ean13, Symbology::DataBarExpanded]);
6150        // the DataBar Expanded reader's own pass, where a QR-family reader
6151        // runs; every pass, where none does
6152        assert_eq!(narrowed(F::All), Some(Some(WithoutExpanded(F::All))));
6153        for set in [expanded, micro] {
6154            assert_eq!(
6155                narrowed(F::Set(set)),
6156                Some(Some(WithoutExpanded(F::Set(set))))
6157            );
6158        }
6159        assert_eq!(narrowed(F::NonQr), Some(None));
6160        assert_eq!(narrowed(F::Set(linear)), Some(None));
6161        assert_eq!(narrowed(F::Set(linears)), Some(None));
6162        // nothing to leave out: the pass reads QR-family symbols and no
6163        // DataBar Expanded, or one symbology, or nothing at all
6164        for filter in [
6165            F::Set(both),
6166            F::QrFamily,
6167            F::Set(qr),
6168            F::Set(engine::Formats::of(&[])),
6169            F::Only(Symbology::QrCode),
6170            F::Only(Symbology::Ean13),
6171            F::Only(Symbology::DataBarExpanded),
6172        ] {
6173            assert_eq!(narrowed(filter), None, "{filter:?}");
6174        }
6175    }
6176
6177    /// A QR Code of `url`, `scale` px a module, four modules of margin.
6178    fn qr_code(url: &str, scale: u32) -> LumaImage {
6179        let code = qrcode::QrCode::with_error_correction_level(url, qrcode::EcLevel::M).unwrap();
6180        let img = code
6181            .render::<image::Luma<u8>>()
6182            .module_dimensions(scale, scale)
6183            .build();
6184        let dims = (img.width(), img.height());
6185        LumaImage::new(img.into_raw(), dims.0, dims.1)
6186    }
6187
6188    /// The rxing passes `work` runs on this thread, and what it returns.
6189    fn rxing_passes<T>(work: impl FnOnce() -> T) -> (Vec<engine::RxingPass>, T) {
6190        engine::RXING_PASSES.with(|passes| passes.replace(Some(Vec::new())));
6191        let value = work();
6192        let passes = engine::RXING_PASSES.with(|passes| passes.replace(None));
6193        (passes.unwrap(), value)
6194    }
6195
6196    /// An unbounded walk of `luma` for `formats`: its rxing passes, what it
6197    /// publishes and the stages it ran.
6198    fn walked(
6199        luma: &LumaImage,
6200        formats: &[Symbology],
6201    ) -> (
6202        Vec<engine::RxingPass>,
6203        Vec<(Symbology, String)>,
6204        Vec<String>,
6205    ) {
6206        let input = ImageInput::luma8(luma.data(), luma.width(), luma.height());
6207        let planes = normalize(&input, &Limits::default()).unwrap();
6208        let mut config = ScanConfig::full();
6209        config.budget_ms = None;
6210        config.formats = formats.to_vec();
6211        let (passes, outcome) =
6212            rxing_passes(|| run(&planes, &config, &CancelToken::new(), None).unwrap());
6213        let published = outcome
6214            .merged
6215            .iter()
6216            .map(|d| (d.symbology, d.text.clone()))
6217            .collect();
6218        let stages = outcome
6219            .trace
6220            .stages
6221            .iter()
6222            .map(|s| s.stage.clone())
6223            .collect();
6224        (passes, published, stages)
6225    }
6226
6227    #[test]
6228    fn a_qr_code_on_a_plain_background_leaves_out_what_reads_no_qr_code() {
6229        let url = "https://qrcode-ai.com/qr-codes-alone";
6230        let luma = qr_code(url, 20);
6231        assert!(luma.width() > 512, "the pyramid runs");
6232        let (passes, published, stages) = walked(&luma, &[]);
6233        // the pyramid's pass leaves out the DataBar Expanded reader's own
6234        // pass, and the completion of the other families outside the QR
6235        // Code finds one value there: no pass
6236        assert_eq!(passes, [WithoutExpanded(F::All)]);
6237        assert_eq!(published, [(Symbology::QrCode, url.to_owned())]);
6238        assert_eq!(stages, ["pyramid", "direct"]);
6239        // what a scan for QR Code alone reads, and stops at
6240        let qr = engine::Formats::of(&[Symbology::QrCode]);
6241        let (passes, alone, stages) = walked(&luma, &[Symbology::QrCode]);
6242        assert_eq!(passes, [Whole(F::Set(qr))]);
6243        assert_eq!(alone, published);
6244        assert_eq!(stages, ["pyramid"]);
6245        // a list of QR Code and EAN-13 reads both at the pyramid, nothing
6246        // to leave out there; its completion for EAN-13 finds one value
6247        let both = engine::Formats::of(&[Symbology::QrCode, Symbology::Ean13]);
6248        let (passes, listed, stages) = walked(&luma, &[Symbology::QrCode, Symbology::Ean13]);
6249        assert_eq!(passes, [Whole(F::Set(both))]);
6250        assert_eq!(listed, published);
6251        assert_eq!(stages, ["pyramid", "direct"]);
6252    }
6253
6254    #[test]
6255    fn a_qr_code_with_one_other_pixel_beside_it_is_read_with_every_family() {
6256        let url = "https://qrcode-ai.com/qr-codes-alone";
6257        let mut data = qr_code(url, 20).data().to_vec();
6258        let side = qr_code(url, 20).width();
6259        // one pixel of the margin, a step darker
6260        data[(side * side - 1) as usize] = 254;
6261        let luma = LumaImage::new(data, side, side);
6262        let (passes, published, stages) = walked(&luma, &[]);
6263        assert_eq!(passes, [Whole(F::All), Whole(F::NonQr)]);
6264        assert_eq!(published, [(Symbology::QrCode, url.to_owned())]);
6265        assert_eq!(stages, ["pyramid", "direct"]);
6266    }
6267
6268    #[test]
6269    fn a_qr_code_beside_a_barcode_is_read_with_every_family() {
6270        let bytes = include_bytes!("../../../fixtures/symbology/mixed-code128-qr.png");
6271        let planes = normalize(&ImageInput::encoded(bytes), &Limits::default()).unwrap();
6272        let (passes, mut published, _) = walked(&planes.luma, &[]);
6273        assert_eq!(passes.first(), Some(&Whole(F::All)), "{passes:?}");
6274        published.sort_by(|a, b| a.1.cmp(&b.1));
6275        assert_eq!(
6276            published,
6277            [
6278                (Symbology::Code128, "STOCK-4827".to_owned()),
6279                (Symbology::QrCode, "https://qrc-ai.com/76xMa".to_owned())
6280            ]
6281        );
6282    }
6283
6284    #[test]
6285    fn a_qr_code_the_walk_admitted_leaves_out_what_reads_no_qr_code_in_a_later_attempt() {
6286        let url = "https://qrcode-ai.com/qr-codes-alone";
6287        let luma = qr_code(url, 4);
6288        let dims = (luma.width(), luma.height());
6289        let inverted = transform::invert(&luma);
6290        let cancel = CancelToken::new();
6291        let mut stages = Vec::new();
6292        // the inverted plane alone: rqrr measures no grid there, and rxing
6293        // reads every family
6294        let mut alone = Run::new(&cancel, None, dims, Seed::default());
6295        let (passes, stop) = rxing_passes(|| {
6296            alone.stage(
6297                "pin",
6298                vec![Attempt::inverting(|| inverted.clone())],
6299                F::All,
6300                &mut stages,
6301            )
6302        });
6303        assert!(!stop.unwrap());
6304        assert_eq!(passes, [Whole(F::All)]);
6305        // after the plain plane, whose QR Code the walk admitted
6306        let mut run = Run::new(&cancel, None, dims, Seed::default());
6307        let (passes, stop) = rxing_passes(|| {
6308            run.stage(
6309                "pin",
6310                vec![
6311                    Attempt::plain(|| luma.clone()),
6312                    Attempt::inverting(|| inverted.clone()),
6313                ],
6314                F::All,
6315                &mut stages,
6316            )
6317        });
6318        assert!(!stop.unwrap());
6319        assert_eq!(passes, [WithoutExpanded(F::All), WithoutExpanded(F::All)]);
6320    }
6321
6322    /// A QR Code of `version` for `url` at EC level M, `scale` px a module,
6323    /// four modules of margin, with one dark pixel at mid-height `out` px
6324    /// right of its right edge; and its modules along a side.
6325    fn qr_code_dotted(url: &str, version: i16, scale: u32, out: u32) -> (LumaImage, u32) {
6326        let code =
6327            qrcode::QrCode::with_version(url, qrcode::Version::Normal(version), qrcode::EcLevel::M)
6328                .unwrap();
6329        let img = code
6330            .render::<image::Luma<u8>>()
6331            .module_dimensions(scale, scale)
6332            .build();
6333        let (width, height) = (img.width(), img.height());
6334        let mut data = img.into_raw();
6335        let modules = u32::try_from(code.width()).unwrap();
6336        let edge = (4 + modules) * scale;
6337        data[((height / 2) * width + edge + out) as usize] = 0;
6338        (LumaImage::new(data, width, height), modules)
6339    }
6340
6341    #[test]
6342    fn a_dark_pixel_half_a_module_out_of_a_qr_code_leaves_out_what_reads_no_qr_code() {
6343        // version 6 at 10 px a module: 490 px, no pyramid. The pixel
6344        // centre 5.5 px out is inside the grid grown by one module (10 px);
6345        // 15.5 px out, outside it. Over 21 modules instead of the grid's 41
6346        // the growth would be 19.5 px and hold both
6347        let url = "https://qrcode-ai.com/one-module";
6348        for (out, pass) in [(5, WithoutExpanded(F::All)), (15, Whole(F::All))] {
6349            let (luma, modules) = qr_code_dotted(url, 6, 10, out);
6350            assert_eq!((luma.width(), modules), (490, 41));
6351            let (passes, published, stages) = walked(&luma, &[]);
6352            assert_eq!(passes, [pass], "{out} px out");
6353            assert_eq!(published, [(Symbology::QrCode, url.to_owned())]);
6354            assert_eq!(stages, ["direct"]);
6355        }
6356    }
6357
6358    #[test]
6359    fn a_region_the_walk_admitted_is_grown_by_one_module_of_its_own_grid() {
6360        // the plane read, then the plane inverted, where rqrr measures no
6361        // grid: only the region the walk admitted out of the first attempt
6362        // decides, grown by one module of the 41 rqrr measured — the pixel
6363        // 5.5 px out inside it, 15.5 px out outside
6364        let url = "https://qrcode-ai.com/one-module";
6365        for (out, pass) in [(5, WithoutExpanded(F::All)), (15, Whole(F::All))] {
6366            let (luma, _) = qr_code_dotted(url, 6, 10, out);
6367            let dims = (luma.width(), luma.height());
6368            let inverted = transform::invert(&luma);
6369            let cancel = CancelToken::new();
6370            let mut run = Run::new(&cancel, None, dims, Seed::default());
6371            let mut stages = Vec::new();
6372            let (passes, stop) = rxing_passes(|| {
6373                run.stage(
6374                    "pin",
6375                    vec![
6376                        Attempt::plain(|| luma.clone()),
6377                        Attempt::inverting(|| inverted.clone()),
6378                    ],
6379                    F::All,
6380                    &mut stages,
6381                )
6382            });
6383            assert!(!stop.unwrap());
6384            assert_eq!(passes, [pass, pass], "{out} px out");
6385            let modules: Vec<_> = run
6386                .store
6387                .qr_regions()
6388                .iter()
6389                .map(|region| region.grid.map(|grid| grid.modules))
6390                .collect();
6391            assert_eq!(modules, [Some(41)]);
6392        }
6393    }
6394
6395    #[test]
6396    fn a_region_rxing_alone_outlined_is_grown_by_its_side_over_177() {
6397        // a Micro QR M3, 15 modules of 6 px from x = 24 to 114: rqrr reads
6398        // no Micro QR, so the walk admits rxing's outline of it, with no
6399        // grid, and grows it by 90 / 177 px. The plane read (nothing known
6400        // yet: every pass), then the plane inverted: a pixel just past the
6401        // symbol (centre 114.5) lies inside the region, one a pixel farther
6402        // (115.5) outside; over the symbol's own 15 modules the growth would
6403        // be 6 px and hold the pixel 3 px out too
6404        let micro = crate::rescue::test_symbols::from_segments(
6405            qrcode::Version::Micro(3),
6406            qrcode::EcLevel::M,
6407            |b| b.push_byte_data(b"micro"),
6408        );
6409        for (out, pass) in [
6410            (0, WithoutExpanded(F::All)),
6411            (1, Whole(F::All)),
6412            (3, Whole(F::All)),
6413        ] {
6414            let (width, height) = (micro.width(), micro.height());
6415            let mut data = micro.data().to_vec();
6416            data[(height / 2 * width + 114 + out) as usize] = 0;
6417            let luma = LumaImage::new(data, width, height);
6418            let inverted = transform::invert(&luma);
6419            let cancel = CancelToken::new();
6420            let mut run = Run::new(&cancel, None, (width, height), Seed::default());
6421            let mut stages = Vec::new();
6422            let (passes, stop) = rxing_passes(|| {
6423                run.stage(
6424                    "pin",
6425                    vec![
6426                        Attempt::plain(|| luma.clone()),
6427                        Attempt::inverting(|| inverted.clone()),
6428                    ],
6429                    F::All,
6430                    &mut stages,
6431                )
6432            });
6433            assert!(!stop.unwrap());
6434            assert_eq!(passes, [Whole(F::All), pass], "{out} px out");
6435            let regions: Vec<_> = run
6436                .store
6437                .qr_regions()
6438                .iter()
6439                .map(|region| (region.corners[0], region.grid))
6440                .collect();
6441            assert_eq!(regions, [(Point { x: 24.5, y: 24.5 }, None)]);
6442        }
6443    }
6444
6445    #[test]
6446    fn a_dark_pixel_past_one_module_of_a_large_qr_code_lets_every_family_read() {
6447        // version 20 at 4 px a module: 97 modules, 420 px. The pixel centre
6448        // 6.5 px out is past one module (4 px); over 21 modules the growth
6449        // would be 18.5 px and leave out what reads no QR code. 2.5 px out, it
6450        // is within one module
6451        let url = "https://qrcode-ai.com/version-twenty";
6452        for (out, pass) in [(6, Whole(F::All)), (2, WithoutExpanded(F::All))] {
6453            let (luma, modules) = qr_code_dotted(url, 20, 4, out);
6454            assert_eq!((luma.width(), modules), (420, 97));
6455            let (passes, published, _) = walked(&luma, &[]);
6456            assert_eq!(passes.first(), Some(&pass), "{out} px out: {passes:?}");
6457            assert_eq!(published, [(Symbology::QrCode, url.to_owned())]);
6458        }
6459    }
6460
6461    /// The one attempt of `luma` under every format: its rxing passes, and
6462    /// the modules along a side of each grid rqrr located there, as the
6463    /// narrowing question measures them.
6464    fn one_attempt(luma: &LumaImage) -> (Vec<engine::RxingPass>, Vec<Option<u16>>) {
6465        let cancel = CancelToken::new();
6466        let run = Run::new(
6467            &cancel,
6468            None,
6469            (luma.width(), luma.height()),
6470            Seed::default(),
6471        );
6472        let (passes, outcome) = rxing_passes(|| run.decode(luma, F::All));
6473        let modules = outcome
6474            .rescue
6475            .iter()
6476            .map(|candidate| located_region(candidate).grid.map(|grid| grid.modules))
6477            .collect();
6478        (passes, modules)
6479    }
6480
6481    /// The data codewords of a version 2-M symbol and the 12 of them to
6482    /// invert: more than its 8 correctable errors.
6483    fn unreadable() -> (Vec<u8>, Vec<usize>) {
6484        let data =
6485            crate::rescue::test_symbols::stream("0100 00000011 01100001 01100010 01100011 0000");
6486        (data, (0..12).collect())
6487    }
6488
6489    #[test]
6490    fn a_grid_rqrr_locates_on_white_is_a_qr_code_known_in_the_attempt() {
6491        // a version 2 grid past its error correction: rqrr reads nothing and
6492        // locates the grid by its format information, 25 modules a side
6493        let (data, corrupt) = unreadable();
6494        // the premise: clean, the stream reads "abc", and its corrupted
6495        // codewords, distinct ones of the symbol's 44, are more than the 8
6496        // errors its 16 error correction codewords correct
6497        let clean = crate::rescue::test_symbols::from_codewords(
6498            qrcode::Version::Normal(2),
6499            qrcode::EcLevel::M,
6500            &data,
6501        );
6502        let (_, published, _) = walked(&clean, &[]);
6503        assert_eq!(published, [(Symbology::QrCode, "abc".to_owned())]);
6504        let distinct: std::collections::BTreeSet<usize> = corrupt.iter().copied().collect();
6505        assert!(distinct.len() > 8, "{corrupt:?}");
6506        assert!(distinct.iter().all(|&index| index < 44), "{corrupt:?}");
6507        let luma = crate::rescue::test_symbols::from_corrupted_codewords(
6508            qrcode::Version::Normal(2),
6509            qrcode::EcLevel::M,
6510            &data,
6511            &corrupt,
6512        );
6513        let read = engine::decode_filtered(&luma, F::All);
6514        assert_eq!(read.detections.len(), 0, "{:?}", read.detections);
6515        assert_eq!(
6516            one_attempt(&luma),
6517            (vec![WithoutExpanded(F::All)], vec![Some(25)])
6518        );
6519    }
6520
6521    #[test]
6522    fn a_grid_whose_format_information_does_not_read_is_no_qr_code_known() {
6523        // the same grid, both copies of its format information light (five
6524        // bits from any format word, past the three a reader corrects): no
6525        // grid located, nothing known, every pass runs
6526        let (data, corrupt) = unreadable();
6527        // the premise: clean, the stream reads "abc", and its corrupted
6528        // codewords, distinct ones of the symbol's 44, are more than the 8
6529        // errors its 16 error correction codewords correct
6530        let clean = crate::rescue::test_symbols::from_codewords(
6531            qrcode::Version::Normal(2),
6532            qrcode::EcLevel::M,
6533            &data,
6534        );
6535        let (_, published, _) = walked(&clean, &[]);
6536        assert_eq!(published, [(Symbology::QrCode, "abc".to_owned())]);
6537        let distinct: std::collections::BTreeSet<usize> = corrupt.iter().copied().collect();
6538        assert!(distinct.len() > 8, "{corrupt:?}");
6539        assert!(distinct.iter().all(|&index| index < 44), "{corrupt:?}");
6540        let (mut colors, width) = crate::rescue::test_symbols::codeword_colors(
6541            qrcode::Version::Normal(2),
6542            qrcode::EcLevel::M,
6543            &data,
6544            &corrupt,
6545        );
6546        let far = width - 1;
6547        let format = (0..=8)
6548            .filter(|&i| i != 6)
6549            .flat_map(|i| [(i, 8), (8, i)])
6550            .chain((0..7).map(|i| (8, far - i)))
6551            .chain((0..8).map(|i| (far - i, 8)));
6552        for (x, y) in format {
6553            colors[y * width + x] = qrcode::Color::Light;
6554        }
6555        let luma = crate::rescue::test_symbols::render(&colors, width);
6556        assert_eq!(one_attempt(&luma), (vec![Whole(F::All)], vec![]));
6557    }
6558
6559    #[test]
6560    fn a_grid_rqrr_refuses_on_white_is_a_qr_code_known_in_the_attempt() {
6561        // a 111xxxxx designator rqrr decodes and the scanner refuses
6562        let data = crate::rescue::test_symbols::stream(
6563            "0111 11100000 0100 00000011 01100001 01100010 01100011 0000",
6564        );
6565        let luma = crate::rescue::test_symbols::from_codewords(
6566            qrcode::Version::Normal(1),
6567            qrcode::EcLevel::M,
6568            &data,
6569        );
6570        let cancel = CancelToken::new();
6571        let run = Run::new(
6572            &cancel,
6573            None,
6574            (luma.width(), luma.height()),
6575            Seed::default(),
6576        );
6577        let (passes, outcome) = rxing_passes(|| run.decode(&luma, F::All));
6578        assert_eq!(passes, [WithoutExpanded(F::All)]);
6579        let modules: Vec<_> = outcome
6580            .refused
6581            .iter()
6582            .map(|refusal| refusal.grid.map(|grid| grid.modules))
6583            .collect();
6584        assert_eq!(modules, [Some(21)]);
6585    }
6586}