qrcode-barcode-scanner 0.12.2

QR code decoding and scannability scoring for artistic, AI-generated, and photo-captured QR codes
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
//! Decode engines — isolated wrappers around third-party decoders.
//!
//! Contract: engines NEVER panic outward (`catch_unwind` boundary), never
//! decide text (they report payload bytes + what they saw of the ECI
//! declarations; the interpretation happens once, in `content`), and only
//! report what they actually measured — no stubs.

pub(crate) mod charset;
pub(crate) mod content;
#[cfg(feature = "engine-rxing")]
mod databar_expanded;
pub(crate) mod locate;
#[cfg(feature = "engine-rxing")]
mod multi_reader;
pub(crate) mod occurrence;
pub(crate) mod reconcile;
#[cfg(feature = "engine-rqrr")]
mod rqrr_engine;
#[cfg(feature = "engine-rxing")]
mod rxing_engine;

use std::panic::{AssertUnwindSafe, catch_unwind};

use crate::input::LumaImage;
use crate::report::{EcLevel, EngineKind, Point, Symbology};
use crate::rescue::bitstream::PortRead;
use content::{ContentKey, EciEvidence, EngineReading, Fnc1, Segments};
use locate::{LocateHint, Located};

/// Still-masked codeword bitstream as the engine sampled it (rqrr only) —
/// feeds the synthetic UEC.
#[derive(Debug, Clone)]
pub(crate) struct MaskedStream {
    /// Packed bits, MSB-first per byte.
    pub bits: Vec<u8>,
    /// Stream length in bits.
    pub bit_len: usize,
}

/// What an engine actually measured — no stubs, `None` means "not provided".
#[derive(Debug, Clone)]
pub(crate) struct RawDetection {
    /// Symbology the engine read this as.
    pub symbology: Symbology,
    /// Payload bytes. QR family: the ORIGINAL bytes, ECI designators
    /// excluded, whichever engine read them — never engine text re-encoded.
    pub raw: Vec<u8>,
    /// What the observation saw of the ECI declarations governing `raw`
    /// (QR family; `Unobserved` elsewhere).
    pub eci: EciEvidence,
    /// Raw sampled bitstream when the engine exposes it (rqrr).
    pub masked_stream: Option<MaskedStream>,
    /// Symbol corners when the engine provides true bounds (rqrr).
    pub corners: Option<[Point; 4]>,
    /// Symbol version 1-40 when measured.
    pub version: Option<u8>,
    /// Error-correction level when measured.
    pub ec: Option<EcLevel>,
    /// Mask pattern 0-7 when measured.
    pub mask: Option<u8>,
    /// The FNC1 position the read observed. First = GS1 formatted data (QR
    /// `]Q3`/`]Q4` · `DataMatrix` `]d2` · GS1-128 `]C1`); second = an AIM
    /// application, never GS1. rqrr cannot decode FNC1 symbols at all (its
    /// mode dispatch rejects indicators 0x5/0x9); rxing and the rescue
    /// parser can.
    pub fnc1: Fnc1,
    /// The scanner's own segment parser read this stream (an rqrr decode's
    /// re-derivation, rxing's codeword output, the rescue): its ECI and
    /// FNC1 account is exposed, not stated by an engine. A refusal withholds
    /// only reads that are not parsed — equal bytes from a parsed stream
    /// belong to another, well-formed symbol.
    pub parsed: bool,
    /// Producing engine.
    pub engine: EngineKind,
    /// The Kanji/Hanzi segments the scanner's parse observed (`NotObserved`
    /// when no parse read the stream).
    pub segments: Segments,
    /// The engine's own mode-aware reading of a QR-family port read
    /// (spec/01 rule 1e); `None` elsewhere.
    pub engine_reading: EngineReading,
    /// The corner points of the symbol the read came from — never
    /// published, they keep the reads of different symbols apart: rxing's
    /// QR-family result points, rqrr's grid bounds. Attempt space here.
    pub location: Option<[Point; 4]>,
    /// Measured outer corners of a decoded matrix symbol, in attempt space.
    /// Internal exclusion evidence only: never inferred from three finder
    /// centres and never substituted for published/scored geometry.
    pub matrix_region: Option<[Point; 4]>,
    /// What the reader measured of the symbol's footprint, in attempt
    /// space, before validation (`occurrence` module doc) — the published
    /// occurrence geometry, independent of `corners` and `location`.
    pub footprint: occurrence::Footprint,
    /// What the re-read needs, when it may run for this read: a port read
    /// whose modifier leaves its declarations unverified, an rqrr read whose
    /// grid decided nothing. Attempt space.
    pub locate: Option<LocateHint>,
    /// The walk publishes this read only once a read at an independent scale
    /// confirms it (07-pipeline § Acceptance): a symbology the readers invent
    /// from module noise, its payload guarded by a check digit or a checksum
    /// alone (UPC-E, `DataBar`, `DataBar` Expanded), or a PDF417 symbol at
    /// error-correction level 0 or 1 (two or four EC codewords) or at no
    /// stated level. Set by the rxing adapter only.
    pub needs_confirmation: bool,
    /// The correction margin of the read's own received word, when the
    /// scanner error-corrected that word itself (the rqrr adapter's
    /// re-derivation); `Unknown` otherwise — an rxing read gets one only from
    /// a re-read that locates it.
    pub margin: crate::rescue::Margin,
}

/// The content rxing's zxing-cpp port reports for a stream: its bytes, a
/// designator signalled iff the port read one, its FNC1 position.
pub(crate) fn port_key(read: PortRead) -> ContentKey {
    ContentKey {
        raw: read.bytes,
        eci: if read.signalled {
            EciEvidence::Signalled
        } else {
            EciEvidence::NoEci
        },
        fnc1: read.fnc1,
    }
}

/// One refused QR stream (ISO 18004 defines no symbol for it), the names it
/// withholds by and where it was refused (07-pipeline property 6
/// § Refusal). A refusal is a content, never bytes alone: a well-formed
/// symbol with equal bytes is another content and keeps its reads; and it
/// is a place: only reads lying inside the refused symbol are withheld. The
/// walk keeps one record per stream and names, wherever it is refused
/// (`reconcile::ReadStore::refuse`) — never compared whole: the place is a
/// rescaled measurement.
#[derive(Debug, Clone)]
pub(crate) struct Refusal {
    /// What rxing's port reports for the stream ([`port_key`]): withholds
    /// the unparsed QR Code reads whose account matches.
    pub port: Option<ContentKey>,
    /// The bytes rqrr decoded from the stream (its own conversion):
    /// withholds unparsed rqrr reads of them, nothing else.
    pub rqrr: Option<Vec<u8>>,
    /// Where the refused symbol is: its grid's corners, or the refused
    /// read's points (attempt space until the ladder rescales it).
    pub place: Option<[Point; 4]>,
}

impl Refusal {
    /// A refused stream's record; `None` when it names nothing to withhold.
    pub(crate) fn new(
        port: Option<PortRead>,
        rqrr: Option<Vec<u8>>,
        place: Option<[Point; 4]>,
    ) -> Option<Self> {
        (port.is_some() || rqrr.is_some()).then(|| Self {
            port: port.map(port_key),
            rqrr,
            place,
        })
    }
}

/// The re-read of one read in its attempt image, under its own panic
/// boundary: a panic is a re-read that could not verify (no engine ran, so
/// nothing is tallied).
pub(crate) fn reread(img: &LumaImage, hint: &LocateHint, payload: &[u8]) -> Located {
    run_isolated(|| locate::locate(img, hint, payload)).unwrap_or(Located::Unverified)
}

/// Aggregated result of one pass over all enabled engines.
#[derive(Debug, Clone, Default)]
pub(crate) struct EngineOutcome {
    /// Every detection from every engine (deduplication is the ladder's job).
    pub detections: Vec<RawDetection>,
    /// Grids detected but NOT decoded (rqrr `get_raw_data` ok, RS failed) —
    /// the S5 rescue inputs. Corners are in ATTEMPT space here.
    pub rescue: Vec<crate::rescue::RescueCandidate>,
    /// QR streams proven malformed in this pass: decodes the rqrr adapter
    /// refused because their own grid parses malformed. The ladder withholds
    /// the reads they cover.
    pub refused: Vec<Refusal>,
    /// Engine panics caught and isolated during this pass. NOTE: isolation
    /// stops the unwind, but the process-global panic HOOK still runs first
    /// — server embedders see a backtrace on stderr per caught panic
    /// (suppress via `std::panic::set_hook` in the application if needed;
    /// a library must not touch the global hook).
    pub panics: u8,
}

#[cfg(test)]
impl RawDetection {
    /// A QR Code read with nothing measured but its content.
    pub(crate) fn qr(raw: &[u8], eci: EciEvidence, fnc1: Fnc1, engine: EngineKind) -> Self {
        Self {
            symbology: Symbology::QrCode,
            raw: raw.to_vec(),
            eci,
            masked_stream: None,
            corners: None,
            version: None,
            ec: None,
            mask: None,
            fnc1,
            parsed: false,
            engine,
            segments: Segments::NotObserved,
            engine_reading: EngineReading::None,
            location: None,
            matrix_region: None,
            footprint: occurrence::Footprint::unavailable(),
            locate: None,
            needs_confirmation: false,
            margin: crate::rescue::Margin::Unknown,
        }
    }
}

/// Run a closure with a panic boundary. `None` = the closure panicked.
fn run_isolated<T>(f: impl FnOnce() -> T) -> Option<T> {
    catch_unwind(AssertUnwindSafe(f)).ok()
}

/// Run one engine pass under the panic boundary, tallying an isolated panic
/// into `panics`. `None` = the engine panicked (already counted). This is the
/// single place `EngineOutcome::panics` is incremented, so the two engine call
/// sites cannot drift on how — or whether — a caught panic is recorded.
fn run_engine<T>(panics: &mut u8, engine: impl FnOnce() -> T) -> Option<T> {
    let outcome = run_isolated(engine);
    if outcome.is_none() {
        // a caught panic is isolated but counted — the ladder surfaces the
        // running tally as `PipelineTrace::engine_panics`.
        *panics += 1;
    }
    outcome
}

#[cfg(all(test, feature = "engine-rxing"))]
thread_local! {
    /// Test-only: while `Some`, the rxing pass of every single-symbology
    /// decode (score cells, envelope probes) panics inside the engine
    /// boundary — the real catch-and-tally path, no decoder bug needed —
    /// and the injected panics are counted here.
    pub(crate) static PROBE_PANICS: std::cell::Cell<Option<u32>> =
        const { std::cell::Cell::new(None) };
}

/// Test-only: the injected panic of [`PROBE_PANICS`].
#[cfg(all(test, feature = "engine-rxing"))]
fn inject_probe_panic(filter: FormatFilter) {
    if !matches!(filter, FormatFilter::Only(_)) {
        return;
    }
    if let Some(count) = PROBE_PANICS.with(std::cell::Cell::get) {
        PROBE_PANICS.with(|injected| injected.set(Some(count + 1)));
        panic!("injected decoder panic");
    }
}

/// Which symbologies a decode pass tries — the cost lever: every extra
/// format family is another detector walking the image.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum FormatFilter {
    /// Everything rxing supports + rqrr.
    All,
    /// Every non-QR family: complete their native-resolution read after a
    /// QR succeeds on a downscaled pyramid image. Narrow bars and small
    /// matrix modules can both disappear in that downscale.
    #[cfg(feature = "engine-rxing")]
    NonQr,
    /// QR · Micro QR · rMQR (+ rqrr) — the artistic-recovery stages are
    /// QR-calibrated; paying the 1D/PDF417/DataMatrix detectors on every
    /// deep rung starves the budget for nothing.
    QrFamily,
    /// Exactly one symbology — the scoring fast path (30 stress cells ×
    /// every decoder is 1× vs ~5× scan cost, and a cross-symbology text
    /// match would be a false survival signal anyway).
    Only(Symbology),
    /// The symbologies the caller asked for (`ScanConfig::formats`), or the
    /// part of them a stage reads: never empty.
    Set(Formats),
}

/// A set of symbologies: what a scan restricted with `ScanConfig::formats`
/// looks for.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Formats(u32);

impl Formats {
    /// Every symbology the QR-family stages read.
    const QR_FAMILY: [Symbology; 3] = [
        Symbology::QrCode,
        Symbology::MicroQrCode,
        Symbology::RectangularMicroQrCode,
    ];

    fn bit(symbology: Symbology) -> u32 {
        1 << (symbology as u32)
    }

    /// The set of `list`; a symbology listed twice is in it once.
    pub(crate) fn of(list: &[Symbology]) -> Self {
        Self(list.iter().fold(0, |set, s| set | Self::bit(*s)))
    }

    pub(crate) fn contains(self, symbology: Symbology) -> bool {
        self.0 & Self::bit(symbology) != 0
    }

    pub(crate) fn is_empty(self) -> bool {
        self.0 == 0
    }

    /// Its QR-family members.
    pub(crate) fn qr_family(self) -> Self {
        Self(self.0 & Self::of(&Self::QR_FAMILY).0)
    }

    /// Its members outside the QR family.
    #[cfg(feature = "engine-rxing")]
    pub(crate) fn non_qr(self) -> Self {
        Self(self.0 & !Self::of(&Self::QR_FAMILY).0)
    }
}

/// One decode pass: every enabled engine, all symbologies.
#[cfg(test)]
pub(crate) fn decode_all(luma: &LumaImage) -> EngineOutcome {
    decode_filtered(luma, FormatFilter::All)
}

/// Decode under a format filter.
pub(crate) fn decode_filtered(luma: &LumaImage, filter: FormatFilter) -> EngineOutcome {
    let mut outcome = EngineOutcome::default();

    #[cfg(feature = "engine-rxing")]
    if let Some(found) = run_engine(&mut outcome.panics, || {
        #[cfg(test)]
        inject_probe_panic(filter);
        rxing_engine::decode(luma, filter)
    }) {
        outcome.detections.extend(found);
    }

    // a single-symbology pass (score cells, envelope probes) discards the
    // rescue candidates: their orientation is never worth an RS there
    #[cfg(feature = "engine-rqrr")]
    if (matches!(
        filter,
        FormatFilter::All | FormatFilter::QrFamily | FormatFilter::Only(Symbology::QrCode)
    ) || matches!(filter, FormatFilter::Set(set) if set.contains(Symbology::QrCode)))
        && let Some(pass) = run_engine(&mut outcome.panics, || {
            rqrr_engine::decode(luma, !matches!(filter, FormatFilter::Only(_)))
        })
    {
        outcome.detections.extend(pass.found);
        outcome.rescue.extend(pass.rescue);
        outcome.refused.extend(pass.refused);
    }

    outcome
}

/// What one reader answered a probe ([`probe`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) struct Probe {
    /// The reader made a read the caller accepts.
    pub(crate) accepted: bool,
    /// Decoder panics caught in the pass.
    pub(crate) panics: u8,
}

/// The readers of a pass restricted to `symbology` — those of
/// `decode_filtered(luma, FormatFilter::Only(symbology))`: rxing for every
/// symbology, rqrr beside it for QR Code.
pub(crate) fn probe_readers(symbology: Symbology) -> &'static [EngineKind] {
    if symbology == Symbology::QrCode {
        &[EngineKind::Rxing, EngineKind::Rqrr]
    } else {
        &[EngineKind::Rxing]
    }
}

/// Whether `reader`'s pass restricted to `symbology` makes a read `admits`
/// accepts — one reader's share of the question a score cell or an envelope
/// probe asks, which keeps nothing else of the pass. Over
/// [`probe_readers`] the answer is that of
/// `decode_filtered(luma, FormatFilter::Only(symbology))`: a read one of
/// them makes is accepted or none is. Only the work differs: the caller
/// picks the order and stops at the first accepted read, and rxing's pass
/// ends at that read. A reader the build lacks, or one that does not read
/// `symbology`, accepts nothing; a decoder panic is caught, counted, and a
/// read not made.
pub(crate) fn probe(
    luma: &LumaImage,
    symbology: Symbology,
    reader: EngineKind,
    admits: &dyn Fn(&RawDetection) -> bool,
) -> Probe {
    let mut panics = 0u8;
    let accepted = match reader {
        #[cfg(feature = "engine-rxing")]
        EngineKind::Rxing => run_engine(&mut panics, || {
            #[cfg(test)]
            inject_probe_panic(FormatFilter::Only(symbology));
            rxing_engine::probe(luma, symbology, admits)
        }),
        // rqrr reads QR Code alone; a probe keeps no rescue candidate, so
        // none is oriented (`rqrr_engine::decode`)
        #[cfg(feature = "engine-rqrr")]
        EngineKind::Rqrr if symbology == Symbology::QrCode => run_engine(&mut panics, || {
            rqrr_engine::decode(luma, false).found.iter().any(admits)
        }),
        _ => None,
    };
    Probe {
        accepted: accepted == Some(true),
        panics,
    }
}

#[cfg(test)]
mod tests {
    #![allow(clippy::unwrap_used, clippy::expect_used, clippy::cast_precision_loss)]

    use super::*;
    use crate::input::LumaImage;
    use crate::report::{Charset, EcLevel, EngineKind};

    /// Render a QR to luma bytes module-by-module (no image-crate coupling):
    /// `scale` px per module + 4-module quiet zone. Returns the symbol version.
    fn qr_luma(content: &[u8], ec: qrcode::EcLevel, scale: u32) -> (LumaImage, u8) {
        let code = qrcode::QrCode::with_error_correction_level(content, ec).unwrap();
        let modules = code.width();
        let colors = code.to_colors();
        let qz = 4u32;
        let side = (u32::try_from(modules).unwrap() + 2 * qz) * scale;
        let mut data = vec![255u8; (side * side) as usize];
        for my in 0..modules {
            for mx in 0..modules {
                if colors[my * modules + mx] == qrcode::Color::Dark {
                    for dy in 0..scale {
                        for dx in 0..scale {
                            let x = (u32::try_from(mx).unwrap() + qz) * scale + dx;
                            let y = (u32::try_from(my).unwrap() + qz) * scale + dy;
                            data[(y * side + x) as usize] = 0;
                        }
                    }
                }
            }
        }
        let version = match code.version() {
            qrcode::Version::Normal(v) => u8::try_from(v).unwrap(),
            qrcode::Version::Micro(_) => 0,
        };
        (LumaImage::new(data, side, side), version)
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn rxing_decodes_utf8_qr_with_text_and_ec() {
        let payload = "héllo → 🦋";
        let (luma, _) = qr_luma(payload.as_bytes(), qrcode::EcLevel::Q, 4);
        let outcome = decode_all(&luma);
        let d = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rxing)
            .expect("rxing must decode a clean generated QR");
        let (text, _) = charset::resolve(&d.raw);
        assert_eq!(text, payload);
        assert_eq!(d.raw, payload.as_bytes());
        assert_eq!(d.ec, Some(EcLevel::Q));
        assert_eq!(outcome.panics, 0);
    }

    #[cfg(feature = "engine-rqrr")]
    #[test]
    fn a_reader_probed_for_a_symbology_it_does_not_read_accepts_nothing() {
        // rqrr reads QR Code alone: probed for another symbology over a QR
        // Code it reads, it makes no pass
        let (luma, _) = qr_luma(b"read by rqrr", qrcode::EcLevel::M, 6);
        let any = |_: &RawDetection| true;
        assert!(
            probe(&luma, Symbology::QrCode, EngineKind::Rqrr, &any).accepted,
            "precondition: rqrr reads the symbol"
        );
        for symbology in [
            Symbology::MicroQrCode,
            Symbology::DataMatrix,
            Symbology::Code128,
        ] {
            let made = probe(&luma, symbology, EngineKind::Rqrr, &any);
            assert!(!made.accepted, "{symbology:?}");
            assert_eq!(made.panics, 0, "{symbology:?}");
        }
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn non_qr_completion_does_not_repeat_either_qr_engine() {
        let (luma, _) = qr_luma(b"already read by the pyramid", qrcode::EcLevel::M, 6);
        let outcome = decode_filtered(&luma, FormatFilter::NonQr);
        assert!(outcome.detections.is_empty());
        assert!(outcome.rescue.is_empty());
        assert!(outcome.refused.is_empty());
        assert_eq!(outcome.panics, 0);
    }

    #[cfg(feature = "engine-rqrr")]
    #[test]
    fn rqrr_provides_geometry_version_ec_mask() {
        let (luma, version) = qr_luma(b"https://qrcode-ai.com/scan", qrcode::EcLevel::Q, 4);
        let outcome = decode_all(&luma);
        let d = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rqrr)
            .expect("rqrr must decode a clean generated QR");
        assert_eq!(d.version, Some(version));
        assert_eq!(d.ec, Some(EcLevel::Q), "rqrr ecc_level 0-3 mapping");
        let mask = d.mask.expect("rqrr reports the mask");
        assert!(mask <= 7, "mask {mask}");
        let corners = d.corners.expect("rqrr reports bounds");
        let side = luma.width() as f32;
        for p in corners {
            assert!(
                p.x >= 0.0 && p.x < side && p.y >= 0.0 && p.y < side,
                "{p:?}"
            );
        }
    }

    #[cfg(feature = "engine-rqrr")]
    #[test]
    fn rqrr_ec_mapping_pinned_on_l_too() {
        let (luma, _) = qr_luma(b"ec level L pin", qrcode::EcLevel::L, 4);
        let outcome = decode_all(&luma);
        let d = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rqrr)
            .expect("decode");
        assert_eq!(d.ec, Some(EcLevel::L));
    }

    #[cfg(all(feature = "engine-rxing", feature = "engine-rqrr"))]
    #[test]
    fn engines_agree_on_raw_payload_bytes() {
        let payload = "parity check 1234";
        let (luma, _) = qr_luma(payload.as_bytes(), qrcode::EcLevel::M, 4);
        let outcome = decode_all(&luma);
        let rxing_raw = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rxing)
            .map(|d| d.raw.clone())
            .expect("rxing");
        let rqrr_raw = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rqrr)
            .map(|d| d.raw.clone())
            .expect("rqrr");
        assert_eq!(rxing_raw, rqrr_raw);
        assert_eq!(rxing_raw, payload.as_bytes());
    }

    #[cfg(feature = "engine-rqrr")]
    #[test]
    fn latin1_byte_mode_payload_resolves_via_raw_path() {
        // "Éé" in windows-1252 — invalid UTF-8, the rqrr decode() trap case.
        let (luma, _) = qr_luma(&[0xC9, 0xE9], qrcode::EcLevel::M, 4);
        let outcome = decode_all(&luma);
        let d = outcome
            .detections
            .iter()
            .find(|d| d.engine == EngineKind::Rqrr)
            .expect("rqrr must decode byte-mode latin1");
        assert_eq!(d.raw, vec![0xC9, 0xE9]);
        let (text, cs) = charset::resolve(&d.raw);
        assert_eq!(text, "Éé");
        assert_eq!(cs, Charset::Latin1);
    }

    #[test]
    fn charset_resolution_order_utf8_sjis_latin1() {
        let (t, c) = charset::resolve("plain ascii".as_bytes());
        assert_eq!((t.as_str(), c), ("plain ascii", Charset::Utf8));

        let (t, c) = charset::resolve("héllo🦋".as_bytes());
        assert_eq!((t.as_str(), c), ("héllo🦋", Charset::Utf8));

        // こんにちは in Shift-JIS
        let sjis: &[u8] = &[0x82, 0xB1, 0x82, 0xF1, 0x82, 0xC9, 0x82, 0xBF, 0x82, 0xCD];
        let (t, c) = charset::resolve(sjis);
        assert_eq!((t.as_str(), c), ("こんにちは", Charset::ShiftJis));

        let (t, c) = charset::resolve(&[0xC9, 0xE9]);
        assert_eq!((t.as_str(), c), ("Éé", Charset::Latin1));
    }

    #[cfg(all(feature = "engine-rxing", feature = "engine-rqrr"))]
    #[test]
    fn stress_cells_match_by_content_key_not_by_text() {
        // A stress cell survives when an engine hit carries the scored
        // CONTENT. Every hit of an ECI-4 [A1] symbol — clean, rotated,
        // blurred, from either engine, located or only signalled — is
        // admitted by the detection's key, while its heuristic text ('¡')
        // differs from the detection's ('Ą'), and an unmarked [A1] hit is
        // refused. (The cell matcher compares `ContentKey::admits`.)
        let symbol = |eci: bool| {
            crate::rescue::test_symbols::from_segments(
                qrcode::Version::Normal(3),
                qrcode::EcLevel::M,
                |b| {
                    if eci {
                        b.push_eci_designator(4)?;
                    }
                    b.push_byte_data(&[0xA1])
                },
            )
        };
        let key = content::ContentKey {
            raw: vec![0xA1],
            eci: EciEvidence::Located(vec![content::EciMark { value: 4, start: 0 }]),
            fnc1: Fnc1::None,
        };
        let reading = content::read(
            &key.raw,
            &key.eci,
            &Segments::NotObserved,
            EngineReading::None,
            true,
        );
        assert_eq!(reading.text, "\u{104}");
        let luma = symbol(true);
        let cells = [
            luma.clone(),
            crate::score::warp::rotate(&luma, 20.0),
            crate::transform::gaussian_blur(&luma, 1.5),
        ];
        for (i, cell) in cells.iter().enumerate() {
            let outcome = decode_filtered(cell, FormatFilter::Only(Symbology::QrCode));
            assert!(!outcome.detections.is_empty(), "cell {i} decodes");
            for d in &outcome.detections {
                assert!(key.admits(d), "cell {i} {:?}: {:?}", d.engine, d.eci);
                assert_eq!(charset::resolve(&d.raw).0, "¡");
            }
        }
        let unmarked = decode_filtered(&symbol(false), FormatFilter::Only(Symbology::QrCode));
        assert!(!unmarked.detections.is_empty());
        assert!(unmarked.detections.iter().all(|d| !key.admits(d)));
    }

    #[test]
    fn panics_are_isolated_not_propagated() {
        let caught: Option<u8> = run_isolated(|| panic!("engine exploded"));
        assert!(caught.is_none());
        let fine = run_isolated(|| 7u8);
        assert_eq!(fine, Some(7));
    }

    #[test]
    fn run_engine_tallies_each_isolated_panic_by_exactly_one() {
        // Pins the `EngineOutcome::panics` counter that `decode_filtered`
        // threads for both engines (mod.rs `*panics += 1`). Traps the shard-0
        // survivors: `+=` → `-=` (0u8 - 1 underflows → the pass panics, the
        // isolation contract broken) and `+=` → `*=` (0 * 1 stays 0, a caught
        // panic goes unrecorded). A clean pass must NOT touch the counter, and
        // a second panic must ACCUMULATE — pinning `+=` (not `=`) and step 1.
        let mut panics = 0u8;

        let ok = run_engine(&mut panics, || 7u8);
        assert_eq!(ok, Some(7), "a surviving engine returns its value");
        assert_eq!(panics, 0, "a clean pass tallies nothing");

        let boom: Option<u8> = run_engine(&mut panics, || panic!("engine exploded"));
        assert!(boom.is_none(), "an isolated panic yields None");
        assert_eq!(panics, 1, "one caught panic is exactly one tally");

        let again: Option<u8> = run_engine(&mut panics, || panic!("engine exploded again"));
        assert!(again.is_none());
        assert_eq!(panics, 2, "a second caught panic accumulates (+=, not =)");
    }

    #[test]
    fn a_refusal_names_the_port_content_and_rqrrs_bytes() {
        // ECI 1000000 + "abc": the port signals a designator
        let signalled = PortRead {
            bytes: b"abc".to_vec(),
            signalled: true,
            fnc1: Fnc1::None,
        };
        assert_eq!(
            port_key(signalled.clone()),
            ContentKey {
                raw: b"abc".to_vec(),
                eci: EciEvidence::Signalled,
                fnc1: Fnc1::None,
            }
        );
        let plain = PortRead {
            signalled: false,
            fnc1: Fnc1::Second,
            ..signalled.clone()
        };
        assert_eq!(port_key(plain).eci, EciEvidence::NoEci);
        // one record per stream, both names; nothing named, no record
        let place = Some([Point { x: 0.0, y: 0.0 }; 4]);
        let refusal = Refusal::new(Some(signalled), Some(b"abc".to_vec()), place)
            .expect("names to withhold by");
        assert_eq!(refusal.rqrr.as_deref(), Some(&b"abc"[..]));
        assert_eq!(refusal.place, place);
        assert!(Refusal::new(None, None, place).is_none());
    }

    // ── footprint coordinates (spec/01 § Occurrences) ───────────────────
    //
    // Edge convention: pixel (i, j) spans [i, i+1) × [j, j+1). The truth
    // comes from the pixels of clean renders (two grey levels, whole-pixel
    // modules), never from a reader.

    /// The validated footprints every engine measures on `luma`.
    #[cfg(feature = "engine-rxing")]
    fn footprints(luma: &LumaImage) -> Vec<(EngineKind, Symbology, occurrence::Footprint)> {
        decode_all(luma)
            .detections
            .into_iter()
            .map(|d| {
                let footprint = d.footprint.validated((luma.width(), luma.height()));
                (d.engine, d.symbology, footprint)
            })
            .collect()
    }

    /// A committed fixture as luma, turned clockwise by `quarters` quarter
    /// turns.
    #[cfg(feature = "engine-rxing")]
    fn turned(bytes: &[u8], quarters: u8) -> LumaImage {
        let image = image::load_from_memory(bytes).unwrap().to_luma8();
        let image = match quarters % 4 {
            0 => image,
            1 => image::imageops::rotate90(&image),
            2 => image::imageops::rotate180(&image),
            _ => image::imageops::rotate270(&image),
        };
        let (width, height) = image.dimensions();
        LumaImage::new(image.into_raw(), width, height)
    }

    /// `luma` mirrored left to right when `turn` ≥ 4, then turned clockwise
    /// `turn % 4` quarter turns — with the motion of a point (pixel edges
    /// at integers) under the same transformation.
    #[cfg(all(feature = "engine-rxing", feature = "engine-rqrr"))]
    fn oriented(luma: &LumaImage, turn: u8) -> (LumaImage, impl Fn((f32, f32)) -> (f32, f32)) {
        let (width, height) = (luma.width(), luma.height());
        let image = image::GrayImage::from_raw(width, height, luma.data().to_vec()).unwrap();
        let image = if turn >= 4 {
            image::imageops::flip_horizontal(&image)
        } else {
            image
        };
        let image = match turn % 4 {
            0 => image,
            1 => image::imageops::rotate90(&image),
            2 => image::imageops::rotate180(&image),
            _ => image::imageops::rotate270(&image),
        };
        let (w, h) = (width as f32, height as f32);
        let motion = move |(x, y): (f32, f32)| {
            let x = if turn >= 4 { w - x } else { x };
            match turn % 4 {
                0 => (x, y),
                1 => (h - y, x),
                2 => (w - x, h - y),
                _ => (y, w - x),
            }
        };
        let (width, height) = image.dimensions();
        (LumaImage::new(image.into_raw(), width, height), motion)
    }

    #[cfg(all(feature = "engine-rxing", feature = "engine-rqrr"))]
    #[test]
    fn qr_quads_are_the_symbols_outer_corners_from_either_engine_in_every_orientation() {
        // the corners clockwise from the symbol's origin (module (0,0)), in
        // all eight orientations: rqrr's anchor is undone (rqrr_anchor), rxing
        // needs nothing
        for scale in [3u32, 4, 5, 6, 7, 8, 11] {
            for content in [&b"PROBE"[..], b"https://qrc-ai.com/occurrence-probe-longer"] {
                let code = qrcode::QrCode::with_error_correction_level(content, qrcode::EcLevel::M)
                    .unwrap();
                let (upright, _) = qr_luma(content, qrcode::EcLevel::M, scale);
                let edge = (4 * scale) as f32;
                let far = edge + (u32::try_from(code.width()).unwrap() * scale) as f32;
                for turn in 0..8u8 {
                    let (luma, motion) = oriented(&upright, turn);
                    let corners = [(edge, edge), (far, edge), (far, far), (edge, far)].map(&motion);
                    let want = if turn >= 4 {
                        [corners[0], corners[3], corners[2], corners[1]]
                    } else {
                        corners
                    };
                    let mut measured = Vec::new();
                    for (engine, _, footprint) in footprints(&luma) {
                        if footprint.kind != occurrence::Kind::Quad {
                            continue;
                        }
                        for (got, (x, y)) in footprint.points.iter().zip(want) {
                            assert!(
                                (got.x - x).abs() <= 0.01 && (got.y - y).abs() <= 0.01,
                                "scale {scale} turn {turn} {engine:?}: {:?} vs {want:?}",
                                footprint.points
                            );
                        }
                        measured.push(engine);
                    }
                    assert!(
                        measured.contains(&EngineKind::Rxing)
                            && measured.contains(&EngineKind::Rqrr),
                        "scale {scale} turn {turn}: {measured:?}"
                    );
                }
            }
        }
    }

    /// Whether `c` is the centre of a pixel row or column.
    #[cfg(feature = "engine-rxing")]
    fn on_centre(c: f32) -> bool {
        (c - c.floor() - 0.5).abs() < 1e-4
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn linear_reads_are_measured_on_their_patterns_upright_reversed_and_rotated() {
        // Code 128 `STOCK-4827`, 498 × 310, 3 px modules from x = 48 to 450:
        // rxing measures the centre of the start pattern (48 + 5.5 modules)
        // and of the stop character's first eleven modules (450 - 7.5
        // modules), on the centre of the row it read. Turned a quarter, a
        // half or three quarters, the same pixels move with the image: the
        // reversed (180), rotated (270) and both (90) readings
        const CODE128: &[u8] =
            include_bytes!("../../../../fixtures/symbology/code128-stock-4827.png");
        // EAN-13, 3 px modules: the guard centres, [17, 26) and [293, 302)
        const EAN13: &[u8] = include_bytes!("../../../../fixtures/symbology/ean13.png");
        let width = 498.0_f32;
        let along = [64.5_f32, 427.5];
        for quarters in 0..4u8 {
            let luma = turned(CODE128, quarters);
            let reads: Vec<_> = footprints(&luma)
                .into_iter()
                .filter(|(_, symbology, _)| *symbology == Symbology::Code128)
                .collect();
            assert!(!reads.is_empty(), "turn {quarters}");
            let want = if quarters < 2 {
                along
            } else {
                [width - along[1], width - along[0]]
            };
            for (_, _, footprint) in reads {
                assert_eq!(footprint.kind, occurrence::Kind::Segment, "turn {quarters}");
                let [a, b] = [footprint.points[0], footprint.points[1]];
                // published in x, then y order
                let (measured, across) = if quarters % 2 == 0 {
                    ([a.x, b.x], [a.y, b.y])
                } else {
                    ([a.y, b.y], [a.x, b.x])
                };
                assert!(
                    (measured[0] - want[0]).abs() <= 0.01 && (measured[1] - want[1]).abs() <= 0.01,
                    "turn {quarters}: {footprint:?}, along {want:?}"
                );
                assert!(
                    (across[0] - across[1]).abs() < 1e-4 && on_centre(across[0]),
                    "turn {quarters}: one scan line on a pixel centre: {footprint:?}"
                );
            }
        }
        let luma = turned(EAN13, 0);
        let reads: Vec<_> = footprints(&luma)
            .into_iter()
            .filter(|(_, symbology, _)| *symbology == Symbology::Ean13)
            .collect();
        assert!(!reads.is_empty(), "the EAN-13 fixture reads");
        for (_, _, footprint) in reads {
            assert_eq!(footprint.kind, occurrence::Kind::Segment);
            let [a, b] = [footprint.points[0], footprint.points[1]];
            assert!(
                (a.x - 21.5).abs() <= 0.01 && (b.x - 297.5).abs() <= 0.01,
                "{footprint:?}"
            );
            assert!((a.y - b.y).abs() < 1e-4 && on_centre(a.y), "{footprint:?}");
        }
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn micro_and_rectangular_qr_quads_are_their_outer_corners_upright() {
        // the truth is the box of the dark pixels: a Micro QR's timing
        // patterns run to its right and bottom edges, an rMQR's along all four
        for (bytes, symbology) in [
            (
                &include_bytes!("../../../../fixtures/symbology/microqr.png")[..],
                Symbology::MicroQrCode,
            ),
            (
                &include_bytes!("../../../../fixtures/symbology/rmqr-url-kanji.png")[..],
                Symbology::RectangularMicroQrCode,
            ),
        ] {
            let luma = turned(bytes, 0);
            let (mut x0, mut y0, mut x1, mut y1) = (u32::MAX, u32::MAX, 0, 0);
            for row in 0..luma.height() {
                for column in 0..luma.width() {
                    if luma.data()[(row * luma.width() + column) as usize] < 128 {
                        (x0, y0) = (x0.min(column), y0.min(row));
                        (x1, y1) = (x1.max(column + 1), y1.max(row + 1));
                    }
                }
            }
            let want = [(x0, y0), (x1, y0), (x1, y1), (x0, y1)].map(|(x, y)| (x as f32, y as f32));
            let quads: Vec<_> = footprints(&luma)
                .into_iter()
                .filter(|(_, s, f)| *s == symbology && f.kind == occurrence::Kind::Quad)
                .collect();
            assert!(!quads.is_empty(), "{symbology:?}");
            for (_, _, footprint) in quads {
                for (got, (x, y)) in footprint.points.iter().zip(want) {
                    assert!(
                        (got.x - x).abs() <= 0.01 && (got.y - y).abs() <= 0.01,
                        "{symbology:?}: {:?} vs {want:?}",
                        footprint.points
                    );
                }
            }
        }
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn databar_finder_points_lie_on_bar_edges_upright_and_upside_down() {
        // a finder's points are the edges of its first and last elements:
        // where the colour of the row changes, read in either direction
        const DATABAR: &[u8] = include_bytes!("../../../../fixtures/symbology/databar-gtin.png");
        const EXPANDED: &[u8] =
            include_bytes!("../../../../fixtures/symbology/databar-expanded-bwipp-regression.png");
        for ((bytes, symbology), quarters) in [
            (DATABAR, Symbology::DataBar),
            (EXPANDED, Symbology::DataBarExpanded),
        ]
        .into_iter()
        .flat_map(|case| [(case, 0u8), (case, 2)])
        {
            let luma = turned(bytes, quarters);
            let reads: Vec<_> = footprints(&luma)
                .into_iter()
                .filter(|(_, s, _)| *s == symbology)
                .collect();
            assert!(!reads.is_empty(), "{symbology:?} turn {quarters}");
            let dark =
                |column: u32, row: u32| luma.data()[(row * luma.width() + column) as usize] < 128;
            for (_, _, footprint) in reads {
                assert_eq!(footprint.kind, occurrence::Kind::Partial, "turn {quarters}");
                for p in &footprint.points {
                    assert!(
                        on_centre(p.y) && p.x.fract().abs() < 1e-4,
                        "turn {quarters}: {p:?}"
                    );
                    #[expect(
                        clippy::cast_possible_truncation,
                        clippy::cast_sign_loss,
                        reason = "validated in-image coordinates"
                    )]
                    let (column, row) = (p.x as u32, p.y.floor() as u32);
                    assert!(
                        column > 0
                            && column < luma.width()
                            && dark(column - 1, row) != dark(column, row),
                        "turn {quarters}: {p:?} lies on no bar edge of {footprint:?}"
                    );
                }
            }
        }
    }

    #[cfg(feature = "engine-rxing")]
    #[test]
    fn matrix_quads_lie_within_a_module_of_the_symbols_corners() {
        /// A fixture, its symbology, the symbol's dark box and its module in
        /// pixels.
        type Case = (&'static [u8], Symbology, (f32, f32, f32, f32), f32);
        let cases: [Case; 3] = [
            (
                include_bytes!("../../../../fixtures/symbology/datamatrix.png"),
                Symbology::DataMatrix,
                (60.0, 60.0, 180.0, 180.0),
                6.0,
            ),
            (
                include_bytes!("../../../../fixtures/symbology/pdf417.png"),
                Symbology::Pdf417,
                (8.0, 8.0, 282.0, 64.0),
                2.0,
            ),
            (
                include_bytes!("../../../../fixtures/symbology/aztec.png"),
                Symbology::Aztec,
                (51.0, 51.0, 189.0, 189.0),
                6.0,
            ),
        ];
        for (bytes, symbology, (x0, y0, x1, y1), module) in cases {
            let luma = turned(bytes, 0);
            let quads: Vec<_> = footprints(&luma)
                .into_iter()
                .filter(|(_, s, f)| *s == symbology && f.kind == occurrence::Kind::Quad)
                .collect();
            assert!(!quads.is_empty(), "{symbology:?}");
            for (_, _, footprint) in quads {
                // clockwise; compare as a set of corners
                for corner in [(x0, y0), (x1, y0), (x1, y1), (x0, y1)] {
                    assert!(
                        footprint.points.iter().any(|p| {
                            (p.x - corner.0).abs() <= module && (p.y - corner.1).abs() <= module
                        }),
                        "{symbology:?}: no corner near {corner:?} in {footprint:?}"
                    );
                }
            }
        }
    }
}