Skip to main content

qrcode_barcode_scanner/
lib.rs

1// The README opens the crate page, so docs.rs shows what crates.io and GitHub show. Only
2// rustdoc reads it, for the rendered page and the doctests it collects: a library build never
3// opens the file, and clippy's doc lints judge the Rust docs below, not the README's prose.
4#![cfg_attr(any(doc, doctest), doc = include_str!("../README.md"))]
5//!
6//! ## Library contract
7//!
8//! Decoding + scannability validation for artistic, AI-generated, and
9//! photo-captured QR codes — the codes that break standard scanners.
10//!
11//! Contract (the normative wire format lives in the `spec/` directory):
12//!
13//! - **No QR found is `Ok`** with empty detections — `Err` is reserved for real
14//!   faults: an option outside its domain (`QRS-006`, checked before the
15//!   input), invalid or oversized input (`QRS-001..004`) or cancellation
16//!   (`QRS-005`).
17//! - **Deterministic**: same bytes + same config + same scanner build ⇒ the
18//!   same report, bit for bit on a given platform (wall clock aside) — no
19//!   RNG anywhere. Three caveats, all bounded:
20//!   - a wall-clock budget makes the CUT point machine-dependent. A cut
21//!     report says so (`trace.budget_exhausted: true`), one that does not
22//!     is the unbounded report, and a judgment the budget cannot complete
23//!     is absent, never partial. Set `budget_ms: None` for strictly
24//!     identical reports; a cancelled scan stays `QRS-005`;
25//!   - CROSS-platform the libm transcendentals (warp kernels, gaussian
26//!     blur) may differ in the last ulp — a stress cell sitting exactly on
27//!     a knee can flip between platforms;
28//!   - rxing's PDF417 decoder (0.9.1–0.9.3) breaks codeword-confidence ties
29//!     in randomized `HashMap` order, so a PDF417 symbol near a decode
30//!     threshold can score, and a marginal one decode, differently between
31//!     runs.
32//! - **Sync by design**: async belongs to the bindings (napi/wasm), never here.
33//! - **Engine-isolated**: third-party decoder panics are caught at the engine
34//!   boundary and recorded in the trace; the ladder continues.
35
36#[cfg(not(any(feature = "engine-rxing", feature = "engine-rqrr")))]
37compile_error!(
38    "qrcode-barcode-scanner requires at least one engine feature: `engine-rxing` or `engine-rqrr`"
39);
40
41mod alpha;
42mod capabilities;
43mod engine;
44mod error;
45mod gs1;
46mod input;
47mod ladder;
48mod matrix;
49pub mod options;
50mod payload;
51mod report;
52mod rescue;
53mod score;
54mod transform;
55
56pub use capabilities::Capabilities;
57pub use error::{Result, ScanError};
58pub use gs1::Gs1Element;
59pub use input::{ImageInput, Limits};
60pub use ladder::{
61    AlphaBackground, CancelToken, ScanConfig, ScanProfile, ScoreCheck, ScoreDepth, ScorePreset,
62};
63pub use payload::Payload;
64pub use report::{
65    AlphaEnvelope, AlphaMode, AlphaPaletteProbe, AlphaPlacement, AlphaProbe, AlphaReport,
66    AxisScore, Charset, DecodedContent, Detection, EcLevel, EciSegment, EngineKind, Fnc1Position,
67    GeometryKind, Grade, Hint, Iso15415Report, IsoGrade, IsoParameter, Occurrence,
68    OccurrenceGeometry, PipelineTrace, PlateColor, Point, QrMeta, Saturation, ScanReport, Score,
69    StageTrace, StressAxis, StructuralReport, Symbology, UecGrade, UecReport, Versions,
70};
71
72/// Fuzz-only entry points — cargo-fuzz builds the whole graph with
73/// `--cfg fuzzing`; this surface does not exist in normal builds.
74#[cfg(fuzzing)]
75#[doc(hidden)]
76pub mod fuzzing {
77    /// Drive every text classifier (plain, FNC1 first, FNC1 second) —
78    /// they parse attacker-controlled decoded content and must never panic.
79    pub fn classify_text(text: &str) {
80        let _ = crate::payload::classify(text);
81        let _ = crate::payload::classify_fnc1(text);
82        let _ = crate::classify_aim_application(text);
83    }
84
85    /// Drive the shared segment parser over attacker-controlled data
86    /// codewords, then the content interpretation over what it parsed. A
87    /// rescued stream never reaches the engines, so these own the decode
88    /// and must never panic (refusal is the correct answer).
89    pub fn parse_bitstream(data: &[u8], version: u8) {
90        crate::rescue::fuzz_api::parse_bitstream(data, version);
91    }
92
93    /// Drive the errors-and-erasures RS corrector over an adversarial block,
94    /// parity count, and erasure set — must never panic (`None` on garbage).
95    pub fn correct_block(block: &mut [u8], npar: usize, erasures: &[usize]) {
96        let _ = crate::rescue::fuzz_api::correct_block(block, npar, erasures);
97    }
98}
99
100/// Reusable QR scanner — configure once, scan many. `Send + Sync`, no
101/// interior state: share one instance across threads freely.
102#[derive(Debug, Clone)]
103pub struct Scanner {
104    config: ScanConfig,
105    limits: Limits,
106}
107
108impl Scanner {
109    /// Start building a scanner.
110    #[must_use]
111    pub fn builder() -> ScannerBuilder {
112        ScannerBuilder::default()
113    }
114
115    /// Scan one input. "No QR found" is `Ok` with empty detections.
116    ///
117    /// # Errors
118    /// Only real faults: an option outside its domain (`QRS-006`, checked
119    /// before the input), invalid/oversized input (`QRS-001..004`) or
120    /// cancellation (`QRS-005`) — never "nothing found".
121    pub fn scan(&self, input: ImageInput<'_>) -> Result<ScanReport> {
122        self.scan_cancellable(input, &CancelToken::new())
123    }
124
125    /// Scan with a cooperative cancellation token (checked between decode
126    /// attempts — a running engine call is not interruptible).
127    ///
128    /// # Errors
129    /// Same contract as [`Scanner::scan`], plus `QRS-005` once `cancel` fires.
130    pub fn scan_cancellable(
131        &self,
132        input: ImageInput<'_>,
133        cancel: &CancelToken,
134    ) -> Result<ScanReport> {
135        // Options first: a configuration no scan can honour is QRS-006
136        // whatever the input, before a byte of it is decoded.
137        self.config.validate()?;
138        self.limits.validate()?;
139        let normalized =
140            transform::normalize_with(&input, &self.limits, self.config.alpha_background)?;
141        let mut planes = normalized.planes;
142        let mut alpha_context = normalized.alpha;
143        // ONE wall-clock budget for the whole scan — decode ladder AND
144        // scoring share it (attempt/cell-granular: an in-flight engine call
145        // is not interruptible, which is why engine inputs are size-capped).
146        let deadline = deadline_after(self.config.budget_ms)?;
147        let mut outcome = ladder::run(&planes, &self.config, cancel, deadline)?;
148        // Alpha `auto` retry: a zero-detection scan re-flattens over the
149        // OPPOSITE background and walks the ladder once more (within the
150        // same budget) — a mis-called content mean must never turn a
151        // decodable design into a false "no detection". Both walks stay in
152        // the trace; `fallback_used` marks a RESCUE, not an attempt. A
153        // stream the first walk refused stays refused in the second: it
154        // starts from the first walk's refusals and parsed contents.
155        let mut fallback_used = false;
156        if outcome.merged.is_empty()
157            && let Some(context) = &mut alpha_context
158            && let Some((alt_planes, alt_background)) = context.opposite_planes()
159        {
160            // the fold carries the second walk's cut into the trace
161            let alt_outcome =
162                ladder::run_seeded(&alt_planes, &self.config, cancel, deadline, outcome.seed())?;
163            if outcome.fold_fallback(alt_outcome) {
164                planes = alt_planes;
165                context.adopt_background(alt_background);
166                fallback_used = true;
167            }
168        }
169        // Score the primary (first) detection when the profile asks for it;
170        // its stress cells and envelope probes match its content (aligned
171        // with it in `contents`), never its text. Each stage runs under its
172        // own bound on the scan's deadline, which also tallies the decoder
173        // panics its decodes caught (`trace.engine_panics`).
174        // The scoring stage shares the engine panic posture: a panic in the
175        // math path degrades to "no score", never a crash (native unwind;
176        // on wasm panics trap regardless — documented limitation). A
177        // contained panic is a fault, not a cut: the judgment is absent
178        // whatever the budget, and no envelope is planned after it.
179        self.measure_margin(&planes.luma, &mut outcome);
180        let primary = outcome
181            .merged
182            .first()
183            .zip(outcome.contents.first().map(|(key, _)| key));
184        // Every planned unit the deadline prevents after the walks — the
185        // judgment's, the envelope's — leaves the report partial
186        // (`trace.budget_exhausted`); the walks' own cuts are in the trace.
187        let mut cut = false;
188        let mut probe_panics = 0u8;
189        let mut faulted = false;
190        let scored = match (primary, self.config.score_depth) {
191            (Some((detection, key)), depth @ (ScoreDepth::Reduced | ScoreDepth::Full)) => {
192                let mut bound = score::Bound::new(cancel, deadline);
193                let attempt = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
194                    score::evaluate(
195                        &planes.luma,
196                        detection,
197                        key,
198                        depth,
199                        &self.config.score_skip_axes,
200                        &self.config.score_skip_checks,
201                        &mut bound,
202                    )
203                }));
204                probe_panics = probe_panics.saturating_add(bound.panics());
205                cut |= bound.cut();
206                if let Ok(result) = attempt {
207                    result?
208                } else {
209                    faulted = true;
210                    None
211                }
212            }
213            _ => None,
214        };
215        // The placement envelope — Full depth only (the sweep is a quality-
216        // gate diagnostic), skippable through the same seam as every other
217        // report section, and not planned after a contained fault of the
218        // judgment: reported absent like any envelope not computed, it can
219        // never make that fault read as a cut. Same panic posture as
220        // scoring: the sweep shares the score module's math path, so a panic
221        // there degrades to "no envelope", never a crash out of the public
222        // API.
223        let envelope = match (&alpha_context, primary) {
224            (Some(context), Some((detection, key)))
225                if !faulted
226                    && self.config.score_depth == ScoreDepth::Full
227                    && !self
228                        .config
229                        .score_skip_checks
230                        .contains(&ScoreCheck::AlphaEnvelope) =>
231            {
232                let mut bound = score::Bound::new(cancel, deadline);
233                let attempt = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
234                    context.envelope(
235                        key,
236                        detection.symbology,
237                        &self.config.alpha_palette,
238                        &mut bound,
239                    )
240                }));
241                probe_panics = probe_panics.saturating_add(bound.panics());
242                match attempt {
243                    Ok(result) => match result? {
244                        alpha::Envelope::Measured(envelope) => Some(envelope),
245                        alpha::Envelope::Undecodable => None,
246                        alpha::Envelope::Cut => {
247                            cut = true;
248                            None
249                        }
250                    },
251                    Err(_) => None,
252                }
253            }
254            _ => None,
255        };
256        outcome.trace.engine_panics = outcome.trace.engine_panics.saturating_add(probe_panics);
257        if cut {
258            outcome.trace.budget_exhausted = Some(true);
259        }
260        let alpha_report =
261            alpha_context.map(|context| context.into_report(fallback_used, envelope));
262        Ok(build_report(outcome, scored, alpha_report))
263    }
264
265    /// Scan a batch — the generator best-of-N gate. Parallel under the
266    /// `parallel` feature (results identical to sequential by construction).
267    /// Per-input results: one `Err` does not fail the batch.
268    #[must_use]
269    pub fn scan_batch(&self, inputs: &[ImageInput<'_>]) -> Vec<Result<ScanReport>> {
270        #[cfg(feature = "parallel")]
271        {
272            use rayon::prelude::*;
273            inputs.par_iter().map(|input| self.scan(*input)).collect()
274        }
275        #[cfg(not(feature = "parallel"))]
276        {
277            inputs.iter().map(|input| self.scan(*input)).collect()
278        }
279    }
280
281    /// A scan that judges first measures the primary symbol's correction
282    /// margin where it lies in the image (`score::margin`): bounded pixel
283    /// sampling, no engine, whatever the budget — the detection states the
284    /// same format in a cut report as in the final one. Same panic posture
285    /// as the judgment: a fault leaves the detection as read.
286    fn measure_margin(&self, luma: &input::LumaImage, outcome: &mut ladder::LadderOutcome) {
287        if self.config.computes_score()
288            && let Some(detection) = outcome.merged.first_mut()
289            && let Ok(Some(measured)) =
290                std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {
291                    score::margin::remeasure(luma, detection)
292                }))
293        {
294            detection.adopt(measured);
295        }
296    }
297}
298
299impl Default for Scanner {
300    fn default() -> Self {
301        Self::builder().build()
302    }
303}
304
305/// Builder for [`Scanner`].
306#[derive(Debug, Clone, Default)]
307pub struct ScannerBuilder {
308    profile: ScanProfile,
309    limits: Limits,
310}
311
312impl ScannerBuilder {
313    /// Select a scan profile (default: [`ScanProfile::Full`]).
314    #[must_use]
315    pub fn profile(mut self, profile: ScanProfile) -> Self {
316        self.profile = profile;
317        self
318    }
319
320    /// Override anti-DoS input limits.
321    #[must_use]
322    pub fn limits(mut self, limits: Limits) -> Self {
323        self.limits = limits;
324        self
325    }
326
327    /// Build the scanner.
328    #[must_use]
329    pub fn build(self) -> Scanner {
330        Scanner {
331            config: self.profile.config(),
332            limits: self.limits,
333        }
334    }
335}
336
337/// The scan's deadline, `budget_ms` from now. Checked: a deadline the clock
338/// cannot represent is `QRS-006`, never a panic and never silently
339/// unbounded. Every admitted budget (at most [`ScanConfig::MAX_BUDGET_MS`],
340/// about 49.7 days) is representable on the supported clocks.
341fn deadline_after(budget_ms: Option<u64>) -> Result<Option<web_time::Instant>> {
342    let Some(ms) = budget_ms else {
343        return Ok(None);
344    };
345    web_time::Instant::now()
346        .checked_add(std::time::Duration::from_millis(ms))
347        .map(Some)
348        .ok_or_else(|| {
349            ScanError::invalid_option(
350                "budget_ms",
351                format!("a deadline {ms} ms from now is not representable"),
352            )
353        })
354}
355
356/// The text classifier for FNC1-in-second-position data (spec/05): an
357/// AIM-assigned application's data, never GS1 — the plain classifier
358/// without its no-FNC1 GS1 sniff (the only route to `Gs1` it has).
359fn classify_aim_application(text: &str) -> Payload {
360    match payload::classify(text) {
361        Payload::Gs1 { .. } => Payload::Text,
362        payload => payload,
363    }
364}
365
366/// FNC1-in-first-position data without a verified text reading: the
367/// element string is not parsed (spec/05).
368fn gs1_not_parsed() -> Payload {
369    Payload::Gs1 {
370        elements: Vec::new(),
371        gtin: None,
372        conformant: false,
373        issues: vec![
374            "content has no verified text reading (charset unknown): element string not parsed"
375                .to_owned(),
376        ],
377    }
378}
379
380/// What a content publishes of its account: the located designators,
381/// `[]` for a declaration that was signalled but not located, no key
382/// otherwise; and the FNC1 position when one was observed.
383fn wire_account(
384    key: &engine::content::ContentKey,
385) -> (Option<Vec<EciSegment>>, Option<Fnc1Position>) {
386    use engine::content::{EciEvidence, Fnc1};
387    let eci = match &key.eci {
388        EciEvidence::Located(marks) => Some(
389            marks
390                .iter()
391                .map(|mark| EciSegment {
392                    designator: mark.value,
393                    start: u32::try_from(mark.start).unwrap_or(u32::MAX),
394                })
395                .collect(),
396        ),
397        EciEvidence::Signalled => Some(Vec::new()),
398        EciEvidence::NoEci | EciEvidence::Unobserved => None,
399    };
400    let fnc1 = match key.fnc1 {
401        Fnc1::First => Some(Fnc1Position::First),
402        Fnc1::Second => Some(Fnc1Position::Second),
403        Fnc1::None | Fnc1::Unobserved => None,
404    };
405    (eci, fnc1)
406}
407
408/// Assemble the public report from ladder output. Each detection's content
409/// is the scanner's one reading of the reconciled content
410/// (`engine::content::read`): `raw` the original payload, `eci` and `fnc1`
411/// its observed account, `text` and `charset` per spec/01 rules 1-3. The
412/// payload is routed by FNC1 position, symbology and charset (spec/05): no
413/// structured reading is ever built from text the scanner could not read.
414fn build_report(
415    outcome: ladder::LadderOutcome,
416    scored: Option<(Score, Vec<Hint>)>,
417    alpha: Option<report::AlphaReport>,
418) -> ScanReport {
419    let (score, mut hints) = match scored {
420        Some((score, hints)) => (Some(score), hints),
421        None => (None, Vec::new()),
422    };
423    // A background-dependent envelope is generator-actionable exactly like
424    // a low-contrast finding: pin a background layer, or constrain the
425    // placement to the safe bands.
426    if let Some(a) = alpha.as_ref()
427        && let Some(envelope) = a.envelope.as_ref()
428        && envelope.placement != report::AlphaPlacement::Any
429    {
430        hints.push(Hint::AlphaBackgroundDependent {
431            placement: envelope.placement,
432        });
433        // …and the canonical remedy: an opaque plate behind the symbol —
434        // robust everywhere, transparent look preserved around it.
435        hints.push(Hint::AddBackgroundPlate {
436            color: if a.content_luma < 128 {
437                report::PlateColor::White
438            } else {
439                report::PlateColor::Black
440            },
441        });
442    }
443    let detections = outcome
444        .merged
445        .into_iter()
446        .zip(outcome.contents)
447        .map(|(m, (key, _))| {
448            let (eci, fnc1) = wire_account(&key);
449            // payload routing (spec/05): FNC1-first carriers are element
450            // strings; retail 1D symbols ARE a GTIN (AI 01 semantics); text
451            // the scanner could not read is text; FNC1-second data belongs
452            // to an AIM application; everything else goes through the text
453            // classifier
454            let payload = if m.fnc1 && m.charset.is_lossy() {
455                gs1_not_parsed()
456            } else if m.fnc1 {
457                payload::classify_fnc1(&m.text)
458            } else if m.symbology.is_retail_gtin() {
459                payload::classify_retail_gtin(&m.text, m.symbology)
460            } else if m.charset.is_lossy() {
461                Payload::Text
462            } else if fnc1 == Some(Fnc1Position::Second) {
463                classify_aim_application(&m.text)
464            } else {
465                payload::classify(&m.text)
466            };
467            Detection {
468                symbology: m.symbology,
469                content: DecodedContent {
470                    text: m.text,
471                    raw: m.raw,
472                    charset: m.charset,
473                    eci,
474                    fnc1,
475                },
476                payload,
477                corners: m.corners,
478                meta: QrMeta {
479                    version: m.version,
480                    ec_level: m.ec,
481                    mask: m.mask,
482                    modules: m.version.and_then(QrMeta::modules_per_side),
483                    inverted: m.corners.is_some().then_some(m.photometric_inverted),
484                },
485                engines: m.engines,
486                occurrences: m.occurrences.into_iter().map(wire_occurrence).collect(),
487            }
488        })
489        .collect();
490    ScanReport {
491        detections,
492        score,
493        hints,
494        alpha,
495        trace: outcome.trace,
496        versions: Versions::current(),
497    }
498}
499
500/// A validated footprint as a published occurrence.
501fn wire_occurrence(footprint: engine::occurrence::Footprint) -> report::Occurrence {
502    use engine::occurrence::Kind;
503    report::Occurrence {
504        geometry: report::OccurrenceGeometry {
505            kind: match footprint.kind {
506                Kind::Quad => report::GeometryKind::Quad,
507                Kind::Segment => report::GeometryKind::Segment,
508                Kind::Partial => report::GeometryKind::Partial,
509                Kind::Unavailable => report::GeometryKind::Unavailable,
510            },
511            points: footprint.points,
512            reader: footprint.detector,
513        },
514    }
515}
516
517#[cfg(test)]
518mod tests {
519    // The public contract is exercised via the re-exported surface; the
520    // workspace deny targets `src/`, so tests opt back into unwrap/expect.
521    #![allow(clippy::unwrap_used, clippy::expect_used)]
522
523    use super::{ImageInput, Limits, ScanConfig, ScanProfile, Scanner};
524
525    fn clean_png() -> Vec<u8> {
526        std::fs::read(concat!(
527            env!("CARGO_MANIFEST_DIR"),
528            "/../../fixtures/clean/gen_v5_q.png"
529        ))
530        .unwrap()
531    }
532
533    fn scanner(config: ScanConfig, limits: Limits) -> Scanner {
534        Scanner::builder()
535            .profile(ScanProfile::Custom(config))
536            .limits(limits)
537            .build()
538    }
539
540    #[test]
541    #[cfg(not(target_family = "wasm"))]
542    fn the_overflow_hypothesis_does_not_reproduce_on_a_native_clock() {
543        // The refuted witness, kept: `now + u64::MAX ms` IS representable on
544        // a native clock (about 1.8e16 s against i64 seconds), so the former
545        // unchecked deadline did not panic for any u64 budget here. The
546        // budget ceiling is the portable option domain, not a crash fix; the
547        // checked addition only keeps an unrepresentable deadline an error.
548        let now = std::time::Instant::now();
549        let largest = std::time::Duration::from_millis(u64::MAX);
550        assert!(now.checked_add(largest).is_some());
551    }
552
553    #[test]
554    fn the_largest_admitted_budget_is_a_representable_deadline() {
555        let max = std::time::Duration::from_millis(ScanConfig::MAX_BUDGET_MS);
556        assert!(web_time::Instant::now().checked_add(max).is_some());
557    }
558
559    #[test]
560    fn an_option_out_of_its_domain_is_qrs_006_before_the_input_is_read() {
561        // checked first: beside unreadable bytes, the option is reported
562        let fast = ScanConfig::fast;
563        let cases = [
564            (
565                "budget_ms",
566                ScanConfig {
567                    budget_ms: Some(u64::MAX),
568                    ..fast()
569                },
570                Limits::default(),
571            ),
572            (
573                "budget_ms",
574                ScanConfig {
575                    budget_ms: Some(ScanConfig::MAX_BUDGET_MS + 1),
576                    ..fast()
577                },
578                Limits::default(),
579            ),
580            (
581                "pyramid_side",
582                ScanConfig {
583                    pyramid_side: 0,
584                    ..fast()
585                },
586                Limits::default(),
587            ),
588            (
589                "max_engine_side",
590                ScanConfig {
591                    max_engine_side: 0,
592                    ..fast()
593                },
594                Limits::default(),
595            ),
596            (
597                "alpha_palette",
598                ScanConfig {
599                    alpha_palette: vec![[0, 0, 0]; ScanConfig::MAX_ALPHA_PALETTE + 1],
600                    ..fast()
601                },
602                Limits::default(),
603            ),
604            (
605                "max_dimension",
606                fast(),
607                Limits {
608                    max_dimension: 0,
609                    ..Limits::default()
610                },
611            ),
612            (
613                "max_pixels",
614                fast(),
615                Limits {
616                    max_pixels: 0,
617                    ..Limits::default()
618                },
619            ),
620        ];
621        let png = clean_png();
622        for (option, config, limits) in cases {
623            let scan = scanner(config, limits);
624            for input in [
625                ImageInput::encoded(b"not an image"),
626                ImageInput::encoded(&png),
627            ] {
628                let err = scan.scan(input).expect_err(option);
629                assert_eq!(err.code(), "QRS-006", "{option}: {err}");
630                assert!(err.to_string().contains(option), "{err}");
631            }
632        }
633    }
634
635    #[test]
636    fn the_largest_budget_and_the_smallest_sides_still_scan() {
637        let config = ScanConfig {
638            budget_ms: Some(ScanConfig::MAX_BUDGET_MS),
639            alpha_palette: vec![[0, 0, 0]; ScanConfig::MAX_ALPHA_PALETTE],
640            ..ScanConfig::fast()
641        };
642        let report = scanner(config, Limits::default())
643            .scan(ImageInput::encoded(&clean_png()))
644            .unwrap();
645        assert_eq!(report.detections.len(), 1);
646        assert_eq!(report.trace.budget_exhausted, Some(false));
647        let tiny = ScanConfig {
648            pyramid_side: 1,
649            max_engine_side: 1,
650            ..ScanConfig::fast()
651        };
652        // a 1-pixel engine side reads nothing, but it is a valid request:
653        // a final empty report, not an error and not a cut
654        let report = scanner(tiny, Limits::default())
655            .scan(ImageInput::encoded(&clean_png()))
656            .unwrap();
657        assert_eq!(report.detections.len(), 0);
658        assert_eq!(report.trace.budget_exhausted, Some(false));
659    }
660
661    #[test]
662    fn a_raw_frame_whose_byte_count_overflows_is_qrs_003() {
663        // 2^32-1 square at four bytes a pixel overflows u64: the limits
664        // allow it, the byte count cannot exist
665        let limits = Limits {
666            max_dimension: u32::MAX,
667            max_pixels: u64::MAX,
668        };
669        let err = scanner(ScanConfig::fast(), limits)
670            .scan(ImageInput::rgba8(&[0; 16], u32::MAX, u32::MAX))
671            .unwrap_err();
672        assert_eq!(err.code(), "QRS-003", "{err}");
673    }
674
675    #[test]
676    fn builder_threads_custom_limits_into_the_scan() {
677        // Traps the builder-plumbing survivor (`ScannerBuilder::limits` →
678        // Default::default(), shard-0): a builder that discarded the
679        // configured Limits would fall back to the 10_000px / 64MP defaults
680        // and wave this input straight through. Pin that BOTH limit fields
681        // are threaded from the builder into input validation.
682        let data = vec![255u8; 64 * 64];
683
684        // (a) dimension cap: 64px per side > 16px limit → QRS-002
685        let strict_dim = Scanner::builder()
686            .limits(Limits {
687                max_dimension: 16,
688                ..Limits::default()
689            })
690            .build();
691        let err = strict_dim
692            .scan(ImageInput::luma8(&data, 64, 64))
693            .expect_err("64px input must exceed the 16px builder limit");
694        assert_eq!(err.code(), "QRS-002", "dimension cap threaded from builder");
695
696        // (b) pixel cap: 4096px total > 100px limit → QRS-003
697        let strict_pixels = Scanner::builder()
698            .limits(Limits {
699                max_pixels: 100,
700                ..Limits::default()
701            })
702            .build();
703        let err = strict_pixels
704            .scan(ImageInput::luma8(&data, 64, 64))
705            .expect_err("4096px input must exceed the 100px builder limit");
706        assert_eq!(err.code(), "QRS-003", "pixel cap threaded from builder");
707
708        // Control: the SAME input sails through DEFAULT limits — proving the
709        // configured cap, not the input, is what rejected it above (so the
710        // builder genuinely threaded the value rather than defaulting it away).
711        let report = Scanner::default()
712            .scan(ImageInput::luma8(&data, 64, 64))
713            .expect("default 10_000px / 64MP limits accept a 64px plane");
714        assert!(report.detections.is_empty(), "a blank plane carries no QR");
715    }
716
717    /// A transparent v3-M symbol as RGBA: dark modules opaque black, every
718    /// other pixel fully transparent (6 px modules, 4-module margin) — the
719    /// `auto` flatten reads it over white, the Full profile scores it and
720    /// measures its placement envelope. Returns the buffer and its side.
721    fn transparent_symbol() -> (Vec<u8>, u32) {
722        let code = qrcode::QrCode::with_version(
723            b"https://qrc-ai.com/probe",
724            qrcode::Version::Normal(3),
725            qrcode::EcLevel::M,
726        )
727        .unwrap();
728        let width = code.width();
729        let side = (width + 8) * 6;
730        let mut rgba = vec![0u8; side * side * 4];
731        for (i, color) in code.to_colors().iter().enumerate() {
732            if *color == qrcode::Color::Dark {
733                let (mx, my) = (i % width + 4, i / width + 4);
734                for dy in 0..6 {
735                    for dx in 0..6 {
736                        let at = ((my * 6 + dy) * side + mx * 6 + dx) * 4;
737                        rgba[at + 3] = 255;
738                    }
739                }
740            }
741        }
742        (rgba, u32::try_from(side).unwrap())
743    }
744
745    #[cfg(feature = "engine-rxing")]
746    #[test]
747    fn decoder_panics_in_score_cells_and_envelope_probes_reach_the_trace() {
748        use crate::engine::PROBE_PANICS;
749        // the walk reads the symbol with no injected fault; the judgment's
750        // cells and the envelope's probes decode it alone, and each of their
751        // rxing passes panics — caught and tallied at the engine boundary.
752        // The cells are judged as before (rqrr still reads them): only the
753        // count is new
754        let (rgba, side) = transparent_symbol();
755        let mut config = super::ScanConfig::full();
756        config.budget_ms = None;
757        let scanner = Scanner::builder()
758            .profile(super::ScanProfile::Custom(config))
759            .build();
760        let clean = scanner.scan(ImageInput::rgba8(&rgba, side, side)).unwrap();
761        assert_eq!(clean.trace.engine_panics, 0, "no real decoder panic");
762        PROBE_PANICS.with(|injected| injected.set(Some(0)));
763        let report = scanner.scan(ImageInput::rgba8(&rgba, side, side));
764        let injected = PROBE_PANICS
765            .with(|injected| injected.replace(None))
766            .unwrap();
767        let report = report.unwrap();
768        assert!(injected > 0, "the probes decoded");
769        assert_eq!(
770            u32::from(report.trace.engine_panics),
771            injected.min(u32::from(u8::MAX)),
772            "every caught probe panic is counted once"
773        );
774        assert_eq!(
775            report.detections, clean.detections,
776            "the walk reads as without the fault: only single-symbology passes panic"
777        );
778        assert!(report.score.is_some(), "the judgment completes");
779        assert!(
780            report
781                .alpha
782                .as_ref()
783                .is_some_and(|alpha| alpha.envelope.is_some()),
784            "the envelope completes: {:?}",
785            report.alpha
786        );
787    }
788
789    #[test]
790    fn a_contained_judgment_fault_plans_no_envelope_and_cuts_nothing() {
791        use crate::score::JUDGMENT_FAULT;
792        // a judgment that faults is absent whatever the budget: no envelope
793        // is planned after it, so no unit the deadline prevents can make the
794        // report read as cut — an absent score with detections and a final
795        // trace stays a fault
796        let (rgba, side) = transparent_symbol();
797        let mut config = super::ScanConfig::full();
798        config.budget_ms = None;
799        let scanner = Scanner::builder()
800            .profile(super::ScanProfile::Custom(config))
801            .build();
802        let whole = scanner.scan(ImageInput::rgba8(&rgba, side, side)).unwrap();
803        assert!(
804            whole.score.is_some()
805                && whole
806                    .alpha
807                    .as_ref()
808                    .is_some_and(|alpha| alpha.envelope.is_some()),
809            "precondition: judged, envelope measured"
810        );
811        JUDGMENT_FAULT.with(|fault| fault.set(true));
812        let faulted = scanner.scan(ImageInput::rgba8(&rgba, side, side));
813        JUDGMENT_FAULT.with(|fault| fault.set(false));
814        let faulted = faulted.unwrap();
815        assert_eq!(faulted.detections, whole.detections);
816        assert!(faulted.score.is_none(), "the fault is contained");
817        let alpha = faulted.alpha.as_ref().expect("the alpha block stays");
818        assert!(alpha.envelope.is_none(), "no envelope after the fault");
819        assert!(faulted.hints.is_empty(), "{:?}", faulted.hints);
820        assert_eq!(faulted.trace.budget_exhausted, Some(false));
821    }
822
823    #[test]
824    fn a_background_plate_is_black_from_content_luma_128() {
825        // the plate contrasts with the content: white behind content darker
826        // than mid-grey (luma below 128), black from 128 up — the symbol's
827        // modules here are opaque grey 128
828        let (mut rgba, side) = transparent_symbol();
829        for px in rgba.as_chunks_mut::<4>().0 {
830            if px[3] == 255 {
831                px[..3].fill(128);
832            }
833        }
834        let mut config = super::ScanConfig::full();
835        config.budget_ms = None;
836        let scanner = Scanner::builder()
837            .profile(super::ScanProfile::Custom(config))
838            .build();
839        let report = scanner.scan(ImageInput::rgba8(&rgba, side, side)).unwrap();
840        let alpha = report.alpha.as_ref().expect("a transparent input");
841        assert_eq!(alpha.content_luma, 128);
842        let plates: Vec<_> = report
843            .hints
844            .iter()
845            .filter_map(|hint| match hint {
846                super::Hint::AddBackgroundPlate { color } => Some(*color),
847                _ => None,
848            })
849            .collect();
850        assert_eq!(
851            plates,
852            [super::report::PlateColor::Black],
853            "{:?} {:?}",
854            report.hints,
855            alpha.envelope
856        );
857    }
858}