qrcode_barcode_scanner/report.rs
1//! Scan report — the versioned cross-boundary contract.
2//!
3//! The serde JSON shape of [`ScanReport`] is consumed by the node/wasm
4//! bindings, the site, and future Nika workflows. It only ever evolves
5//! additively; `Versions` carries the contract markers.
6
7use crate::payload::Payload;
8
9/// Base64 wire shape for raw byte payloads — a JSON number-array would
10/// bloat the contract (one number per byte).
11#[cfg(feature = "serde")]
12mod raw_b64 {
13 use base64::Engine as _;
14 use base64::engine::general_purpose::STANDARD;
15 use serde::{Deserialize, Deserializer, Serializer};
16
17 pub fn serialize<S: Serializer>(bytes: &[u8], ser: S) -> Result<S::Ok, S::Error> {
18 ser.serialize_str(&STANDARD.encode(bytes))
19 }
20
21 pub fn deserialize<'de, D: Deserializer<'de>>(de: D) -> Result<Vec<u8>, D::Error> {
22 let s = String::deserialize(de)?;
23 STANDARD.decode(s).map_err(serde::de::Error::custom)
24 }
25}
26
27/// The wire spelling of the report's `f32` fields: the `f64` nearest to
28/// the shortest decimal that reads back as the `f32` — the number the JSON
29/// text shows for it. Bindings that convert a report through serde's data
30/// model instead of JSON text (a `serde_json::Value` turned into Python
31/// objects, a serializer straight to JavaScript values) would otherwise
32/// widen the `f32` itself — 0.612 arriving as 0.6119999885559082 — while
33/// the JSON says 0.612; with this every serializer sees the decimal the JSON
34/// shows. The JSON text keeps its digits (`serde_json` writes the same
35/// shortest decimal for both types); between 1e-6 and 1e-5, and from 1e13,
36/// it spells them in exponent form as it does for any `f64`. Reading a
37/// report back is unchanged.
38#[cfg(feature = "serde")]
39mod decimal {
40 use serde::Serializer;
41 use serde::ser::SerializeTuple as _;
42
43 /// The `f64` nearest to `value`'s shortest round-trip decimal, as
44 /// `serde_json` spells it: when two decimals of that length read back as
45 /// `value` and lie equally close to it, the one with the even last
46 /// digit (2015.65625 is 2015.6562, where `Display` writes 2015.6563). A
47 /// non-finite value and zero keep their kind.
48 pub(super) fn of(value: f32) -> f64 {
49 let shortest = value.to_string();
50 let digits: String = shortest.chars().filter(char::is_ascii_digit).collect();
51 let significant = digits.trim_start_matches('0').trim_end_matches('0').len();
52 if !value.is_finite() || significant == 0 {
53 return f64::from(value);
54 }
55 // the decimal of that many digits nearest to `value`, an exact tie
56 // rounded to even: the spelling when it reads back as `value`
57 let precision = significant - 1;
58 let even = format!("{value:.precision$e}");
59 let reads_back = even
60 .parse::<f32>()
61 .is_ok_and(|parsed| parsed.to_bits() == value.to_bits());
62 let spelled = if reads_back { even } else { shortest };
63 spelled.parse().unwrap_or(f64::from(value))
64 }
65
66 /// One `f32` field.
67 #[allow(
68 clippy::trivially_copy_pass_by_ref,
69 reason = "serde's serialize_with passes the field by reference"
70 )]
71 pub(super) fn serialize<S: Serializer>(value: &f32, ser: S) -> Result<S::Ok, S::Error> {
72 ser.serialize_f64(of(*value))
73 }
74
75 /// An array of `f32` fields, element by element, in serde's own array
76 /// shape (a tuple).
77 pub(super) fn serialize_array<S: Serializer, const N: usize>(
78 values: &[f32; N],
79 ser: S,
80 ) -> Result<S::Ok, S::Error> {
81 let mut tuple = ser.serialize_tuple(N)?;
82 for value in values {
83 tuple.serialize_element(&of(*value))?;
84 }
85 tuple.end()
86 }
87}
88
89/// A 2D point in image pixel coordinates.
90#[derive(Debug, Clone, Copy, PartialEq)]
91#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
92pub struct Point {
93 /// X coordinate (pixels, sub-pixel precision).
94 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
95 pub x: f32,
96 /// Y coordinate (pixels, sub-pixel precision).
97 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
98 pub y: f32,
99}
100
101/// The barcode symbology of a detection. QR-family entries
102/// (`QrCode` · `MicroQrCode` · `RectangularMicroQrCode`) are the only ones
103/// that can carry `QrMeta` geometry, the synthetic UEC, the ISO 15415 card
104/// and the rescue stage; every other symbology decodes content + payload
105/// classification only.
106#[derive(Debug, Clone, Copy, PartialEq, Eq)]
107#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
108#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
109#[non_exhaustive]
110pub enum Symbology {
111 /// QR Code Model 2 (ISO/IEC 18004).
112 QrCode,
113 /// Micro QR (ISO/IEC 18004 M1-M4).
114 MicroQrCode,
115 /// rMQR — Rectangular Micro QR (ISO/IEC 23941).
116 RectangularMicroQrCode,
117 /// Data Matrix ECC 200 (ISO/IEC 16022).
118 DataMatrix,
119 /// Aztec (ISO/IEC 24778).
120 Aztec,
121 /// PDF417 (ISO/IEC 15438).
122 Pdf417,
123 /// `MaxiCode` (ISO/IEC 16023).
124 MaxiCode,
125 /// EAN-13 (GTIN-13 retail).
126 Ean13,
127 /// EAN-8.
128 Ean8,
129 /// UPC-A (GTIN-12 retail).
130 UpcA,
131 /// UPC-E.
132 UpcE,
133 /// Code 128 (GS1-128 when FNC1-led).
134 Code128,
135 /// Code 39.
136 Code39,
137 /// Code 93.
138 Code93,
139 /// Codabar.
140 Codabar,
141 /// ITF — Interleaved 2 of 5 (ITF-14 when 14 digits).
142 Itf,
143 /// GS1 `DataBar` (RSS-14).
144 DataBar,
145 /// GS1 `DataBar` Expanded.
146 DataBarExpanded,
147 /// Telepen.
148 Telepen,
149}
150
151impl Symbology {
152 /// Every symbology, in declaration order — the order of
153 /// `trace.formats`.
154 pub const ALL: [Self; 19] = [
155 Self::QrCode,
156 Self::MicroQrCode,
157 Self::RectangularMicroQrCode,
158 Self::DataMatrix,
159 Self::Aztec,
160 Self::Pdf417,
161 Self::MaxiCode,
162 Self::Ean13,
163 Self::Ean8,
164 Self::UpcA,
165 Self::UpcE,
166 Self::Code128,
167 Self::Code39,
168 Self::Code93,
169 Self::Codabar,
170 Self::Itf,
171 Self::DataBar,
172 Self::DataBarExpanded,
173 Self::Telepen,
174 ];
175
176 /// The wire name of the symbology (`qr_code`, `ean13`, … — the
177 /// spelling of `detections[].symbology`).
178 #[must_use]
179 pub fn name(self) -> &'static str {
180 match self {
181 Self::QrCode => "qr_code",
182 Self::MicroQrCode => "micro_qr_code",
183 Self::RectangularMicroQrCode => "rectangular_micro_qr_code",
184 Self::DataMatrix => "data_matrix",
185 Self::Aztec => "aztec",
186 Self::Pdf417 => "pdf417",
187 Self::MaxiCode => "maxi_code",
188 Self::Ean13 => "ean13",
189 Self::Ean8 => "ean8",
190 Self::UpcA => "upc_a",
191 Self::UpcE => "upc_e",
192 Self::Code128 => "code128",
193 Self::Code39 => "code39",
194 Self::Code93 => "code93",
195 Self::Codabar => "codabar",
196 Self::Itf => "itf",
197 Self::DataBar => "data_bar",
198 Self::DataBarExpanded => "data_bar_expanded",
199 Self::Telepen => "telepen",
200 }
201 }
202
203 /// Parse the wire name of a symbology ([`Symbology::name`]). `None` on
204 /// anything else, so bindings fail LOUD on a typo — the same shape as
205 /// [`StressAxis::from_name`].
206 #[must_use]
207 pub fn from_name(name: &str) -> Option<Self> {
208 Self::ALL
209 .into_iter()
210 .find(|symbology| symbology.name() == name)
211 }
212
213 /// QR family — the symbologies whose geometry/meta/UEC paths exist.
214 #[must_use]
215 pub fn is_qr_family(self) -> bool {
216 matches!(
217 self,
218 Self::QrCode | Self::MicroQrCode | Self::RectangularMicroQrCode
219 )
220 }
221
222 /// Retail GTIN carriers — the symbol's data IS a GTIN (AI 01 semantics).
223 #[must_use]
224 pub fn is_retail_gtin(self) -> bool {
225 matches!(self, Self::Ean13 | Self::Ean8 | Self::UpcA | Self::UpcE)
226 }
227
228 /// Linear symbologies — one row of bars, read along one direction. The
229 /// stacked and matrix symbologies (PDF417 included) are not.
230 pub(crate) fn is_linear(self) -> bool {
231 matches!(
232 self,
233 Self::Ean13
234 | Self::Ean8
235 | Self::UpcA
236 | Self::UpcE
237 | Self::Code128
238 | Self::Code39
239 | Self::Code93
240 | Self::Codabar
241 | Self::Itf
242 | Self::DataBar
243 | Self::DataBarExpanded
244 | Self::Telepen
245 )
246 }
247}
248
249/// Which decode engine produced a detection.
250#[derive(Debug, Clone, Copy, PartialEq, Eq)]
251#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
252#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
253#[non_exhaustive]
254pub enum EngineKind {
255 /// ZXing-family engine (rxing).
256 Rxing,
257 /// quirc-family engine (rqrr).
258 Rqrr,
259 /// The S5 erasure-rescue stage — errors-and-erasures RS over a grid
260 /// the engines detected but could not decode (Forney 1965; the
261 /// logo-occlusion recovery path).
262 Rescue,
263}
264
265/// QR error-correction level.
266#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
267#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
268#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
269#[non_exhaustive]
270pub enum EcLevel {
271 /// ~7% codeword recovery.
272 L,
273 /// ~15% codeword recovery.
274 M,
275 /// ~25% codeword recovery.
276 Q,
277 /// ~30% codeword recovery.
278 H,
279}
280
281/// How [`DecodedContent::text`] relates to [`DecodedContent::raw`] (spec/01
282/// § Content). Every value except [`Charset::Unknown`] states that `text` is
283/// a complete decoding of `raw` that the scanner checked byte for byte; it
284/// states the encoder's declared interpretation only when
285/// [`DecodedContent::eci`] lists it. `Unknown` is the only lossy value, now
286/// and in every later version: test with [`Charset::is_lossy`]. Outside the
287/// QR family `raw` is the engine's reading, which under an ECI can omit a
288/// segment the engine could not decode; the label describes `raw` as
289/// published and is not downgraded for it (spec/01 § raw).
290#[derive(Debug, Clone, Copy, PartialEq, Eq)]
291#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
292#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
293#[non_exhaustive]
294pub enum Charset {
295 /// Exactly the strict UTF-8 decoding of `raw` (ASCII included).
296 Utf8,
297 /// Exactly the WHATWG `Shift_JIS` decoding of `raw`.
298 ShiftJis,
299 /// Exactly the WHATWG windows-1252 decoding of `raw` (historical name;
300 /// not strict ISO/IEC 8859-1).
301 Latin1,
302 /// Exactly the WHATWG gb18030 decoding of `raw` (GB 2312 and GBK read
303 /// unchanged): Hanzi-mode data without a designator, or designators 29,
304 /// 31, 32.
305 Gb18030,
306 /// `raw` decoded under [`DecodedContent::eci`] (bytes before the first
307 /// designator as ISO/IEC 8859-1), when no label above states the same
308 /// reading.
309 Eci,
310 /// Not a complete decoding: each U+FFFD stands for one byte or one
311 /// maximal ill-formed sequence the scanner could not read; positions
312 /// cannot be recovered from `text` — use `raw` (and `eci`).
313 Unknown,
314 /// Reader side only: a label written by a newer scanner, still a
315 /// complete, checked decoding (show `text`, never re-decode `raw` from
316 /// it). Never produced by this crate; serializing it is an error
317 /// (forward the original JSON). Must stay the last variant.
318 #[cfg_attr(feature = "serde", serde(other, skip_serializing))]
319 Unrecognized,
320}
321
322impl Charset {
323 /// `true` only for [`Charset::Unknown`], forever.
324 #[must_use]
325 pub const fn is_lossy(self) -> bool {
326 matches!(self, Self::Unknown)
327 }
328}
329
330/// One ECI designator observed in the symbol's data (ISO/IEC 18004 §7.4.2).
331/// It governs `raw[start..]` up to the next entry's `start`, or the end; an
332/// empty span governs no byte.
333#[derive(Debug, Clone, Copy, PartialEq, Eq)]
334#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
335#[non_exhaustive]
336pub struct EciSegment {
337 /// ECI assignment number as encoded, 0-999999.
338 pub designator: u32,
339 /// Byte offset into [`DecodedContent::raw`]; non-decreasing along the
340 /// list, at most `raw.len()`.
341 pub start: u32,
342}
343
344/// FNC1 position (ISO/IEC 18004 §7.4.8; AIM `]Q3`–`]Q6`,
345/// `]d2`/`]d3`/`]d5`/`]d6`, `]C1`/`]C2`).
346#[derive(Debug, Clone, Copy, PartialEq, Eq)]
347#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
348#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
349#[non_exhaustive]
350pub enum Fnc1Position {
351 /// GS1 mode: `raw` holds GS1 element-string data (QR and Data Matrix
352 /// transmit 0x1D between fields; GS1-128 read by the current engine
353 /// does not).
354 First,
355 /// AIM application mode: `raw` starts with the application indicator.
356 Second,
357 /// Reader side only, as [`Charset::Unrecognized`].
358 #[cfg_attr(feature = "serde", serde(other, skip_serializing))]
359 Unrecognized,
360}
361
362/// The exact bytes, the declarations observed and the scanner's ONE reading
363/// of them (spec/01 § Content). Compare contents by identity (spec/01
364/// § Comparing contents), never by `text`.
365#[derive(Debug, Clone, PartialEq, Eq)]
366#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
367#[non_exhaustive]
368pub struct DecodedContent {
369 /// `raw` decoded as `charset` states; empty if and only if `raw` is
370 /// empty.
371 pub text: String,
372 /// Payload bytes, base64 on the wire. QR family: the ORIGINAL bytes on
373 /// every decode path (designators excluded), never an engine's text.
374 /// Other symbologies: the ISO/IEC 8859-1 encoding of the engine's text
375 /// when every character is ≤ U+00FF (exact on its non-ECI paths), else
376 /// its UTF-8; under an ECI the engine's text can omit a segment it could
377 /// not decode (spec/01 § raw).
378 #[cfg_attr(feature = "serde", serde(with = "raw_b64"))]
379 pub raw: Vec<u8>,
380 /// How `text` relates to `raw`.
381 pub charset: Charset,
382 /// `None` (key absent): no designator observed. `Some(vec![])`: ECI use
383 /// signalled (`]Q2`/`]Q4`/`]Q6`) but the designators could not be
384 /// located.
385 #[cfg_attr(
386 feature = "serde",
387 serde(default, skip_serializing_if = "Option::is_none")
388 )]
389 pub eci: Option<Vec<EciSegment>>,
390 /// `None` (key absent): no FNC1 observed, or not observable for this
391 /// symbology.
392 #[cfg_attr(
393 feature = "serde",
394 serde(default, skip_serializing_if = "Option::is_none")
395 )]
396 pub fnc1: Option<Fnc1Position>,
397}
398
399/// QR symbol metadata.
400#[derive(Debug, Clone, Copy, PartialEq, Eq)]
401#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
402#[non_exhaustive]
403pub struct QrMeta {
404 /// Symbol version, 1-40, when an engine measured it (rqrr path).
405 pub version: Option<u8>,
406 /// Error-correction level when measured — or, for a symbol only rxing
407 /// read, the level its decoder states (the one field such a read fills).
408 pub ec_level: Option<EcLevel>,
409 /// Mask pattern 0-7 when measured.
410 pub mask: Option<u8>,
411 /// Modules per side (`version * 4 + 17`), derived from `version`.
412 pub modules: Option<u8>,
413 /// Symbol is photometrically INVERTED (light-on-dark) — measured from
414 /// the geometry source's decode path. `None` when no geometry (the
415 /// rxing-only path handles inverted symbols internally without
416 /// reporting which reading won).
417 pub inverted: Option<bool>,
418}
419
420/// One decoded symbol content.
421///
422/// Detections are the distinct contents the scanner can tell apart
423/// (spec/01 § Detection): every read of every attempt is reconciled before
424/// publication, and reads with the same symbology, `raw` and FNC1 position
425/// and compatible ECI evidence become one detection. Identical copies of a
426/// symbol are one detection; a different `raw`, FNC1 position or
427/// contradicting declarations always stay separate, even with equal text.
428#[derive(Debug, Clone, PartialEq)]
429#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
430#[non_exhaustive]
431pub struct Detection {
432 /// The barcode symbology this detection was read as.
433 pub symbology: Symbology,
434 /// The content: raw bytes, declarations and the one reading of them.
435 pub content: DecodedContent,
436 /// Typed payload classification of the text.
437 pub payload: Payload,
438 /// Symbol corners in image coordinates, clockwise from top-left: from
439 /// rqrr (its decode, or a grid it detected that the scanner
440 /// error-corrected itself — `engines` may then list rxing alone) or the
441 /// S5 rescue candidate.
442 pub corners: Option<[Point; 4]>,
443 /// Symbol metadata, from the same source as `corners`; a symbol only
444 /// rxing read carries the EC level its decoder states and nothing else
445 /// (spec/01 § Detection).
446 pub meta: QrMeta,
447 /// Engines that confirmed this payload (consensus surface for scoring).
448 pub engines: Vec<EngineKind>,
449 /// Where each physical copy of this content was measured (spec/01
450 /// § Occurrences): at least one, at most sixteen, earliest observed
451 /// first. Identical copies stay one detection with several occurrences.
452 /// Empty only in a report older than pipeline 5.
453 #[cfg_attr(feature = "serde", serde(default))]
454 pub occurrences: Vec<Occurrence>,
455}
456
457/// One physical copy of a detection's content.
458#[derive(Debug, Clone, PartialEq)]
459#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
460#[non_exhaustive]
461pub struct Occurrence {
462 /// What a reader measured of it, as measured.
463 pub geometry: OccurrenceGeometry,
464}
465
466/// What a reader measured of one symbol, in stored-pixel image
467/// coordinates — never completed, extended or reconstructed.
468#[derive(Debug, Clone, PartialEq)]
469#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
470#[non_exhaustive]
471pub struct OccurrenceGeometry {
472 /// What the points are.
473 pub kind: GeometryKind,
474 /// `quad` 4 · `segment` 2 · `partial` 1 to 8 · `unavailable` none.
475 pub points: Vec<Point>,
476 /// The reader that measured the points; `None` exactly when
477 /// `unavailable`.
478 pub reader: Option<EngineKind>,
479}
480
481/// The kind of an occurrence's geometry (spec/01 § Occurrences).
482#[derive(Debug, Clone, Copy, PartialEq, Eq)]
483#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
484#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
485#[non_exhaustive]
486pub enum GeometryKind {
487 /// Four outer corners: finite, inside the image within a small
488 /// tolerance, strictly convex, clockwise in image space. Only for the
489 /// QR family does the first corner mean the symbol's top-left.
490 Quad,
491 /// Two points along the reader's scan line — neither the symbol's
492 /// extent nor its height.
493 Segment,
494 /// Points that form no validated quad or segment.
495 Partial,
496 /// The reader measured nothing.
497 Unavailable,
498}
499
500/// Capacities a scan reached: what it left out is unknown, not absent.
501#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
502#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
503#[non_exhaustive]
504pub struct Saturation {
505 /// Distinct reads past the walk's capacity were not reconciled.
506 pub reads: bool,
507 /// Contents past the sixteen published detections were left out.
508 pub detections: bool,
509 /// A detection's occurrences are incomplete: footprints past a
510 /// capacity, copies past sixteen, or copies kept together without their
511 /// pixels compared.
512 pub occurrences: bool,
513}
514
515impl Saturation {
516 /// Either capacity reached.
517 #[must_use]
518 pub fn either(a: Self, b: Self) -> Self {
519 Self {
520 reads: a.reads || b.reads,
521 detections: a.detections || b.detections,
522 occurrences: a.occurrences || b.occurrences,
523 }
524 }
525
526 /// Whether any capacity was reached.
527 #[must_use]
528 pub fn any(self) -> bool {
529 self.reads || self.detections || self.occurrences
530 }
531}
532
533/// Score grade bands — the published interpretation table.
534#[derive(Debug, Clone, Copy, PartialEq, Eq)]
535#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
536#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
537#[non_exhaustive]
538pub enum Grade {
539 /// 80-100 — safe for all devices and conditions.
540 Excellent,
541 /// 70-79 — production ready.
542 Good,
543 /// 60-69 — may fail on older phones or poor lighting.
544 Acceptable,
545 /// 40-59 — consider regenerating.
546 Fair,
547 /// 0-39 — regenerate.
548 Poor,
549}
550
551impl Grade {
552 /// Band for a 0-100 score value.
553 #[must_use]
554 pub fn from_value(value: u8) -> Self {
555 match value {
556 80.. => Self::Excellent,
557 70..=79 => Self::Good,
558 60..=69 => Self::Acceptable,
559 40..=59 => Self::Fair,
560 0..=39 => Self::Poor,
561 }
562 }
563}
564
565/// One stress dimension of the score contract.
566#[derive(Debug, Clone, Copy, PartialEq, Eq)]
567#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
568#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
569#[non_exhaustive]
570pub enum StressAxis {
571 /// Downscale ramp — sampling margin (px/module floor).
572 Resolution,
573 /// Gaussian blur ramp — focus/motion margin.
574 Blur,
575 /// Global contrast reduction ramp.
576 Contrast,
577 /// Perspective tilt ramp — grid-estimation margin.
578 Perspective,
579 /// Non-cardinal rotation ramp.
580 Rotation,
581 /// Local lighting defects (shadow · glare · exposure) — pass set.
582 Lighting,
583}
584
585impl StressAxis {
586 /// Parse the wire name (the `snake_case` serde spelling — what
587 /// `score.axes[].axis` carries). The bindings' string-config seam:
588 /// same shape as [`crate::ScanProfile::from_name`].
589 #[must_use]
590 pub fn from_name(name: &str) -> Option<Self> {
591 match name {
592 "resolution" => Some(Self::Resolution),
593 "blur" => Some(Self::Blur),
594 "contrast" => Some(Self::Contrast),
595 "perspective" => Some(Self::Perspective),
596 "rotation" => Some(Self::Rotation),
597 "lighting" => Some(Self::Lighting),
598 _ => None,
599 }
600 }
601}
602
603/// Survival result on one stress axis.
604#[derive(Debug, Clone, PartialEq, Eq)]
605#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
606#[non_exhaustive]
607pub struct AxisScore {
608 /// The dimension.
609 pub axis: StressAxis,
610 /// Cells survived. Ramps stop at the first failure (the knee); the
611 /// lighting set is unordered — no knee-exit (depth still picks the
612 /// cell subset).
613 pub passed: u8,
614 /// Cells in the ramp at this depth.
615 pub total: u8,
616 /// Wire label of the first failed cell — WHY this axis lost points
617 /// ("blur 2.5", "glare", "128px"…). `null` when every cell passed.
618 /// The panel's explainability seam: a lost point always names its cell.
619 pub failed_at: Option<String>,
620 /// The knee, bisected once (Full depth, ordered ramps only): the
621 /// TIGHTEST TESTED failing intensity — the midpoint label when the
622 /// midpoint probe failed, the knee cell's label when it held. Key
623 /// ABSENT when no refinement ran (Reduced depth · no knee · lighting ·
624 /// budget cut — the score stands, and `trace.budget_exhausted` says the
625 /// budget cut it). Informational: the composite never reads it.
626 #[cfg_attr(
627 feature = "serde",
628 serde(default, skip_serializing_if = "Option::is_none")
629 )]
630 pub refined_failed_at: Option<String>,
631}
632
633/// ISO 15415 UEC grade bands.
634#[derive(Debug, Clone, Copy, PartialEq, Eq)]
635#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
636#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
637#[non_exhaustive]
638pub enum UecGrade {
639 /// margin ≥ 0.62
640 A,
641 /// margin ≥ 0.50
642 B,
643 /// margin ≥ 0.37
644 C,
645 /// margin ≥ 0.25
646 D,
647 /// margin < 0.25
648 F,
649}
650
651impl UecGrade {
652 /// ISO band for a margin value.
653 #[must_use]
654 pub fn from_margin(margin: f32) -> Self {
655 if margin >= 0.62 {
656 Self::A
657 } else if margin >= 0.50 {
658 Self::B
659 } else if margin >= 0.37 {
660 Self::C
661 } else if margin >= 0.25 {
662 Self::D
663 } else {
664 Self::F
665 }
666 }
667}
668
669/// Synthetic Unused Error Correction — the real robustness margin
670/// (`1 − 2t/d`, worst RS block). Validation-grade, not ISO verification.
671/// Measured on the stream of the orientation the decode verified, only
672/// when every block error-corrects errors-only under the detection's
673/// version, EC level and mask; a stream the S5 rescue recovered keeps its
674/// errors-only count.
675#[derive(Debug, Clone, Copy, PartialEq)]
676#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
677#[non_exhaustive]
678pub struct UecReport {
679 /// Remaining correction margin, 0.0-1.0 (1.0 = pristine).
680 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
681 pub margin: f32,
682 /// ISO band for `margin`.
683 pub grade: UecGrade,
684 /// Errors the worst block corrected, or a rescued read's errors-only count.
685 pub worst_block_errors: u8,
686 /// EC codewords (capacity `d`) of that block.
687 pub worst_block_capacity: u8,
688}
689
690/// Structural checks — computed when symbol geometry was measured.
691#[derive(Debug, Clone, Copy, PartialEq)]
692#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
693#[non_exhaustive]
694pub struct StructuralReport {
695 /// Per-finder 1:1:3:1:1 integrity, 0.0-1.0 — [top-left, top-right,
696 /// bottom-left]. The #1 documented AI-art failure mode.
697 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize_array"))]
698 pub finder_integrity: [f32; 3],
699 /// Clear border present — probed on a 2-module outer ring (ISO/IEC
700 /// 18004 recommends 4 modules; the lenient probe targets what breaks
701 /// locators in practice).
702 pub quiet_zone_ok: bool,
703}
704
705/// ISO 15415 letter grade (4=A … 0=F vocabulary, lowercase on the wire).
706#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
707#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
708#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
709#[non_exhaustive]
710pub enum IsoGrade {
711 /// 4.0
712 A,
713 /// 3.0
714 B,
715 /// 2.0
716 C,
717 /// 1.0
718 D,
719 /// 0.0
720 F,
721}
722
723/// One measured ISO 15415 parameter: the raw value + its grade band.
724#[derive(Debug, Clone, Copy, PartialEq)]
725#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
726#[non_exhaustive]
727pub struct IsoParameter {
728 /// Parameter value in its ISO unit (see each field's doc).
729 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
730 pub value: f32,
731 /// ISO band for `value`.
732 pub grade: IsoGrade,
733}
734
735/// ISO/IEC 15415-**informed** grade card — the software-measurable subset.
736///
737/// HONESTY CONTRACT: a conformant 15415 grade requires calibrated optics
738/// (45° illumination, stated wavelength, defined aperture — they are IN the
739/// grade string) and ISO 15426-2 hardware conformance. This report is
740/// standards-based DIAGNOSTICS over an arbitrary image. Grid Nonuniformity
741/// and Reflectance Margin are deliberately absent (not measurable from
742/// 4-corner geometry / uncalibrated reflectance).
743#[derive(Debug, Clone, Copy, PartialEq)]
744#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
745#[non_exhaustive]
746pub struct Iso15415Report {
747 /// Symbol Contrast — `(R_high − R_low)/255` over module means
748 /// (2nd/98th percentile, noise-robust). A ≥0.70 · B ≥0.55 · C ≥0.40 ·
749 /// D ≥0.20.
750 pub symbol_contrast: IsoParameter,
751 /// Modulation — robust minimum of per-module `2·|R − GT|/SC`
752 /// (5th percentile; simplified — no notional-UEC iteration).
753 /// A ≥0.50 · B ≥0.40 · C ≥0.30 · D ≥0.20.
754 pub modulation: IsoParameter,
755 /// Axial Nonuniformity — `|X̄ − Ȳ| / mean` of the two axis pitches from
756 /// the detected corners. A ≤0.06 · B ≤0.08 · C ≤0.10 · D ≤0.12.
757 /// Caveat: perspective in a photo reads as ANU (ISO assumes flat capture).
758 pub axial_nonuniformity: IsoParameter,
759 /// Fixed Pattern Damage approximation — worst finder integrity
760 /// (A ≥0.95 · B ≥0.90 · C ≥0.80 · D ≥0.70); a quiet-zone violation caps
761 /// the grade at D. (No clock-track subtest.)
762 pub fixed_pattern_damage: IsoParameter,
763 /// Unused Error Correction — the synthetic UEC margin, ISO bands
764 /// (A ≥0.62 · B ≥0.50 · C ≥0.37 · D ≥0.25). `None` without a measured
765 /// margin, or withheld when the `uec` check is skipped (its grade still
766 /// counts in `overall`).
767 pub unused_error_correction: Option<IsoParameter>,
768 /// Overall = LOWEST measured parameter (the ISO rule) — a parameter
769 /// withheld by `score_skip_checks` (`uec`) still counts, so a skip never
770 /// moves it. Decode = A implicit (only decoded symbols are graded).
771 pub overall: IsoGrade,
772}
773
774/// Scannability score — survival ramps, structural caps and the UEC margin
775/// cap (spec/04-score.md). Validation, NOT ISO verification (no calibrated
776/// optics). A present score is a COMPLETE judgment: its calibration and
777/// every planned stress cell ran, so no budget moves it — only a knee
778/// bisection (`AxisScore::refined_failed_at`) may be missing.
779#[derive(Debug, Clone, PartialEq)]
780#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
781#[non_exhaustive]
782pub struct Score {
783 /// Composite 0-100 (weighted axis survival, then the structural caps and
784 /// the UEC margin cap).
785 pub value: u8,
786 /// Σ contract weights of the axes that RAN (100 = the full six-axis
787 /// contract · 70 with perspective+rotation skipped). The honesty
788 /// integer: a score on skipped axes SAYS how much contract stands
789 /// behind it — two 85s with different `weights_run` are different
790 /// promises. Only skipped axes lower it, never the budget.
791 /// Lenient default 0 when parsing pre-0.9 reports.
792 #[cfg_attr(feature = "serde", serde(default))]
793 pub weights_run: u8,
794 /// Interpretation band for `value`.
795 pub grade: Grade,
796 /// Per-axis survival breakdown.
797 pub axes: Vec<AxisScore>,
798 /// Structural checks — `None` when no geometry was measured.
799 pub structural: Option<StructuralReport>,
800 /// Synthetic UEC margin — `None` when no stream error-corrects
801 /// errors-only under the detection's format (then no margin cap and no
802 /// margin hint either), or when the `uec` check is skipped (the measured
803 /// margin still caps `value`).
804 pub uec: Option<UecReport>,
805 /// ISO 15415-informed grade card — `None` when no geometry was measured.
806 pub iso15415: Option<Iso15415Report>,
807}
808
809/// The requested alpha-background handling (config echo on the wire).
810#[derive(Debug, Clone, Copy, PartialEq, Eq)]
811#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
812#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
813#[non_exhaustive]
814pub enum AlphaMode {
815 /// Adaptive: the content's own luma picked the background.
816 Auto,
817 /// Forced white.
818 White,
819 /// Forced black.
820 Black,
821 /// Forced host background (`alpha.background` carries the hex).
822 Custom,
823}
824
825/// Placement verdict spelled by the envelope's decoded ranges.
826#[derive(Debug, Clone, Copy, PartialEq, Eq)]
827#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
828#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
829#[non_exhaustive]
830pub enum AlphaPlacement {
831 /// Every tested background decoded — place it anywhere.
832 Any,
833 /// Only light backgrounds decoded (dark-module designs).
834 LightOnly,
835 /// Only dark backgrounds decoded (light-module designs).
836 DarkOnly,
837 /// A narrower or split range — read `safe_luma` for the exact bands.
838 Mixed,
839 /// No tested background decoded.
840 None,
841}
842
843/// One neutral-background decode probe of the placement envelope.
844#[derive(Debug, Clone, Copy, PartialEq, Eq)]
845#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
846#[non_exhaustive]
847pub struct AlphaProbe {
848 /// Neutral background luma composited under the content.
849 pub background_luma: u8,
850 /// One of the composite's reads denotes the same content as the
851 /// primary detection (spec/07 property 7).
852 pub decoded: bool,
853}
854
855/// One HOST-requested palette probe (`alpha_palette` config) — "does the
856/// design survive on this specific theme/brand color".
857#[derive(Debug, Clone, PartialEq, Eq)]
858#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
859#[non_exhaustive]
860pub struct AlphaPaletteProbe {
861 /// The requested color — `"white"` · `"black"` · `"#rrggbb"`.
862 pub background: String,
863 /// Its BT.601 luma (the sweep is luma-space by construction).
864 pub background_luma: u8,
865 /// One of the composite's reads denotes the same content as the
866 /// primary detection (spec/07 property 7).
867 pub decoded: bool,
868}
869
870/// The placement envelope — "over which backgrounds does this transparent
871/// design keep decoding". Probes are quick decodes in the primary symbol's
872/// own decode class (never the full ladder's recovery power): the envelope
873/// measures COMFORTABLE placement, the primary verdict measures full
874/// margin on its declared background.
875#[derive(Debug, Clone, PartialEq, Eq)]
876#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
877#[non_exhaustive]
878pub struct AlphaEnvelope {
879 /// Decode probes ordered by background luma — the five fixed rungs
880 /// (0 · 64 · 128 · 192 · 255) plus one bisection probe per
881 /// decoded/undecoded boundary.
882 pub probes: Vec<AlphaProbe>,
883 /// Contiguous decoded bands `[lo, hi]` — every endpoint is a TESTED
884 /// background, never interpolation.
885 pub safe_luma: Vec<[u8; 2]>,
886 /// The verdict the bands spell.
887 pub placement: AlphaPlacement,
888 /// HOST-requested palette verdicts (`alpha_palette` config), in
889 /// request order — empty when none were requested. Palette colors
890 /// never distort the neutral `probes`/`safe_luma`/`placement`.
891 pub palette: Vec<AlphaPaletteProbe>,
892}
893
894/// How transparency was handled for this scan. Present ONLY when the input
895/// actually carried transparent pixels AND `alpha_background` was not
896/// `none` — opaque inputs stay byte-identical to pre-0.9 reports.
897#[derive(Debug, Clone, PartialEq)]
898#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
899#[non_exhaustive]
900pub struct AlphaReport {
901 /// Fraction of pixels with alpha < 255, rounded to 3 decimals.
902 #[cfg_attr(feature = "serde", serde(serialize_with = "decimal::serialize"))]
903 pub coverage: f32,
904 /// Alpha-weighted mean BT.601 luma of the visible content — what the
905 /// `auto` decision reads (< 128 → white, else black).
906 pub content_luma: u8,
907 /// The requested handling mode (config echo).
908 pub mode: AlphaMode,
909 /// Background the verdict was measured over — `"white"` · `"black"` ·
910 /// `"#rrggbb"`.
911 pub background: String,
912 /// The declared flatten found nothing and the opposite background
913 /// produced the detections (`auto` only).
914 pub fallback_used: bool,
915 /// The placement envelope — Full profile only; `None` when skipped
916 /// (`score_skip_checks: ["alpha_envelope"]`), cut by the budget
917 /// (`trace.budget_exhausted`), when no probe class reads the design, or
918 /// after a contained fault of the score computation.
919 pub envelope: Option<AlphaEnvelope>,
920}
921
922/// Machine-actionable improvement hint — the generator/agent feedback loop.
923#[derive(Debug, Clone, PartialEq, Eq)]
924#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
925#[cfg_attr(feature = "serde", serde(tag = "hint", rename_all = "snake_case"))]
926#[non_exhaustive]
927pub enum Hint {
928 /// Regenerate with a higher error-correction level.
929 RaiseErrorCorrection {
930 /// Level observed in the symbol.
931 current: EcLevel,
932 },
933 /// Module contrast is the limiting factor.
934 IncreaseContrast,
935 /// Modules are too dense/small for reliable sampling.
936 EnlargeModules,
937 /// A finder pattern is damaged.
938 FixFinderPattern {
939 /// Corner index: 0 top-left, 1 top-right, 2 bottom-left.
940 corner: u8,
941 },
942 /// The quiet zone is violated.
943 RestoreQuietZone,
944 /// Artistic texture overwhelms module structure.
945 ReduceArtTexture,
946 /// The published UEC margin is 0: the worst RS block's errors spent all
947 /// its parity (on a rescued read, its errors-only count reached it), so
948 /// the decode may already BE a miscorrection. Treat the content as
949 /// unverified; confirm out-of-band before acting on it.
950 LowCorrectionMargin {
951 /// Errors the worst block corrected, or a rescued read's errors-only count.
952 errors: u8,
953 /// EC codeword capacity of that block.
954 capacity: u8,
955 },
956 /// The transparent design only survives on part of the background
957 /// range (`alpha.envelope` narrower than `any`): pin a background
958 /// layer in the artwork, or place it only on surfaces inside
959 /// `alpha.envelope.safe_luma`.
960 AlphaBackgroundDependent {
961 /// The envelope's placement verdict.
962 placement: AlphaPlacement,
963 },
964 /// The canonical REMEDY for a background-dependent transparent design:
965 /// add an opaque plate (rounded rectangle + quiet-zone margin) behind
966 /// the symbol in the artwork — robust everywhere, transparent look
967 /// preserved around it. Fires alongside `alpha_background_dependent`.
968 AddBackgroundPlate {
969 /// Plate color that maximizes contrast with the design's content.
970 color: PlateColor,
971 },
972}
973
974/// Recommended plate color for [`Hint::AddBackgroundPlate`].
975#[derive(Debug, Clone, Copy, PartialEq, Eq)]
976#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
977#[cfg_attr(feature = "serde", serde(rename_all = "snake_case"))]
978#[non_exhaustive]
979pub enum PlateColor {
980 /// Dark content — plate white.
981 White,
982 /// Light content — plate black.
983 Black,
984}
985
986/// Per-stage pipeline trace entry.
987#[derive(Debug, Clone, PartialEq)]
988#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
989#[non_exhaustive]
990pub struct StageTrace {
991 /// Stage name (stable identifiers: `pyramid` · `direct` · `enhance` ·
992 /// `deep` · `rescue`).
993 pub stage: String,
994 /// Number of transform attempts executed in this stage.
995 pub transforms_tried: u32,
996 /// Wall-clock milliseconds spent in this stage.
997 pub ms: f64,
998 /// Reads this stage's engine adapters delivered — raw hits before
999 /// folding, the re-read, vetoes and reconciliation (an rxing + rqrr
1000 /// double read counts 2); a decode an adapter refuses (an rqrr grid that
1001 /// parses malformed, an rxing read a read check refuses) is not delivered;
1002 /// candidate re-derivations, re-reads and confirmation decodes never count.
1003 /// It includes hits the scanner later refuses or holds: read `detections`.
1004 pub detections_found: u32,
1005}
1006
1007/// Pipeline execution trace — why a scan succeeded or came back empty.
1008#[derive(Debug, Clone, PartialEq)]
1009#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1010#[non_exhaustive]
1011pub struct PipelineTrace {
1012 /// Stages executed, in order.
1013 pub stages: Vec<StageTrace>,
1014 /// Engine panics caught and isolated during this scan.
1015 pub engine_panics: u8,
1016 /// Wall-clock milliseconds of the ladder walk(s) only.
1017 pub total_ms: f64,
1018 /// `Some(true)`: the wall-clock budget prevented planned work — a
1019 /// ladder attempt or stage, the opposite-background walk, a rescue
1020 /// candidate, a score calibration step or stress cell, a knee bisection,
1021 /// an envelope probe — and the report is PARTIAL. `Some(false)`: every
1022 /// planned unit ran and the report is final, equal to the unbounded one
1023 /// (wall clock aside). `None`: unknown, a report older than this field;
1024 /// this crate always writes `Some`, and an unbounded scan `Some(false)`.
1025 #[cfg_attr(
1026 feature = "serde",
1027 serde(default, skip_serializing_if = "Option::is_none")
1028 )]
1029 pub budget_exhausted: Option<bool>,
1030 /// The capacities the scan reached, independent of the budget. `None`:
1031 /// unknown, a report older than pipeline 5; this crate always writes
1032 /// `Some`.
1033 #[cfg_attr(
1034 feature = "serde",
1035 serde(default, skip_serializing_if = "Option::is_none")
1036 )]
1037 pub saturation: Option<Saturation>,
1038 /// The symbologies the scan was restricted to (`ScanConfig::formats`),
1039 /// each once, in the declaration order of [`Symbology`]. `None`: every
1040 /// symbology the build reads was looked for — an unrestricted scan, and
1041 /// every report older than this field.
1042 #[cfg_attr(
1043 feature = "serde",
1044 serde(default, skip_serializing_if = "Option::is_none")
1045 )]
1046 pub formats: Option<Vec<Symbology>>,
1047}
1048
1049impl Default for PipelineTrace {
1050 /// An empty walk that skipped nothing: the trace of a final report.
1051 fn default() -> Self {
1052 Self {
1053 stages: Vec::new(),
1054 engine_panics: 0,
1055 total_ms: 0.0,
1056 budget_exhausted: Some(false),
1057 saturation: Some(Saturation::default()),
1058 formats: None,
1059 }
1060 }
1061}
1062
1063/// Contract version markers carried by every report.
1064#[derive(Debug, Clone, PartialEq, Eq)]
1065#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1066#[non_exhaustive]
1067pub struct Versions {
1068 /// Crate version that produced the report.
1069 pub scanner: String,
1070 /// Decode pipeline version.
1071 pub pipeline: u8,
1072 /// Score contract version.
1073 pub score_contract: u8,
1074}
1075
1076impl QrMeta {
1077 /// Modules per side for a QR version (`v*4 + 17`), `None` past v40 —
1078 /// the ONE place this formula lives.
1079 #[must_use]
1080 pub fn modules_per_side(version: u8) -> Option<u8> {
1081 (1..=40).contains(&version).then(|| version * 4 + 17)
1082 }
1083}
1084
1085impl Versions {
1086 /// Markers for this build.
1087 #[must_use]
1088 pub fn current() -> Self {
1089 Self {
1090 scanner: env!("CARGO_PKG_VERSION").to_owned(),
1091 // pipeline 5: every physical copy of a content measured as an
1092 // occurrence (equal linear copies no longer collapse in the
1093 // multiple reader) and the capacities a scan reached published.
1094 // Pipeline 4: native-resolution linear completion after a QR
1095 // pyramid read, plus independently confirmed DataBar reads.
1096 pipeline: 5,
1097 // score contract 6: the correction margin measured in the image
1098 // (the widest verified sampling of the symbol, whatever read
1099 // it), so one design keeps one margin at every export size;
1100 // and a linear symbology judged on a base that keeps the pixel
1101 // count of the 512 px square, not its side.
1102 // Contract 5: the margin cap on the verified orientation's
1103 // stream, interrupted judgments absent, probes matched by
1104 // content identity.
1105 score_contract: 6,
1106 }
1107 }
1108}
1109
1110/// The scan result — the versioned cross-boundary contract.
1111///
1112/// Empty `detections` means "no QR found", which is a valid outcome,
1113/// never an error.
1114#[derive(Debug, Clone, PartialEq)]
1115#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1116#[non_exhaustive]
1117pub struct ScanReport {
1118 /// Decoded symbols (empty = nothing found — final only when
1119 /// `trace.budget_exhausted` is `Some(false)`; multi-QR future-proof).
1120 pub detections: Vec<Detection>,
1121 /// Scannability score of the PRIMARY detection (`detections[0]` — for
1122 /// single-QR inputs, THE symbol). `None` exactly when no judgment was
1123 /// published: no detection; a configuration that computes no score
1124 /// ([`crate::ScanConfig::computes_score`]: the `Frame` profile, every
1125 /// axis skipped); a judgment the budget interrupted
1126 /// (`trace.budget_exhausted` is then `Some(true)`); a contained internal
1127 /// fault in the score computation. Never partial, never a zero.
1128 /// Per-detection scoring for multi-QR scenes is a future additive
1129 /// extension.
1130 pub score: Option<Score>,
1131 /// Machine-actionable improvement hints.
1132 pub hints: Vec<Hint>,
1133 /// Alpha-transparency handling — absent (not `null`) for opaque
1134 /// inputs and under `alpha_background: none`, so pre-0.9 consumers
1135 /// and opaque reports keep their exact bytes.
1136 #[cfg_attr(
1137 feature = "serde",
1138 serde(default, skip_serializing_if = "Option::is_none")
1139 )]
1140 pub alpha: Option<AlphaReport>,
1141 /// Pipeline execution trace.
1142 pub trace: PipelineTrace,
1143 /// Contract version markers.
1144 pub versions: Versions,
1145}
1146
1147impl ScanReport {
1148 /// A valid "nothing found" report.
1149 #[must_use]
1150 pub fn empty() -> Self {
1151 Self {
1152 detections: Vec::new(),
1153 score: None,
1154 hints: Vec::new(),
1155 alpha: None,
1156 trace: PipelineTrace::default(),
1157 versions: Versions::current(),
1158 }
1159 }
1160}
1161
1162#[cfg(test)]
1163mod tests {
1164 #![allow(clippy::unwrap_used, clippy::expect_used)]
1165
1166 use super::*;
1167 use crate::payload::Payload;
1168
1169 fn full_alpha() -> AlphaReport {
1170 AlphaReport {
1171 coverage: 0.612,
1172 content_luma: 34,
1173 mode: AlphaMode::Auto,
1174 background: "white".into(),
1175 fallback_used: false,
1176 envelope: Some(AlphaEnvelope {
1177 probes: [
1178 (0, false),
1179 (64, false),
1180 (96, false),
1181 (128, true),
1182 (192, true),
1183 (255, true),
1184 ]
1185 .into_iter()
1186 .map(|(background_luma, decoded)| AlphaProbe {
1187 background_luma,
1188 decoded,
1189 })
1190 .collect(),
1191 safe_luma: vec![[128, 255]],
1192 placement: AlphaPlacement::LightOnly,
1193 palette: vec![AlphaPaletteProbe {
1194 background: "#1a1a2e".into(),
1195 background_luma: 28,
1196 decoded: false,
1197 }],
1198 }),
1199 }
1200 }
1201
1202 fn full_score() -> Score {
1203 Score {
1204 value: 87,
1205 grade: Grade::Excellent,
1206 weights_run: 42,
1207 axes: vec![
1208 AxisScore {
1209 axis: StressAxis::Resolution,
1210 passed: 4,
1211 total: 5,
1212 failed_at: None,
1213 refined_failed_at: None,
1214 },
1215 AxisScore {
1216 axis: StressAxis::Perspective,
1217 passed: 3,
1218 total: 5,
1219 failed_at: Some("34\u{b0}".into()),
1220 refined_failed_at: Some("30\u{b0}".into()),
1221 },
1222 ],
1223 structural: Some(StructuralReport {
1224 finder_integrity: [1.0, 0.96, 0.88],
1225 quiet_zone_ok: true,
1226 }),
1227 uec: Some(UecReport {
1228 margin: 0.85,
1229 grade: UecGrade::A,
1230 worst_block_errors: 1,
1231 worst_block_capacity: 18,
1232 }),
1233 iso15415: Some(Iso15415Report {
1234 symbol_contrast: IsoParameter {
1235 value: 0.82,
1236 grade: IsoGrade::A,
1237 },
1238 modulation: IsoParameter {
1239 value: 0.46,
1240 grade: IsoGrade::B,
1241 },
1242 axial_nonuniformity: IsoParameter {
1243 value: 0.03,
1244 grade: IsoGrade::A,
1245 },
1246 fixed_pattern_damage: IsoParameter {
1247 value: 0.88,
1248 grade: IsoGrade::C,
1249 },
1250 unused_error_correction: Some(IsoParameter {
1251 value: 0.85,
1252 grade: IsoGrade::A,
1253 }),
1254 overall: IsoGrade::C,
1255 }),
1256 }
1257 }
1258
1259 fn full_report() -> ScanReport {
1260 ScanReport {
1261 detections: vec![Detection {
1262 symbology: Symbology::QrCode,
1263 content: DecodedContent {
1264 text: "https://qrcode-ai.com".into(),
1265 raw: b"https://qrcode-ai.com".to_vec(),
1266 charset: Charset::Utf8,
1267 eci: None,
1268 fnc1: None,
1269 },
1270 payload: Payload::Text,
1271 corners: Some([
1272 Point { x: 10.0, y: 10.0 },
1273 Point { x: 90.0, y: 10.5 },
1274 Point { x: 90.5, y: 90.0 },
1275 Point { x: 10.0, y: 89.5 },
1276 ]),
1277 meta: QrMeta {
1278 version: Some(5),
1279 ec_level: Some(EcLevel::Q),
1280 mask: Some(3),
1281 modules: Some(37),
1282 inverted: Some(false),
1283 },
1284 engines: vec![EngineKind::Rxing, EngineKind::Rqrr],
1285 occurrences: vec![Occurrence {
1286 geometry: OccurrenceGeometry {
1287 kind: GeometryKind::Quad,
1288 points: vec![
1289 Point { x: 10.0, y: 10.0 },
1290 Point { x: 86.5, y: 10.4 },
1291 Point { x: 86.9, y: 86.0 },
1292 Point { x: 10.0, y: 85.6 },
1293 ],
1294 reader: Some(EngineKind::Rqrr),
1295 },
1296 }],
1297 }],
1298 score: Some(full_score()),
1299 hints: vec![
1300 Hint::RaiseErrorCorrection {
1301 current: EcLevel::Q,
1302 },
1303 Hint::IncreaseContrast,
1304 Hint::LowCorrectionMargin {
1305 errors: 12,
1306 capacity: 24,
1307 },
1308 Hint::AlphaBackgroundDependent {
1309 placement: AlphaPlacement::LightOnly,
1310 },
1311 Hint::AddBackgroundPlate {
1312 color: PlateColor::White,
1313 },
1314 ],
1315 alpha: Some(full_alpha()),
1316 trace: PipelineTrace {
1317 stages: vec![StageTrace {
1318 stage: "direct".into(),
1319 transforms_tried: 1,
1320 ms: 12.5,
1321 detections_found: 1,
1322 }],
1323 engine_panics: 0,
1324 total_ms: 12.5,
1325 budget_exhausted: Some(false),
1326 saturation: Some(Saturation {
1327 reads: false,
1328 detections: false,
1329 occurrences: true,
1330 }),
1331 formats: None,
1332 },
1333 versions: Versions::current(),
1334 }
1335 }
1336
1337 #[test]
1338 fn symbology_wire_names_pinned() {
1339 for (sym, wire) in [
1340 (Symbology::QrCode, "qr_code"),
1341 (Symbology::MicroQrCode, "micro_qr_code"),
1342 (
1343 Symbology::RectangularMicroQrCode,
1344 "rectangular_micro_qr_code",
1345 ),
1346 (Symbology::DataMatrix, "data_matrix"),
1347 (Symbology::Aztec, "aztec"),
1348 (Symbology::Pdf417, "pdf417"),
1349 (Symbology::MaxiCode, "maxi_code"),
1350 (Symbology::Ean13, "ean13"),
1351 (Symbology::Ean8, "ean8"),
1352 (Symbology::UpcA, "upc_a"),
1353 (Symbology::UpcE, "upc_e"),
1354 (Symbology::Code128, "code128"),
1355 (Symbology::Code39, "code39"),
1356 (Symbology::Code93, "code93"),
1357 (Symbology::Codabar, "codabar"),
1358 (Symbology::Itf, "itf"),
1359 (Symbology::DataBar, "data_bar"),
1360 (Symbology::DataBarExpanded, "data_bar_expanded"),
1361 (Symbology::Telepen, "telepen"),
1362 ] {
1363 assert_eq!(
1364 serde_json::to_value(sym).unwrap(),
1365 serde_json::Value::String(wire.to_owned())
1366 );
1367 }
1368 }
1369
1370 #[cfg(feature = "serde")]
1371 #[test]
1372 fn content_wire_names_pinned() {
1373 for (charset, wire) in [
1374 (Charset::Utf8, "utf8"),
1375 (Charset::ShiftJis, "shift_jis"),
1376 (Charset::Latin1, "latin1"),
1377 (Charset::Gb18030, "gb18030"),
1378 (Charset::Eci, "eci"),
1379 (Charset::Unknown, "unknown"),
1380 ] {
1381 assert_eq!(serde_json::to_value(charset).unwrap(), wire);
1382 let back: Charset = serde_json::from_value(wire.into()).unwrap();
1383 assert_eq!(back, charset);
1384 assert_eq!(charset.is_lossy(), charset == Charset::Unknown, "{wire}");
1385 }
1386 // a newer scanner's label reads as a complete decoding, and is never
1387 // written back
1388 let future: Charset = serde_json::from_str("\"future_x\"").unwrap();
1389 assert_eq!(future, Charset::Unrecognized);
1390 assert!(!future.is_lossy());
1391 assert!(serde_json::to_string(&Charset::Unrecognized).is_err());
1392 for (position, wire) in [
1393 (Fnc1Position::First, "first"),
1394 (Fnc1Position::Second, "second"),
1395 ] {
1396 assert_eq!(serde_json::to_value(position).unwrap(), wire);
1397 }
1398 let fifth: Fnc1Position = serde_json::from_str("\"fifth\"").unwrap();
1399 assert_eq!(fifth, Fnc1Position::Unrecognized);
1400 assert!(serde_json::to_string(&Fnc1Position::Unrecognized).is_err());
1401 assert_eq!(
1402 serde_json::to_value(EciSegment {
1403 designator: 4,
1404 start: 0
1405 })
1406 .unwrap(),
1407 serde_json::json!({"designator": 4, "start": 0})
1408 );
1409 }
1410
1411 #[cfg(feature = "serde")]
1412 #[test]
1413 fn content_optional_keys_are_absent_or_present() {
1414 let content = |eci, fnc1| DecodedContent {
1415 text: "hi".into(),
1416 raw: b"hi".to_vec(),
1417 charset: Charset::Utf8,
1418 eci,
1419 fnc1,
1420 };
1421 assert_eq!(
1422 serde_json::to_value(content(None, None)).unwrap(),
1423 serde_json::json!({"text": "hi", "raw": "aGk=", "charset": "utf8"})
1424 );
1425 assert_eq!(
1426 serde_json::to_value(content(Some(Vec::new()), Some(Fnc1Position::First))).unwrap(),
1427 serde_json::json!({
1428 "text": "hi", "raw": "aGk=", "charset": "utf8", "eci": [], "fnc1": "first"
1429 })
1430 );
1431 // reports without the keys read with both absent
1432 let old: DecodedContent =
1433 serde_json::from_str(r#"{"text":"hi","raw":"aGk=","charset":"utf8"}"#).unwrap();
1434 assert_eq!(old, content(None, None));
1435 let unknown: DecodedContent =
1436 serde_json::from_str(r#"{"text":"日本中文","raw":"k/qWe9bQzsQ=","charset":"unknown"}"#)
1437 .unwrap();
1438 assert_eq!((unknown.charset, unknown.eci), (Charset::Unknown, None));
1439 assert_eq!(
1440 unknown.raw,
1441 [0x93, 0xFA, 0x96, 0x7B, 0xD6, 0xD0, 0xCE, 0xC4]
1442 );
1443 }
1444
1445 #[test]
1446 fn versions_pin_the_contract() {
1447 let v = Versions::current();
1448 assert_eq!(v.scanner, env!("CARGO_PKG_VERSION"));
1449 assert_eq!(
1450 v.pipeline, 5,
1451 "pipeline v5 = occurrences of every physical copy and the capacities \
1452 reached; a bump must be deliberate"
1453 );
1454 assert_eq!(
1455 v.score_contract, 6,
1456 "score contract v6 = the correction margin measured in the image, \
1457 whatever read the symbol; a bump must be deliberate"
1458 );
1459 }
1460
1461 #[test]
1462 fn empty_report_has_no_detections_and_no_score() {
1463 let report = ScanReport::empty();
1464 assert_eq!(report.detections.len(), 0);
1465 assert!(report.score.is_none());
1466 assert_eq!(report.hints.len(), 0);
1467 assert_eq!(report.versions, Versions::current());
1468 }
1469
1470 /// Every report this crate writes says whether the budget cut planned
1471 /// work; a report without the key predates it, and reads as unknown —
1472 /// never as "final".
1473 #[cfg(feature = "serde")]
1474 #[test]
1475 fn the_budget_flag_is_written_always_and_read_absent_as_unknown() {
1476 let old: PipelineTrace =
1477 serde_json::from_str(r#"{"stages":[],"engine_panics":0,"total_ms":0.0}"#).unwrap();
1478 assert_eq!(old.budget_exhausted, None, "absent reads as unknown");
1479 assert_eq!(
1480 serde_json::to_value(&old).unwrap(),
1481 serde_json::json!({"stages": [], "engine_panics": 0, "total_ms": 0.0}),
1482 "an unknown flag is re-written absent, never as false"
1483 );
1484 let cut: PipelineTrace = serde_json::from_str(
1485 r#"{"stages":[],"engine_panics":0,"total_ms":0.0,"budget_exhausted":true}"#,
1486 )
1487 .unwrap();
1488 assert_eq!(cut.budget_exhausted, Some(true));
1489 assert_eq!(
1490 serde_json::to_value(&cut).unwrap()["budget_exhausted"],
1491 true
1492 );
1493 assert_eq!(PipelineTrace::default().budget_exhausted, Some(false));
1494 let empty = serde_json::to_value(ScanReport::empty()).unwrap();
1495 assert_eq!(empty["trace"]["budget_exhausted"], false, "{empty}");
1496 }
1497
1498 #[test]
1499 fn is_qr_family_pins_exactly_the_three_qr_symbologies() {
1500 // report.rs 91:9 — the `matches!` body was replaced by `-> true` AND
1501 // `-> false` stubs, both survived (nothing called the predicate). Pin
1502 // both directions: every QR-family symbology is true, every other false.
1503 for sym in [
1504 Symbology::QrCode,
1505 Symbology::MicroQrCode,
1506 Symbology::RectangularMicroQrCode,
1507 ] {
1508 assert!(sym.is_qr_family(), "{sym:?} is QR-family"); // kills `-> false`
1509 }
1510 for sym in [
1511 Symbology::DataMatrix,
1512 Symbology::Aztec,
1513 Symbology::Pdf417,
1514 Symbology::MaxiCode,
1515 Symbology::Ean13,
1516 Symbology::Ean8,
1517 Symbology::UpcA,
1518 Symbology::UpcE,
1519 Symbology::Code128,
1520 Symbology::Code39,
1521 Symbology::DataBar,
1522 Symbology::Telepen,
1523 ] {
1524 assert!(!sym.is_qr_family(), "{sym:?} is NOT QR-family"); // kills `-> true`
1525 }
1526 }
1527
1528 #[test]
1529 fn is_retail_gtin_pins_exactly_the_four_retail_symbologies() {
1530 // report.rs 100:9 — the `matches!` body → `-> true` stub survived.
1531 // Pin both directions for completeness.
1532 for sym in [
1533 Symbology::Ean13,
1534 Symbology::Ean8,
1535 Symbology::UpcA,
1536 Symbology::UpcE,
1537 ] {
1538 assert!(sym.is_retail_gtin(), "{sym:?} is a retail GTIN carrier"); // kills `-> false`
1539 }
1540 for sym in [
1541 Symbology::QrCode,
1542 Symbology::DataMatrix,
1543 Symbology::Aztec,
1544 Symbology::Code128,
1545 Symbology::Itf,
1546 Symbology::DataBar,
1547 ] {
1548 assert!(!sym.is_retail_gtin(), "{sym:?} is NOT a retail GTIN"); // kills `-> true`
1549 }
1550 }
1551
1552 #[test]
1553 fn grade_bands_are_pinned() {
1554 let bands = [
1555 (100, Grade::Excellent),
1556 (80, Grade::Excellent),
1557 (79, Grade::Good),
1558 (70, Grade::Good),
1559 (69, Grade::Acceptable),
1560 (60, Grade::Acceptable),
1561 (59, Grade::Fair),
1562 (40, Grade::Fair),
1563 (39, Grade::Poor),
1564 (0, Grade::Poor),
1565 ];
1566 for (value, expected) in bands {
1567 assert_eq!(Grade::from_value(value), expected, "value {value}");
1568 }
1569 }
1570
1571 #[test]
1572 fn stress_axes_parse_from_their_wire_names_only() {
1573 // the bindings' string-config seam: every axis from the name the
1574 // report writes for it, and nothing from any other spelling
1575 for (name, axis) in [
1576 ("resolution", StressAxis::Resolution),
1577 ("blur", StressAxis::Blur),
1578 ("contrast", StressAxis::Contrast),
1579 ("perspective", StressAxis::Perspective),
1580 ("rotation", StressAxis::Rotation),
1581 ("lighting", StressAxis::Lighting),
1582 ] {
1583 assert_eq!(StressAxis::from_name(name), Some(axis), "{name}");
1584 #[cfg(feature = "serde")]
1585 assert_eq!(serde_json::to_string(&axis).unwrap(), format!("\"{name}\""));
1586 }
1587 for name in ["", "Blur", "BLUR", "exposure", "tilt"] {
1588 assert_eq!(StressAxis::from_name(name), None, "{name}");
1589 }
1590 }
1591
1592 #[cfg(feature = "serde")]
1593 #[test]
1594 fn schema_snapshot_full() {
1595 insta::assert_json_snapshot!("scan_report_full", full_report(), {
1596 ".versions.scanner" => "[crate-version]"
1597 });
1598 }
1599
1600 #[cfg(feature = "serde")]
1601 #[test]
1602 fn schema_snapshot_empty() {
1603 insta::assert_json_snapshot!("scan_report_empty", ScanReport::empty(), {
1604 ".versions.scanner" => "[crate-version]"
1605 });
1606 }
1607
1608 /// Bindings that convert through serde's data model — pythonize over a
1609 /// `serde_json::Value`, serde-wasm-bindgen — receive what the JSON text
1610 /// shows: an `f32` field arrives as the decimal `serde_json` prints for
1611 /// it, never as the `f32` itself widened (0.612 as 0.6119999885559082).
1612 #[cfg(feature = "serde")]
1613 #[test]
1614 fn float_fields_reach_serde_as_the_decimals_the_json_shows() {
1615 let sum = 0.1_f32 + 0.2_f32; // f32 arithmetic: 0.3
1616 let third = 1.0_f32 / 3.0; // 0.33333334
1617 let point = Point { x: 0.612, y: third };
1618 let value = serde_json::to_value(point).unwrap();
1619 assert_eq!(
1620 (value["x"].as_f64(), value["y"].as_f64()),
1621 (Some(0.612), Some(0.333_333_34))
1622 );
1623 let uec = UecReport {
1624 margin: sum,
1625 grade: UecGrade::A,
1626 worst_block_errors: 0,
1627 worst_block_capacity: 26,
1628 };
1629 assert_eq!(
1630 serde_json::to_value(uec).unwrap()["margin"].as_f64(),
1631 Some(0.3)
1632 );
1633 let structural = StructuralReport {
1634 finder_integrity: [0.612, third, sum],
1635 quiet_zone_ok: true,
1636 };
1637 assert_eq!(
1638 serde_json::to_value(structural).unwrap()["finder_integrity"],
1639 serde_json::json!([0.612, 0.333_333_34, 0.3])
1640 );
1641 let parameter = IsoParameter {
1642 value: 0.612,
1643 grade: IsoGrade::A,
1644 };
1645 assert_eq!(
1646 serde_json::to_value(parameter).unwrap()["value"].as_f64(),
1647 Some(0.612)
1648 );
1649 assert_eq!(
1650 serde_json::to_value(full_alpha()).unwrap()["coverage"].as_f64(),
1651 Some(0.612)
1652 );
1653 // the JSON text is the f32's own shortest decimal, as it always was
1654 assert_eq!(
1655 serde_json::to_string(&point).unwrap(),
1656 r#"{"x":0.612,"y":0.33333334}"#
1657 );
1658 }
1659
1660 /// The decimal spelling never moves a number, and moves no JSON byte
1661 /// where the report's values live: every finite `f32` of a sweep over
1662 /// the whole bit range reads back as the same number, and from 1e-5 to
1663 /// 1e13 (and zero) as the same text.
1664 #[cfg(feature = "serde")]
1665 #[test]
1666 fn the_decimal_spelling_keeps_the_json_text() {
1667 let mut same_text = 0;
1668 for bits in (0..=u32::MAX).step_by(65_521) {
1669 let value = f32::from_bits(bits);
1670 if !value.is_finite() {
1671 continue;
1672 }
1673 let widened = serde_json::to_string(&value).unwrap();
1674 let decimal = serde_json::to_string(&decimal::of(value)).unwrap();
1675 assert_eq!(
1676 widened.parse::<f64>().unwrap().to_bits(),
1677 decimal.parse::<f64>().unwrap().to_bits(),
1678 "{value:e}: {widened} vs {decimal}"
1679 );
1680 // ±0: every bit below the sign is clear
1681 let zero = bits.trailing_zeros() >= 31;
1682 if zero || (1e-5..1e13).contains(&value.abs()) {
1683 assert_eq!(widened, decimal, "{value:e}");
1684 same_text += 1;
1685 }
1686 }
1687 assert!(same_text > 10_000, "{same_text}");
1688 }
1689
1690 #[cfg(feature = "serde")]
1691 #[test]
1692 fn serde_roundtrip_preserves_everything() {
1693 let report = full_report();
1694 let json = serde_json::to_string(&report).unwrap();
1695 let back: ScanReport = serde_json::from_str(&json).unwrap();
1696 assert_eq!(report, back);
1697 }
1698
1699 #[test]
1700 fn two_saturations_keep_every_capacity_either_reached() {
1701 // the alpha fallback folds its walk's saturation into the first
1702 // walk's: a capacity either reached stays reached, flag by flag, and
1703 // none is invented; `any` reads each flag
1704 let none = Saturation::default();
1705 let reads = Saturation {
1706 reads: true,
1707 ..none
1708 };
1709 let detections = Saturation {
1710 detections: true,
1711 ..none
1712 };
1713 let occurrences = Saturation {
1714 occurrences: true,
1715 ..none
1716 };
1717 for one in [reads, detections, occurrences] {
1718 assert_eq!(Saturation::either(one, none), one, "{one:?} first");
1719 assert_eq!(Saturation::either(none, one), one, "{one:?} second");
1720 assert_eq!(Saturation::either(one, one), one, "{one:?} both");
1721 assert!(one.any(), "{one:?}");
1722 }
1723 assert_eq!(Saturation::either(none, none), none);
1724 assert!(!none.any());
1725 assert_eq!(
1726 Saturation::either(reads, Saturation::either(detections, occurrences)),
1727 Saturation {
1728 reads: true,
1729 detections: true,
1730 occurrences: true,
1731 }
1732 );
1733 }
1734}