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
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
//! rxing wrapper — the robustness engine (`ZXing` lineage + zxing-cpp detector).
//!
//! The luma helper defaults `TryHarder` on; we add `AlsoInverted`. rxing
//! tries two QR readers in turn and `getRawBytes()` means something
//! different for each (verified in the 0.9.1 and 0.9.3 sources):
//!
//! - its zxing-cpp port (the first try for every image — it runs its
//!   general finder-pattern detector unless `PureBarcode` is set — and the
//!   only Micro QR / rMQR reader): the ORIGINAL payload bytes, ECI
//!   designators excluded — exact, but the designators themselves are not
//!   exposed (only their presence, through the AIM modifier `]Q2`/`]Q4`/
//!   `]Q6`). A plain (`]Q1`) read of ASCII text carries that text's bytes,
//!   or a byte-order mark and the bytes rxing decoded the text from; a read
//!   that carries anything else is no payload of this reader and is
//!   refused;
//! - its `ZXing`-lineage reader (when the port fails): the RS-corrected
//!   data codewords — parsed here with the scanner's segment parser, and
//!   kept only when the parse's byte-mode segments are the reader's own.
//!
//! The decoded text is neither the payload nor the reading: content is
//! interpreted once, in `engine::content` (a port read's text only says
//! which complete double-byte decoding the engine chose, rule 1e). Version
//! and corners are NOT published from the QR paths — rqrr supplies
//! geometry; the result points stay internal (they tell symbols apart and
//! frame the re-read). Other symbologies carry the ISO/IEC 8859-1 bytes of
//! the engine's text when it fits, else its UTF-8 (spec/01 § raw), and the
//! FNC1 position their symbology identifier states. A `DataBar` read is a
//! GTIN-14 or nothing; the reads of the symbologies rxing invents from
//! noise (and of thinly protected PDF417 symbols) wait for confirmation at
//! an independent scale (07-pipeline § Acceptance).

use rxing::RXingResultMetadataType as MetaKey;
use rxing::RXingResultMetadataValue as MetaValue;

use super::RawDetection;
use super::content::{EciEvidence, EngineReading, Fnc1, Segments};
use super::locate::{Frame, LocateHint};
use super::occurrence::{Footprint, Kind};
use crate::input::LumaImage;
use crate::report::{EcLevel, EngineKind, Point, Symbology};
use crate::rescue::{Margin, bitstream};

/// rxing format → our wire symbology. `None` = formats we refuse to
/// publish unlabeled (extensions, unrecognized).
fn map_symbology(format: rxing::BarcodeFormat) -> Option<Symbology> {
    use rxing::BarcodeFormat as F;
    Some(match format {
        F::QR_CODE => Symbology::QrCode,
        F::MICRO_QR_CODE => Symbology::MicroQrCode,
        F::RECTANGULAR_MICRO_QR_CODE => Symbology::RectangularMicroQrCode,
        F::DATA_MATRIX => Symbology::DataMatrix,
        F::AZTEC => Symbology::Aztec,
        F::PDF_417 => Symbology::Pdf417,
        F::MAXICODE => Symbology::MaxiCode,
        F::EAN_13 => Symbology::Ean13,
        F::EAN_8 => Symbology::Ean8,
        F::UPC_A => Symbology::UpcA,
        F::UPC_E => Symbology::UpcE,
        F::CODE_128 => Symbology::Code128,
        F::CODE_39 => Symbology::Code39,
        F::CODE_93 => Symbology::Code93,
        F::CODABAR => Symbology::Codabar,
        F::ITF => Symbology::Itf,
        F::RSS_14 => Symbology::DataBar,
        F::RSS_EXPANDED => Symbology::DataBarExpanded,
        F::TELEPEN => Symbology::Telepen,
        // UPC_EAN_EXTENSION add-ons + UNSUPORTED_FORMAT: never published
        F::UPC_EAN_EXTENSION | F::DXFilmEdge | F::UNSUPORTED_FORMAT => return None,
    })
}

fn parse_ec(s: &str) -> Option<EcLevel> {
    match s {
        "L" => Some(EcLevel::L),
        "M" => Some(EcLevel::M),
        "Q" => Some(EcLevel::Q),
        "H" => Some(EcLevel::H),
        _ => None,
    }
}

/// Every symbology an rxing pass can be restricted to.
const SYMBOLOGIES: [Symbology; 19] = [
    Symbology::QrCode,
    Symbology::MicroQrCode,
    Symbology::RectangularMicroQrCode,
    Symbology::DataMatrix,
    Symbology::Aztec,
    Symbology::Pdf417,
    Symbology::MaxiCode,
    Symbology::Ean13,
    Symbology::Ean8,
    Symbology::UpcA,
    Symbology::UpcE,
    Symbology::Code128,
    Symbology::Code39,
    Symbology::Code93,
    Symbology::Codabar,
    Symbology::Itf,
    Symbology::DataBar,
    Symbology::DataBarExpanded,
    Symbology::Telepen,
];

/// The rxing format set of a caller's symbology set.
fn formats_of(set: super::Formats) -> std::collections::HashSet<rxing::BarcodeFormat> {
    SYMBOLOGIES
        .into_iter()
        .filter(|symbology| set.contains(*symbology))
        .flat_map(formats_for)
        .collect()
}

/// Our symbology → the rxing format set to restrict a pass to.
fn formats_for(only: Symbology) -> std::collections::HashSet<rxing::BarcodeFormat> {
    use rxing::BarcodeFormat as F;
    let format = match only {
        Symbology::QrCode => F::QR_CODE,
        Symbology::MicroQrCode => F::MICRO_QR_CODE,
        Symbology::RectangularMicroQrCode => F::RECTANGULAR_MICRO_QR_CODE,
        Symbology::DataMatrix => F::DATA_MATRIX,
        Symbology::Aztec => F::AZTEC,
        Symbology::Pdf417 => F::PDF_417,
        Symbology::MaxiCode => F::MAXICODE,
        Symbology::Ean13 => F::EAN_13,
        Symbology::Ean8 => F::EAN_8,
        Symbology::UpcA => F::UPC_A,
        Symbology::UpcE => F::UPC_E,
        Symbology::Code128 => F::CODE_128,
        Symbology::Code39 => F::CODE_39,
        Symbology::Code93 => F::CODE_93,
        Symbology::Codabar => F::CODABAR,
        Symbology::Itf => F::ITF,
        Symbology::DataBar => F::RSS_14,
        Symbology::DataBarExpanded => F::RSS_EXPANDED,
        Symbology::Telepen => F::TELEPEN,
    };
    std::collections::HashSet::from([format])
}

pub(super) fn decode(luma: &LumaImage, filter: super::FormatFilter) -> Vec<RawDetection> {
    decode_until(luma, filter, &|_| false)
}

/// Whether a pass restricted to `symbology` makes a read `admits` accepts.
/// The pass ends at the first such read ([`decode_until`]): the regions
/// around it are not searched, and the answer is the one the whole pass
/// would give (a read it filters out as a duplicate carries the content of
/// the read that replaces it).
pub(super) fn probe(
    luma: &LumaImage,
    symbology: Symbology,
    admits: &dyn Fn(&RawDetection) -> bool,
) -> bool {
    decode_until(luma, super::FormatFilter::Only(symbology), admits)
        .iter()
        .any(admits)
}

/// One rxing pass under `filter`, ended at the first read whose observation
/// `stop` accepts: that read is then the only one returned.
fn decode_until(
    luma: &LumaImage,
    filter: super::FormatFilter,
    stop: &dyn Fn(&RawDetection) -> bool,
) -> Vec<RawDetection> {
    use rxing::BarcodeFormat as F;
    let stop = |result: &rxing::RXingResult| observe(result).is_some_and(|read| stop(&read));
    let possible = match filter {
        super::FormatFilter::All => None,
        super::FormatFilter::NonQr => Some(std::collections::HashSet::from([
            F::DATA_MATRIX,
            F::AZTEC,
            F::PDF_417,
            F::MAXICODE,
            F::EAN_13,
            F::EAN_8,
            F::UPC_A,
            F::UPC_E,
            F::CODE_128,
            F::CODE_39,
            F::CODE_93,
            F::CODABAR,
            F::ITF,
            F::RSS_14,
            F::RSS_EXPANDED,
            F::TELEPEN,
        ])),
        super::FormatFilter::QrFamily => Some(std::collections::HashSet::from([
            F::QR_CODE,
            F::MICRO_QR_CODE,
            F::RECTANGULAR_MICRO_QR_CODE,
        ])),
        super::FormatFilter::Only(symbology) => {
            Some(formats_for(symbology)).filter(|set| !set.is_empty())
        }
        super::FormatFilter::Set(set) => Some(formats_of(set)),
    };
    // the dispatcher of the general pass runs the zxing-cpp port for QR Code
    // or Micro QR only: a set with rMQR and neither of them reads rMQR in
    // the pass of its own (`decode_rmqr`), after the general one
    let (general, rmqr_alone) = match filter {
        super::FormatFilter::Only(Symbology::RectangularMicroQrCode) => (false, true),
        super::FormatFilter::Set(set) => {
            let alone = set.contains(Symbology::RectangularMicroQrCode)
                && !set.contains(Symbology::QrCode)
                && !set.contains(Symbology::MicroQrCode);
            // a set of rMQR and nothing else leaves the general pass no
            // format to read
            (
                set != super::Formats::of(&[Symbology::RectangularMicroQrCode]),
                alone,
            )
        }
        _ => (true, false),
    };
    let expanded = match filter {
        super::FormatFilter::All
        | super::FormatFilter::NonQr
        | super::FormatFilter::Only(Symbology::DataBarExpanded) => true,
        super::FormatFilter::Set(set) => set.contains(Symbology::DataBarExpanded),
        _ => false,
    };
    // TryHarder defaults on in the helper; inverted symbols are real in the
    // artistic corpus — always on (a config knob nobody turns is debt).
    let mut hints = rxing::DecodeHints {
        AlsoInverted: Some(true),
        PossibleFormats: possible,
        ..Default::default()
    };

    let mut results = if general {
        decode_all(luma, &mut hints, &stop).unwrap_or_default()
    } else {
        Vec::new()
    };
    if rmqr_alone {
        let mut hints = rxing::DecodeHints {
            AlsoInverted: Some(true),
            PossibleFormats: Some(formats_for(Symbology::RectangularMicroQrCode)),
            ..Default::default()
        };
        results.extend(decode_rmqr(luma, &mut hints, &stop).unwrap_or_default());
    }
    if expanded
        && !results
            .iter()
            .any(|result| *result.getBarcodeFormat() == F::RSS_EXPANDED)
    {
        // The upstream reader can stop at an internal false finder. The
        // patched reader retains checksums, stacked rows and independent
        // confirmation; it only rejects incorrectly spaced finders.
        if let Ok(expanded) = decode_expanded(luma, &stop) {
            results.extend(expanded);
        }
    }
    results.iter().filter_map(observe).collect()
}

/// The binarized attempt image every rxing pass reads: the helper's hybrid
/// binarizer over the luma bytes.
fn bitmap(
    luma: &LumaImage,
) -> rxing::common::Result<
    rxing::BinaryBitmap<rxing::common::HybridBinarizer<rxing::Luma8LuminanceSource>>,
> {
    let source =
        rxing::Luma8LuminanceSource::new(luma.data().to_vec(), luma.width(), luma.height())?;
    Ok(rxing::BinaryBitmap::new(
        rxing::common::HybridBinarizer::new(source),
    ))
}

/// The unrestricted, family and single-format passes: the helper's reader
/// stack (`detect_multiple_in_luma_with_hints`, `TryHarder` on) as the
/// scanner's multiple reader runs it — the format dispatch in one fixed
/// order, every point in the image's frame, physically distinct copies of
/// one content kept (`multi_reader`).
fn decode_all(
    luma: &LumaImage,
    hints: &mut rxing::DecodeHints,
    stop: &dyn Fn(&rxing::RXingResult) -> bool,
) -> rxing::common::Result<Vec<rxing::RXingResult>> {
    hints.TryHarder = hints.TryHarder.or(Some(true));
    let mut image = bitmap(luma)?;
    let mut reader = super::multi_reader::FormatReader::default();
    super::multi_reader::decode_multiple(&mut reader, &mut image, hints, luma, stop)
}

fn decode_expanded(
    luma: &LumaImage,
    stop: &dyn Fn(&rxing::RXingResult) -> bool,
) -> rxing::common::Result<Vec<rxing::RXingResult>> {
    let mut image = bitmap(luma)?;
    // The patched reader reads only TryHarder; the ladder retries inverted images.
    let hints = rxing::DecodeHints {
        TryHarder: Some(true),
        ..Default::default()
    };
    let mut reader = super::databar_expanded::RSSExpandedReader::default();
    super::multi_reader::decode_multiple(&mut reader, &mut image, &hints, luma, stop)
}

/// The pass of an rMQR-only filter (score cells, envelope probes): the
/// helper's reader stack — the multiple-barcode reader over a hybrid
/// binarizer, `TryHarder` on — with the format dispatcher that sends rMQR
/// to the zxing-cpp port, the reader the unrestricted passes read rMQR
/// with. The multi-use dispatcher behind the helper has no rMQR arm in
/// rxing 0.9.1: restricted to that format it ran no reader at all, and
/// every cell of an rMQR read as failed. Restricted the same way, this
/// dispatcher runs the port alone, for rMQR alone: no other reader, no
/// other symbology.
fn decode_rmqr(
    luma: &LumaImage,
    hints: &mut rxing::DecodeHints,
    stop: &dyn Fn(&rxing::RXingResult) -> bool,
) -> rxing::common::Result<Vec<rxing::RXingResult>> {
    hints.TryHarder = hints.TryHarder.or(Some(true));
    let mut image = bitmap(luma)?;
    let mut reader = rxing::MultiFormatReader::default();
    super::multi_reader::decode_multiple(&mut reader, &mut image, hints, luma, stop)
}

/// Which rxing QR reader produced a result — it decides what
/// `getRawBytes()` holds.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Reader {
    /// The zxing-cpp port: `getRawBytes()` is the payload itself.
    Port,
    /// The `ZXing`-lineage reader: `getRawBytes()` is the RS-corrected data
    /// codeword stream of a symbol at this EC level.
    Codewords(EcLevel),
}

/// Tell the readers apart by what each deterministically writes (rxing
/// 0.9.1-0.9.3): the port states the EC level as a letter, the
/// `ZXing`-lineage reader as its format-bits value (M=0 · L=1 · H=2 · Q=3).
/// Micro QR and rMQR exist only on the port. `None`: neither shape — the
/// bytes' meaning is unknown.
fn reader(symbology: Symbology, ec_level: Option<&str>) -> Option<Reader> {
    if symbology != Symbology::QrCode {
        return Some(Reader::Port);
    }
    match ec_level? {
        "L" | "M" | "Q" | "H" => Some(Reader::Port),
        "0" => Some(Reader::Codewords(EcLevel::M)),
        "1" => Some(Reader::Codewords(EcLevel::L)),
        "2" => Some(Reader::Codewords(EcLevel::H)),
        "3" => Some(Reader::Codewords(EcLevel::Q)),
        _ => None,
    }
}

/// Map one rxing result to an observation. `None`: a format we refuse to
/// publish, or a QR-family result whose original bytes cannot be
/// established — never published with a stand-in.
fn observe(result: &rxing::RXingResult) -> Option<RawDetection> {
    let symbology = map_symbology(*result.getBarcodeFormat())?;
    let metadata = result.getRXingResultMetadata();
    let ec_level = match metadata.get(&MetaKey::ERROR_CORRECTION_LEVEL) {
        Some(MetaValue::ErrorCorrectionLevel(level)) => Some(level.as_str()),
        _ => None,
    };
    let identifier = match metadata.get(&MetaKey::SYMBOLOGY_IDENTIFIER) {
        Some(MetaValue::SymbologyIdentifier(id)) => id.as_str(),
        _ => "",
    };
    let mut detection = RawDetection {
        symbology,
        raw: Vec::new(),
        eci: EciEvidence::Unobserved,
        masked_stream: None,
        corners: None,
        version: None,
        ec: ec_level.and_then(parse_ec),
        mask: None,
        fnc1: Fnc1::Unobserved,
        parsed: false,
        engine: EngineKind::Rxing,
        segments: Segments::NotObserved,
        engine_reading: EngineReading::None,
        location: None,
        matrix_region: None,
        footprint: Footprint::unavailable(),
        locate: None,
        needs_confirmation: false,
        margin: Margin::Unknown,
    };
    if !symbology.is_qr_family() {
        return non_qr(detection, result, identifier, ec_level);
    }
    let reader = reader(symbology, ec_level)?;
    detection.footprint = footprint(symbology, Some(reader), result.getPoints());
    detection.location = location(result.getPoints()).map(|points| match reader {
        // rxing 0.9.3's grid sampler returns TL, TR, BL, BR. Keep the
        // cyclic corner order required by the scanner's grid re-read.
        Reader::Port => [points[0], points[1], points[3], points[2]],
        Reader::Codewords(_) => points,
    });
    // a corner the sampler could not project is its (0,0) default, not a
    // measurement: no exclusion region from it
    if reader == Reader::Port
        && result.getPoints().len() == 4
        && !result.getPoints().iter().any(|p| unprojected(*p))
    {
        detection.matrix_region = detection.location;
    }
    match reader {
        Reader::Port => {
            let raw = result.getRawBytes();
            // a plain read of ASCII text carries that text's bytes: anything
            // else is not the port's payload (another reader's shape). An
            // empty text claims nothing of them: it is what rxing renders for
            // a segment its decoders reject (a Kanji pair 5949-5951)
            let text = result.getText();
            if identifier == "]Q1" && !text.is_empty() && text.is_ascii() && !reads_as(raw, text) {
                return None;
            }
            detection.raw = raw.to_vec();
            // AIM modifier (ISO 18004 Annex F): 2 · 4 · 6 = ECI in use,
            // 3/4 = FNC1 first (GS1), 5/6 = FNC1 second (an AIM application),
            // 0-2 = no FNC1 — observed; an identifier that does not parse
            // observes neither
            let modifier = identifier
                .strip_prefix("]Q")
                .and_then(|m| m.parse::<u8>().ok());
            detection.eci = match modifier {
                Some(2 | 4 | 6) => EciEvidence::Signalled,
                Some(_) => EciEvidence::NoEci,
                None => EciEvidence::Unobserved,
            };
            detection.fnc1 = match modifier {
                Some(3 | 4) => Fnc1::First,
                Some(5 | 6) => Fnc1::Second,
                Some(_) => Fnc1::None,
                None => Fnc1::Unobserved,
            };
            detection.engine_reading = EngineReading::of(&detection.raw, result.getText());
            detection.locate = locate_hint(&detection, result, modifier);
        }
        Reader::Codewords(ec) => {
            let codewords = result.getRawBytes();
            let parsed = crate::rescue::version_of_data(codewords.len(), ec)
                .and_then(|version| bitstream::parse(codewords, version))?;
            // the parse must be the reader's own: its byte-mode segments,
            // in order (none with none)
            let segments: Vec<&[u8]> = parsed
                .byte_segments
                .iter()
                .filter_map(|range| parsed.bytes.get(range.clone()))
                .collect();
            let reader_segments: Vec<&[u8]> = match metadata.get(&MetaKey::BYTE_SEGMENTS) {
                Some(MetaValue::ByteSegments(own)) => own.iter().map(Vec::as_slice).collect(),
                _ => Vec::new(),
            };
            if segments != reader_segments {
                return None;
            }
            detection.raw = parsed.bytes;
            detection.eci = EciEvidence::from_marks(parsed.eci);
            detection.fnc1 = parsed.fnc1;
            detection.segments = Segments::Observed(parsed.segments);
            detection.parsed = true;
            // the EC level this reader states is not published: the
            // detection metadata stays exactly what it was before
            detection.ec = None;
        }
    }
    Some(detection)
}

/// A result of another symbology than the QR family: outside the QR
/// content contract, the engine's reading, never its byte segments (they
/// omit every non-byte encodation), and the footprint its points measured.
fn non_qr(
    mut detection: RawDetection,
    result: &rxing::RXingResult,
    identifier: &str,
    ec_level: Option<&str>,
) -> Option<RawDetection> {
    let symbology = detection.symbology;
    let text = result.getText();
    // DataBar (RSS-14) carries a GTIN-14: any other text is no DataBar the
    // reader decoded
    if symbology == Symbology::DataBar
        && !(text.len() == 14 && text.bytes().all(|b| b.is_ascii_digit()))
    {
        return None;
    }
    detection.footprint = footprint(symbology, None, result.getPoints());
    detection.raw = non_qr_raw(text);
    detection.fnc1 = identifier_fnc1(identifier);
    detection.needs_confirmation = needs_confirmation(symbology, ec_level);
    Some(detection)
}

/// rxing 0.9.3's grid sampler default for a corner no sampling region
/// covers (`default_grid_sampler.rs`, `projectCorner`): exactly (0,0),
/// without the half pixel every projected corner carries.
fn unprojected(p: rxing::Point) -> bool {
    p.x.to_bits() == 0 && p.y.to_bits() == 0
}

/// What an rxing result's points measured of its symbol, in attempt space
/// and before validation (`occurrence` module doc): never completed or
/// extended. QR family: the port's four sampler corners (TL, TR, BL, BR,
/// outer corners plus half a pixel) as the quad TL, TR, BR, BL on the outer
/// corners; the lineage reader's finder centres (and alignment pattern) as
/// partial points. Data Matrix and Aztec: their four corners. PDF417: the
/// symbol corners of its eight vertices (TL, BL, TR, BR, then the codeword
/// area's four) when all are present — missing vertices lose their index,
/// so fewer are partial. Linear symbologies: the scan line's two points.
/// `DataBar` and its Expanded form: the finder spans, partial. `MaxiCode`:
/// its points, partial, if any (rxing 0.9.3 reports none).
fn footprint(symbology: Symbology, reader: Option<Reader>, points: &[rxing::Point]) -> Footprint {
    let measured: Vec<Point> = points.iter().map(|p| Point { x: p.x, y: p.y }).collect();
    let quad = |order: [usize; 4]| order.map(|i| measured[i]).to_vec();
    let (kind, published) = match symbology {
        _ if measured.is_empty() => return Footprint::unavailable(),
        Symbology::QrCode | Symbology::MicroQrCode | Symbology::RectangularMicroQrCode => {
            match reader {
                Some(Reader::Port)
                    if points.len() == 4 && !points.iter().any(|p| unprojected(*p)) =>
                {
                    let outer = quad([0, 1, 3, 2])
                        .into_iter()
                        .map(|p| Point {
                            x: p.x - 0.5,
                            y: p.y - 0.5,
                        })
                        .collect();
                    (Kind::Quad, outer)
                }
                _ => (
                    Kind::Partial,
                    points
                        .iter()
                        .filter(|p| !unprojected(**p))
                        .map(|p| Point { x: p.x, y: p.y })
                        .collect(),
                ),
            }
        }
        Symbology::DataMatrix | Symbology::Aztec if measured.len() == 4 => (Kind::Quad, measured),
        Symbology::Pdf417 if measured.len() == 8 => (Kind::Quad, quad([0, 2, 3, 1])),
        Symbology::DataMatrix
        | Symbology::Aztec
        | Symbology::Pdf417
        | Symbology::MaxiCode
        | Symbology::DataBar
        | Symbology::DataBarExpanded => (Kind::Partial, measured),
        _ if measured.len() == 2 => (Kind::Segment, measured),
        _ => (Kind::Partial, measured),
    };
    Footprint::candidate(kind, published, EngineKind::Rxing)
}

/// Whether a port read's bytes are its text: the text's own bytes or, behind
/// a byte-order mark, the text rxing decodes them to — its decoders sniff
/// and strip the mark (`encoding_rs`'s `Encoding::decode`, the call rxing
/// makes).
fn reads_as(raw: &[u8], text: &str) -> bool {
    match raw {
        [0xEF, 0xBB, 0xBF, ..] | [0xFE, 0xFF, ..] | [0xFF, 0xFE, ..] => {
            encoding_rs::UTF_8.decode(raw).0 == text
        }
        _ => raw == text.as_bytes(),
    }
}

/// Whether a non-QR read waits for a read at an independent scale before the
/// walk publishes it: UPC-E, `DataBar` and `DataBar` Expanded — rxing reads them
/// out of module noise, and a check digit or a checksum is all that guards
/// their payload — and PDF417 at error-correction level 0 or 1, or at no
/// stated level: `2^(level + 1)` EC codewords, two or four, barely refuse a
/// misread.
fn needs_confirmation(symbology: Symbology, ec_level: Option<&str>) -> bool {
    match symbology {
        Symbology::UpcE | Symbology::DataBar | Symbology::DataBarExpanded => true,
        Symbology::Pdf417 => ec_level
            .and_then(|level| level.parse::<u8>().ok())
            .is_none_or(|level| level < 2),
        _ => false,
    }
}

/// A non-QR read's bytes (spec/01 § raw): the ISO/IEC 8859-1 encoding of
/// the engine's text when every character is at most U+00FF — exactly the
/// symbol's bytes on the engine's paths without ECI — else its UTF-8.
fn non_qr_raw(text: &str) -> Vec<u8> {
    text.chars()
        .map(|c| u8::try_from(u32::from(c)).ok())
        .collect::<Option<Vec<u8>>>()
        .unwrap_or_else(|| text.as_bytes().to_vec())
}

/// The FNC1 position an ISO/IEC 15424 symbology identifier states: Data
/// Matrix `]d2`/`]d5` and GS1-128 `]C1` first, `]d3`/`]d6`/`]C2` second,
/// `]d1`/`]d4`/`]C0`/`]C4` none; any other identifier says nothing of it.
fn identifier_fnc1(identifier: &str) -> Fnc1 {
    match identifier {
        "]d2" | "]d5" | "]C1" => Fnc1::First,
        "]d3" | "]d6" | "]C2" => Fnc1::Second,
        "]d1" | "]d4" | "]C0" | "]C4" => Fnc1::None,
        _ => Fnc1::Unobserved,
    }
}

/// A QR-family result's points as four corners: the port's four outer
/// corners, or the general reader's finder centres completed to a
/// parallelogram (its fourth point, when present, is an alignment pattern
/// near the missing corner).
fn location(points: &[rxing::Point]) -> Option<[Point; 4]> {
    let at = |i: usize| points.get(i).map(|p| Point { x: p.x, y: p.y });
    match points.len() {
        3 => {
            let (a, b, c) = (at(0)?, at(1)?, at(2)?);
            Some([
                a,
                b,
                c,
                Point {
                    x: a.x + c.x - b.x,
                    y: a.y + c.y - b.y,
                },
            ])
        }
        n if n >= 4 => Some([at(0)?, at(1)?, at(2)?, at(3)?]),
        _ => None,
    }
}

/// What the re-read needs for a port read of a QR Code symbol: on every
/// version, its declarations or segments when its modifier leaves them
/// unverified — an ECI or FNC1 indicator (`]Q2`-`]Q6`), or no indicator
/// over a payload that is not UTF-8 (Kanji segments to find); otherwise, at
/// EC level L or M, its word's margin on the versions where errors alone
/// pass the Annex B reserve ([`LocateHint::for_margin`]). Micro QR and rMQR
/// are never re-read.
fn locate_hint(
    detection: &RawDetection,
    result: &rxing::RXingResult,
    modifier: Option<u8>,
) -> Option<LocateHint> {
    let modifier = modifier?;
    let unverified = match modifier {
        2..=6 => true,
        0 | 1 => std::str::from_utf8(&detection.raw).is_err(),
        _ => false,
    };
    if detection.symbology != Symbology::QrCode || result.getPoints().len() != 4 {
        return None;
    }
    let inverted = matches!(
        result.getRXingResultMetadata().get(&MetaKey::IS_INVERTED),
        Some(MetaValue::IsInverted(true))
    );
    let hint = LocateHint {
        points: detection.location?,
        frame: Frame::OuterCorners,
        inverted,
        ec: detection.ec?,
        versions: 1..=40,
        modifier: Some(modifier),
        declarations: true,
    };
    if unverified {
        Some(hint)
    } else {
        hint.for_margin()
    }
}

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

    use super::{MetaKey, MetaValue, Reader, decode, location, observe, reader};
    use crate::engine::FormatFilter;
    use crate::engine::content::{EciEvidence, EciMark, Fnc1, Segments};
    use crate::input::LumaImage;
    use crate::report::{EcLevel, EngineKind, Symbology};
    use crate::rescue::test_symbols;

    /// Render a QR to a luma plane (default 4-module quiet zone, 6px modules).
    fn render(content: &[u8], ec: qrcode::EcLevel) -> LumaImage {
        let code = qrcode::QrCode::with_error_correction_level(content, ec).unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(6, 6)
            .build();
        let (w, h) = (img.width(), img.height());
        LumaImage::new(img.into_raw(), w, h)
    }

    /// Render an FNC1-in-first-position (GS1) symbol from an explicit bitstream.
    fn render_fnc1(byte_data: &[u8]) -> LumaImage {
        let mut bits = qrcode::bits::Bits::new(qrcode::Version::Normal(3));
        bits.push_fnc1_first_position().unwrap();
        bits.push_byte_data(byte_data).unwrap();
        bits.push_terminator(qrcode::EcLevel::M).unwrap();
        let code = qrcode::QrCode::with_bits(bits, qrcode::EcLevel::M).unwrap();
        let img = code
            .render::<image::Luma<u8>>()
            .module_dimensions(6, 6)
            .build();
        let (w, h) = (img.width(), img.height());
        LumaImage::new(img.into_raw(), w, h)
    }

    #[test]
    fn decodes_a_clean_qr_with_raw_bytes_and_ec() {
        let luma = render(b"parity check 1234", qrcode::EcLevel::Q);
        let found = decode(&luma, FormatFilter::All);
        let d = found
            .iter()
            .find(|d| d.symbology == Symbology::QrCode)
            .expect("rxing decodes a clean QR");
        assert_eq!(d.raw, b"parity check 1234");
        assert_eq!(d.engine, EngineKind::Rxing);
        assert_eq!(d.ec, Some(EcLevel::Q));
        // the rxing 0.9.1 QR path supplies no geometry/stream — rqrr owns that
        assert_eq!(d.version, None);
        assert!(d.corners.is_none() && d.masked_stream.is_none() && d.mask.is_none());
        assert_eq!(
            d.fnc1,
            Fnc1::None,
            "]Q1 observes: plain byte-mode QR is not FNC1"
        );
        assert!(!d.parsed, "the port states its account, never exposes it");
    }

    #[test]
    fn surfaces_the_fnc1_flag_on_a_gs1_symbol() {
        // rxing is THE GS1 engine: it reads the ]Q3 symbology identifier and
        // states FNC1 first so the payload router sends the bytes to the
        // element-string classifier. The raw bytes are the port's payload.
        let luma = render_fnc1(b"010950600013435210ABC123\x1d17261231");
        let found = decode(&luma, FormatFilter::All);
        let d = found
            .iter()
            .find(|d| d.symbology == Symbology::QrCode)
            .expect("rxing decodes the GS1 QR");
        assert_eq!(d.fnc1, Fnc1::First, "the ]Q3 identifier states FNC1 first");
        assert!(
            d.raw.starts_with(b"0109506000134352"),
            "raw carries the element data: {:?}",
            d.raw
        );
    }

    #[test]
    fn decodes_an_inverted_symbol_via_also_inverted() {
        // AlsoInverted is forced on in the adapter (light-on-dark artistic
        // codes are real). Photometrically invert a clean render — rxing still
        // reads it, proving the hint is wired.
        let luma = render(b"inverted-ok", qrcode::EcLevel::M);
        let inverted = LumaImage::new(
            luma.data().iter().map(|&p| 255 - p).collect(),
            luma.width(),
            luma.height(),
        );
        let found = decode(&inverted, FormatFilter::All);
        let d = found
            .iter()
            .find(|d| d.symbology == Symbology::QrCode)
            .expect("AlsoInverted decodes a light-on-dark QR");
        assert_eq!(d.raw, b"inverted-ok");
    }

    #[test]
    fn only_filter_restricts_to_the_requested_symbology() {
        // FormatFilter::Only(QrCode) routes through formats_for → a one-format
        // hint set; a clean QR still decodes under the restriction.
        let luma = render(b"only-qr", qrcode::EcLevel::M);
        let found = decode(&luma, FormatFilter::Only(Symbology::QrCode));
        assert!(
            found
                .iter()
                .any(|d| d.symbology == Symbology::QrCode && d.raw == b"only-qr")
        );
    }

    #[test]
    fn three_finder_centres_complete_to_a_parallelogram() {
        // the general reader's finder centres a, b, c gain the fourth corner
        // a + c − b; the port's four corners pass as they are; fewer points
        // locate nothing
        let at = |x, y| rxing::Point { x, y };
        let corner = |x, y| crate::report::Point { x, y };
        assert_eq!(
            location(&[at(10.0, 20.0), at(50.0, 20.0), at(50.0, 70.0)]),
            Some([
                corner(10.0, 20.0),
                corner(50.0, 20.0),
                corner(50.0, 70.0),
                corner(10.0, 70.0),
            ])
        );
        let four = [at(1.0, 2.0), at(9.0, 2.0), at(9.0, 8.0), at(1.0, 8.0)];
        assert_eq!(location(&four), Some(four.map(|p| corner(p.x, p.y))));
        assert_eq!(location(&four[..2]), None);
        assert_eq!(location(&[]), None);
    }

    #[test]
    fn a_plain_read_of_double_byte_bytes_is_re_read_for_its_segments() {
        // no indicator (]Q1) over Shift JIS bytes: the Kanji segments are
        // what a re-read finds — on every version, at every EC level (not
        // just the margin re-read of L and M)
        for ec in [qrcode::EcLevel::M, qrcode::EcLevel::H] {
            let luma = test_symbols::from_segments(qrcode::Version::Normal(2), ec, |b| {
                b.push_kanji_data(&[0x93, 0xFA, 0x96, 0x7B])
            });
            let found = decode(&luma, FormatFilter::All);
            let read = qr(&found);
            assert_eq!(read.raw, [0x93, 0xFA, 0x96, 0x7B], "{ec:?}");
            let hint = read.locate.as_ref().expect("a declarations re-read");
            assert!(
                hint.declarations && hint.versions == (1..=40) && hint.modifier == Some(1),
                "{ec:?}: {hint:?}"
            );
        }
    }

    /// The QR-family detection of a clean render.
    fn qr(found: &[super::RawDetection]) -> &super::RawDetection {
        found
            .iter()
            .find(|d| d.symbology.is_qr_family())
            .expect("rxing decodes the clean render")
    }

    #[test]
    fn the_port_reports_the_original_bytes_and_eci_presence() {
        // ECI 4 + byte A1: rxing's text is 'Ą'; the payload stays [A1] and
        // the ]Q2 modifier says a designator exists (position unexposed)
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(3), qrcode::EcLevel::M, |b| {
                b.push_eci_designator(4)?;
                b.push_byte_data(&[0xA1])
            });
        let found = decode(&luma, FormatFilter::All);
        let d = qr(&found);
        assert_eq!(d.raw, vec![0xA1], "never the UTF-8 of rxing's text");
        assert_eq!(d.eci, EciEvidence::Signalled);
        // a plain symbol: ]Q1 — no designator, stated
        let found = decode(&render(b"plain", qrcode::EcLevel::M), FormatFilter::All);
        assert_eq!(qr(&found).eci, EciEvidence::NoEci);
    }

    #[test]
    fn micro_qr_raw_is_the_symbol_byte_not_its_text() {
        // Micro QR decodes through the port only — exact bytes there too
        let luma =
            test_symbols::from_segments(qrcode::Version::Micro(3), qrcode::EcLevel::M, |b| {
                b.push_byte_data(&[0xE9])
            });
        let found = decode(&luma, FormatFilter::All);
        let d = qr(&found);
        assert_eq!(d.symbology, Symbology::MicroQrCode);
        assert_eq!(d.raw, vec![0xE9]);
        assert_eq!(d.eci, EciEvidence::NoEci);
    }

    #[test]
    fn fnc1_second_keeps_its_indicator_and_is_not_gs1() {
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(3), qrcode::EcLevel::M, |b| {
                b.push_fnc1_second_position(37)?;
                b.push_byte_data(b"abc")
            });
        let found = decode(&luma, FormatFilter::All);
        let d = qr(&found);
        assert_eq!(d.raw, b"37abc");
        assert_eq!(d.fnc1, Fnc1::Second, "]Q5: an AIM application, never GS1");
    }

    /// Data codewords of `12345` (numeric) + `abc` (byte) in a v1-M symbol.
    fn mixed_codewords() -> Vec<u8> {
        let mut bits = qrcode::bits::Bits::new(qrcode::Version::Normal(1));
        bits.push_numeric_data(b"12345").unwrap();
        bits.push_byte_data(b"abc").unwrap();
        bits.push_terminator(qrcode::EcLevel::M).unwrap();
        bits.into_bytes()
    }

    /// A result shaped like rxing's `ZXing`-lineage reader output, with the
    /// byte segments it lists (none: no metadata, as rxing omits it).
    fn general_reader_result(
        codewords: Vec<u8>,
        ec_digit: &str,
        byte_segments: &[&[u8]],
    ) -> rxing::RXingResult {
        let mut result = rxing::RXingResult::new(
            "12345abc",
            codewords,
            Vec::new(),
            rxing::BarcodeFormat::QR_CODE,
        );
        if !byte_segments.is_empty() {
            result.putMetadata(
                MetaKey::BYTE_SEGMENTS,
                MetaValue::ByteSegments(byte_segments.iter().map(|s| s.to_vec()).collect()),
            );
        }
        result.putMetadata(
            MetaKey::ERROR_CORRECTION_LEVEL,
            MetaValue::ErrorCorrectionLevel(ec_digit.to_owned()),
        );
        result.putMetadata(
            MetaKey::SYMBOLOGY_IDENTIFIER,
            MetaValue::SymbologyIdentifier("]Q1".to_owned()),
        );
        result
    }

    #[test]
    fn general_reader_codewords_reparse_to_the_whole_payload() {
        // the general reader's byte segments hold 'abc' only; its raw bytes
        // are the data codewords — re-parsed, the payload is all of it
        let abc: &[&[u8]] = &[b"abc"];
        let d = observe(&general_reader_result(mixed_codewords(), "0", abc)).expect("parses");
        assert_eq!(d.raw, b"12345abc", "never the byte segments alone");
        assert_eq!(d.eci, EciEvidence::NoEci, "observed: no designator");
        assert_eq!(d.fnc1, Fnc1::None, "observed: no FNC1 indicator");
        assert_eq!(d.segments, Segments::Observed(Vec::new()));
        assert!(d.parsed, "the scanner's parser read the codewords");
        assert_eq!(d.ec, None, "the reader's EC digit stays unpublished");
        assert!(d.locate.is_none(), "a parsed read needs no re-read");
        // a stream that does not parse is no observation — never a stand-in
        assert!(observe(&general_reader_result(vec![0xFF; 16], "0", abc)).is_none());
        // a length no version has at that EC level: unknown structure
        assert!(observe(&general_reader_result(vec![0x40; 17], "0", abc)).is_none());
        // an EC field of neither reader's shape: the bytes' meaning is unknown
        assert!(observe(&general_reader_result(mixed_codewords(), "?", abc)).is_none());
    }

    #[test]
    fn general_reader_codewords_must_be_the_readers_own() {
        // the parse's byte-mode segments equal the reader's own, in order,
        // or the codewords are not what it decoded — no observation
        for segments in [
            &[][..],
            &[&b"ab"[..]][..],
            &[&b"abc"[..], &b""[..]][..],
            &[&b"12345"[..], &b"abc"[..]][..],
        ] {
            assert!(
                observe(&general_reader_result(mixed_codewords(), "0", segments)).is_none(),
                "{segments:?}"
            );
        }
        // numeric data alone: none with none
        let digits = codewords(1, qrcode::EcLevel::M, |b| b.push_numeric_data(b"12345"));
        let d = observe(&general_reader_result(digits.clone(), "0", &[])).expect("parses");
        assert_eq!(d.raw, b"12345");
        assert!(observe(&general_reader_result(digits, "0", &[b"12345"])).is_none());
    }

    #[test]
    fn general_reader_codewords_must_carry_the_readers_own_byte_text() {
        // equal segment count and length, other bytes: not what it decoded
        assert!(observe(&general_reader_result(mixed_codewords(), "0", &[b"abd"])).is_none());
        let d = observe(&general_reader_result(mixed_codewords(), "0", &[b"abc"])).expect("parses");
        assert_eq!(d.raw, b"12345abc");
    }

    #[test]
    fn class_crossing_lengths_parse_only_at_their_own_level() {
        // 154 data codewords are v8-M and v10-Q, 1276 are v25-L and v40-H:
        // under the other level's digit the length names another version,
        // whose character-count widths misread the numeric segment
        use qrcode::EcLevel as L;
        let mixed = |b: &mut qrcode::bits::Bits| {
            b.push_numeric_data(b"12345")?;
            b.push_byte_data(b"abc")
        };
        for (version, level, right, wrong) in [(10, L::Q, "3", "0"), (40, L::H, "2", "1")] {
            let stream = codewords(version, level, mixed);
            assert!(
                observe(&general_reader_result(stream.clone(), wrong, &[b"abc"])).is_none(),
                "v{version} {level:?} read under digit {wrong}"
            );
            let d = observe(&general_reader_result(stream, right, &[b"abc"]))
                .unwrap_or_else(|| panic!("v{version} {level:?} parses under digit {right}"));
            assert_eq!(d.raw, b"12345abc");
        }
    }

    /// A result shaped like rxing's zxing-cpp port output: the EC level as a
    /// letter, the modifier `identifier`.
    fn port_result(text: &str, raw: Vec<u8>, identifier: &str) -> rxing::RXingResult {
        let mut result =
            rxing::RXingResult::new(text, raw, Vec::new(), rxing::BarcodeFormat::QR_CODE);
        result.putMetadata(
            MetaKey::ERROR_CORRECTION_LEVEL,
            MetaValue::ErrorCorrectionLevel("M".to_owned()),
        );
        result.putMetadata(
            MetaKey::SYMBOLOGY_IDENTIFIER,
            MetaValue::SymbologyIdentifier(identifier.to_owned()),
        );
        result
    }

    #[test]
    fn a_plain_port_read_is_kept_only_when_its_bytes_are_its_text() {
        // ]Q1 and an ASCII text: the bytes are the text's own, or the codewords
        // of a misread reader shape (refused)
        assert!(observe(&port_result("12345abc", mixed_codewords(), "]Q1")).is_none());
        let d = observe(&port_result("12345abc", b"12345abc".to_vec(), "]Q1")).expect("its text");
        assert_eq!(d.raw, b"12345abc");
        // behind a byte-order mark: the text rxing decodes the bytes to (it
        // sniffs and strips the mark), the bytes kept whole
        let bom = |rest: &[u8]| [&[0xEF, 0xBB, 0xBF][..], rest].concat();
        let url = b"https://qrc-ai.com/K1Ng2";
        let d = observe(&port_result("https://qrc-ai.com/K1Ng2", bom(url), "]Q1")).expect("BOM");
        assert_eq!(d.raw, bom(url));
        let utf16 = vec![0xFE, 0xFF, 0x00, b'a', 0x00, b'b', 0x00, b'c'];
        assert!(observe(&port_result("abc", utf16, "]Q1")).is_some());
        let utf16le = vec![0xFF, 0xFE, b'a', 0x00, b'b', 0x00, b'c', 0x00];
        assert!(observe(&port_result("abc", utf16le, "]Q1")).is_some());
        assert!(observe(&port_result("abc", bom(b"abd"), "]Q1")).is_none());
        // the rule reads only plain reads of ASCII text: a declared ECI or a
        // non-ASCII text is the content contract's to decide
        assert!(observe(&port_result("\u{104}", vec![0xA1], "]Q1")).is_some());
        assert!(observe(&port_result("abc", vec![0xA1], "]Q2")).is_some());
        // an empty text claims nothing of the bytes: rxing renders a segment
        // its decoder rejects (the Kanji pair 9F FD, value 5949) as nothing,
        // and the content contract reads the bytes. A non-empty ASCII text
        // that is not the bytes still refuses, with such a pair in them too
        let d = observe(&port_result("", vec![0x9F, 0xFD], "]Q1")).expect("an empty text");
        assert_eq!(d.raw, [0x9F, 0xFD]);
        assert!(observe(&port_result("QR", b"QR\x9F\xFD".to_vec(), "]Q1")).is_none());
    }

    /// Cell 825 of the rescue-stress grid: a v6-M symbol of a 120-byte filler
    /// under a gray square over 10 % of its area, below and left of the
    /// top-right finder. rxing's port cannot read it; its `ZXing`-lineage
    /// reader can.
    fn lineage_only() -> (LumaImage, String) {
        const ALPHABET: &[u8] = b"QRCODEAI0123456789abcdefghijklmnopqrstuvwxyz-./:";
        let truth: String = (0..120)
            .map(|i| char::from(ALPHABET[i % ALPHABET.len()]))
            .collect();
        let code = qrcode::QrCode::with_version(
            truth.as_bytes(),
            qrcode::Version::Normal(6),
            qrcode::EcLevel::M,
        )
        .unwrap();
        let symbol = code
            .render::<image::Luma<u8>>()
            .quiet_zone(false)
            .module_dimensions(8, 8)
            .build();
        let side = symbol.width() as f32;
        let quiet = 48;
        let canvas_side = symbol.width() + 2 * quiet;
        let mut canvas = image::GrayImage::from_pixel(canvas_side, canvas_side, image::Luma([255]));
        image::imageops::replace(&mut canvas, &symbol, i64::from(quiet), i64::from(quiet));
        let (cx, cy) = (quiet as f32 + 0.78 * side, quiet as f32 + 0.30 * side);
        let half = (0.10 * side * side).sqrt() / 2.0;
        let span = |lo: f32, hi: f32| {
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "pixel bounds inside the canvas"
            )]
            let bounds = (lo.floor() as u32, hi.ceil() as u32);
            bounds.0..bounds.1
        };
        for y in span(cy - half, cy + half) {
            for x in span(cx - half, cx + half) {
                canvas.put_pixel(x, y, image::Luma([120]));
            }
        }
        let (w, h) = (canvas.width(), canvas.height());
        (LumaImage::new(canvas.into_raw(), w, h), truth)
    }

    #[test]
    fn qr_family_reads_never_depend_on_the_format_set_order() {
        // rxing walks the QR-family format set in std HashSet order, and every
        // pass builds a set with fresh random keys: each format calls the same
        // stateless port reader with the same hints, and only QR_CODE then
        // tries the lineage reader, so every order reads the same
        let port = render(b"https://qrc-ai.com/order", qrcode::EcLevel::M);
        let (lineage, truth) = lineage_only();
        let reads = |luma: &LumaImage| format!("{:?}", decode(luma, FormatFilter::QrFamily));
        for (name, luma) in [("port", &port), ("lineage", &lineage)] {
            let first = reads(luma);
            for _ in 1..16 {
                assert_eq!(reads(luma), first, "{name}");
            }
        }
        let found = decode(&lineage, FormatFilter::QrFamily);
        let d = qr(&found);
        assert!(d.parsed, "the lineage reader's codewords");
        assert_eq!(d.raw, truth.as_bytes());
    }

    #[test]
    fn identifiers_state_the_fnc1_position_of_other_symbologies() {
        // ISO/IEC 15424 symbology identifiers
        for (identifier, fnc1) in [
            ("]d2", Fnc1::First),
            ("]d5", Fnc1::First),
            ("]C1", Fnc1::First),
            ("]d3", Fnc1::Second),
            ("]d6", Fnc1::Second),
            ("]C2", Fnc1::Second),
            ("]d1", Fnc1::None),
            ("]d4", Fnc1::None),
            ("]C0", Fnc1::None),
            ("]C4", Fnc1::None),
            ("]e0", Fnc1::Unobserved),
            ("]z0", Fnc1::Unobserved),
            ("]L2", Fnc1::Unobserved),
            ("", Fnc1::Unobserved),
        ] {
            assert_eq!(super::identifier_fnc1(identifier), fnc1, "{identifier:?}");
        }
    }

    #[test]
    fn other_symbologies_carry_the_engines_reading() {
        // the ISO/IEC 8859-1 bytes of the text when they fit, else its
        // UTF-8 — never the byte segments
        assert_eq!(super::non_qr_raw("日本"), "日本".as_bytes());
        assert_eq!(super::non_qr_raw("é"), vec![0xC3, 0xA9]);
        assert_eq!(super::non_qr_raw("Café"), vec![b'C', b'a', b'f', 0xE9]);
        let mut result = rxing::RXingResult::new(
            "é",
            vec![0xFF],
            Vec::new(),
            rxing::BarcodeFormat::DATA_MATRIX,
        );
        result.putMetadata(
            MetaKey::BYTE_SEGMENTS,
            MetaValue::ByteSegments(vec![vec![0xFF]]),
        );
        result.putMetadata(
            MetaKey::SYMBOLOGY_IDENTIFIER,
            MetaValue::SymbologyIdentifier("]d2".to_owned()),
        );
        let d = observe(&result).expect("a Data Matrix read");
        assert_eq!(d.raw, vec![0xC3, 0xA9]);
        assert_eq!((d.eci, d.fnc1), (EciEvidence::Unobserved, Fnc1::First));
        assert!(d.location.is_none() && d.locate.is_none());
    }

    /// An rxing result of `format` with `text`, its identifier and, when
    /// given, its error-correction level as rxing's PDF417 reader states it.
    fn other_result(
        format: rxing::BarcodeFormat,
        text: &str,
        identifier: &str,
        ec_level: Option<&str>,
    ) -> rxing::RXingResult {
        let mut result =
            rxing::RXingResult::new(text, text.as_bytes().to_vec(), Vec::new(), format);
        result.putMetadata(
            MetaKey::SYMBOLOGY_IDENTIFIER,
            MetaValue::SymbologyIdentifier(identifier.to_owned()),
        );
        if let Some(level) = ec_level {
            result.putMetadata(
                MetaKey::ERROR_CORRECTION_LEVEL,
                MetaValue::ErrorCorrectionLevel(level.to_owned()),
            );
        }
        result
    }

    #[test]
    fn a_databar_text_is_exactly_fourteen_digits() {
        // DataBar (RSS-14) carries a GTIN-14: anything else is no DataBar the
        // reader decoded (0.9.3 can write a saturated fifteenth character)
        let read = |text: &str| {
            observe(&other_result(
                rxing::BarcodeFormat::RSS_14,
                text,
                "]e0",
                None,
            ))
        };
        let d = read("09506000134352").expect("a GTIN-14");
        assert_eq!(d.raw, b"09506000134352");
        for text in [
            "095060001343520",
            "0950600013435",
            "0950600013435a",
            "09506000134352 ",
            "",
        ] {
            assert!(read(text).is_none(), "{text:?}");
        }
    }

    #[test]
    fn invention_prone_reads_wait_for_confirmation() {
        use rxing::BarcodeFormat as F;
        let waits = |format, text: &str, identifier: &str, level: Option<&str>| {
            observe(&other_result(format, text, identifier, level))
                .expect("a read")
                .needs_confirmation
        };
        assert!(waits(F::UPC_E, "04917052", "]E0", None));
        assert!(waits(F::RSS_14, "09506000134352", "]e0", None));
        assert!(waits(F::RSS_EXPANDED, "(01)09955188000001", "]e0", None));
        // PDF417 at level 0 or 1 (2 or 4 EC codewords) or no stated level
        for level in [Some("0"), Some("1"), None] {
            assert!(waits(F::PDF_417, "pdf", "]L2", level), "{level:?}");
        }
        for level in ["2", "5", "8"] {
            assert!(!waits(F::PDF_417, "pdf", "]L2", Some(level)), "{level}");
        }
        // the retail and 2D symbologies keep settling on one read
        assert!(!waits(F::EAN_13, "9506000134352", "]E0", None));
        assert!(!waits(F::CODE_128, "QRCAI-0042", "]C0", None));
        assert!(!waits(F::DATA_MATRIX, "abc", "]d1", None));
        // and QR-family reads never wait: their margins decide
        let found = decode(&render(b"plain", qrcode::EcLevel::M), FormatFilter::All);
        assert!(!qr(&found).needs_confirmation);
    }

    #[test]
    fn the_pdf417_fixtures_settle_on_one_read() {
        // rxing's writer default (level 2) and zxing-cpp's: neither is a
        // symbol the walk holds for confirmation
        for name in ["pdf417.png", "pdf417-utf8-cafe.png"] {
            let path = format!(
                "{}/../../fixtures/symbology/{name}",
                env!("CARGO_MANIFEST_DIR")
            );
            let bytes = std::fs::read(&path).unwrap();
            let img = image::load_from_memory(&bytes).unwrap().to_luma8();
            let (w, h) = (img.width(), img.height());
            let found = decode(&LumaImage::new(img.into_raw(), w, h), FormatFilter::All);
            let d = found
                .iter()
                .find(|d| d.symbology == Symbology::Pdf417)
                .unwrap_or_else(|| panic!("{name}: a PDF417 read"));
            assert!(!d.needs_confirmation, "{name}");
        }
    }

    #[test]
    fn rxing_points_are_outer_corners_plus_half() {
        // the locked rxing release, 6 px modules, 4-module quiet zone: the
        // port's result points sit half a pixel inside the outer corners
        let luma = render(b"https://qrc-ai.com/points", qrcode::EcLevel::M);
        let found = decode(&luma, FormatFilter::All);
        let d = qr(&found);
        let modules = ((luma.width() / 6) - 8) as f32;
        let (lo, hi) = (24.5, 24.5 + 6.0 * modules);
        let expected = [(lo, lo), (hi, lo), (hi, hi), (lo, hi)];
        let points = d.location.expect("the port's corner points");
        for (point, (x, y)) in points.iter().zip(expected) {
            assert!(
                (point.x - x).abs() < 0.01 && (point.y - y).abs() < 0.01,
                "{points:?} vs {expected:?}"
            );
        }
    }

    #[test]
    fn port_reads_get_the_re_read_their_modifier_and_shape_need() {
        // ]Q2 needs its declarations located (every version, at the port's
        // corners, in the polarity it read); ]Q1 ASCII and UTF-8 need none —
        // but at EC level L or M a margin to measure, on versions 1 and 2;
        // Q and H need nothing; Micro QR is never re-read
        let plain = decode(&render(b"plain", qrcode::EcLevel::M), FormatFilter::All);
        let hint = qr(&plain).locate.clone().expect("M: a margin to measure");
        assert!(!hint.declarations);
        assert_eq!(hint.versions, crate::engine::locate::MARGIN_VERSIONS);
        let utf8 = decode(
            &render("café".as_bytes(), qrcode::EcLevel::Q),
            FormatFilter::All,
        );
        assert!(qr(&utf8).locate.is_none());
        let high = decode(&render(b"plain", qrcode::EcLevel::H), FormatFilter::All);
        assert!(qr(&high).locate.is_none());
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(3), qrcode::EcLevel::M, |b| {
                b.push_eci_designator(4)?;
                b.push_byte_data(&[0xA1])
            });
        let found = decode(&luma, FormatFilter::All);
        let hint = qr(&found)
            .locate
            .clone()
            .expect("]Q2: declarations to locate");
        assert!(hint.declarations);
        assert_eq!(hint.versions, 1..=40);
        assert_eq!(hint.modifier, Some(2));
        assert_eq!(hint.ec, EcLevel::M);
        assert!(!hint.inverted);
        assert_eq!(Some(hint.points), qr(&found).location);
        let micro =
            test_symbols::from_segments(qrcode::Version::Micro(3), qrcode::EcLevel::M, |b| {
                b.push_byte_data(&[0xE9])
            });
        let found = decode(&micro, FormatFilter::All);
        assert!(qr(&found).locate.is_none());
    }

    /// The data codewords of a symbol built from `push`, padded to the
    /// capacity of `version` at `ec` — what the general reader returns.
    fn codewords(
        version: i16,
        ec: qrcode::EcLevel,
        push: impl FnOnce(&mut qrcode::bits::Bits) -> qrcode::types::QrResult<()>,
    ) -> Vec<u8> {
        let mut bits = qrcode::bits::Bits::new(qrcode::Version::Normal(version));
        push(&mut bits).unwrap();
        bits.push_terminator(ec).unwrap();
        bits.into_bytes()
    }

    #[test]
    fn general_reader_codewords_expose_declarations_and_fnc1_positions() {
        let m = qrcode::EcLevel::M;
        // ECI 4 + byte A1: the designator is located where it takes effect
        let d = observe(&general_reader_result(
            codewords(1, m, |b| {
                b.push_eci_designator(4)?;
                b.push_byte_data(&[0xA1])
            }),
            "0",
            &[&[0xA1]],
        ))
        .expect("parses");
        assert_eq!(d.raw, vec![0xA1]);
        assert_eq!(
            d.eci,
            EciEvidence::Located(vec![EciMark { value: 4, start: 0 }])
        );
        assert_eq!(d.fnc1, Fnc1::None);
        // FNC1 first + alphanumeric "10AB%%C": '%%' transmits one '%'
        let d = observe(&general_reader_result(
            codewords(1, m, |b| {
                b.push_fnc1_first_position()?;
                b.push_alphanumeric_data(b"10AB%%C")
            }),
            "0",
            &[],
        ))
        .expect("parses");
        assert_eq!(d.raw, b"10AB%C");
        assert_eq!(d.fnc1, Fnc1::First);
        // FNC1 second (37) + byte "abc": the indicator leads, AIM not GS1
        let d = observe(&general_reader_result(
            codewords(1, m, |b| {
                b.push_fnc1_second_position(37)?;
                b.push_byte_data(b"abc")
            }),
            "0",
            &[b"abc"],
        ))
        .expect("parses");
        assert_eq!(d.raw, b"37abc");
        assert_eq!(d.fnc1, Fnc1::Second);
        assert!(d.parsed);
    }

    #[test]
    fn general_reader_ec_digits_resolve_to_their_level_and_version() {
        // each stream's length exists at its own level only (v1-L 19, v3-M
        // 44, v1-H 9, v1-Q 13 data codewords): under any other digit no
        // version matches and the read is refused, so a remapped digit can
        // never parse at the wrong version
        use qrcode::EcLevel as L;
        let cases = [
            ("0", L::M, 3),
            ("1", L::L, 1),
            ("2", L::H, 1),
            ("3", L::Q, 1),
        ];
        for (digit, level, version) in cases {
            let stream = codewords(version, level, |b| b.push_byte_data(b"abc"));
            let d = observe(&general_reader_result(stream.clone(), digit, &[b"abc"]))
                .unwrap_or_else(|| panic!("digit {digit}: v{version} {level:?} parses"));
            assert_eq!(d.raw, b"abc", "digit {digit}");
            for (other, ..) in cases.iter().filter(|(other, ..)| *other != digit) {
                assert!(
                    observe(&general_reader_result(stream.clone(), other, &[b"abc"])).is_none(),
                    "the v{version} {level:?} stream read under digit {other}"
                );
            }
        }
    }

    #[test]
    fn an_unparsable_identifier_observes_neither_eci_nor_fnc1() {
        let mut result = rxing::RXingResult::new(
            "abc",
            b"abc".to_vec(),
            Vec::new(),
            rxing::BarcodeFormat::QR_CODE,
        );
        result.putMetadata(
            MetaKey::ERROR_CORRECTION_LEVEL,
            MetaValue::ErrorCorrectionLevel("M".to_owned()),
        );
        let d = observe(&result).expect("a port read");
        assert_eq!((d.eci, d.fnc1), (EciEvidence::Unobserved, Fnc1::Unobserved));
        result.putMetadata(
            MetaKey::SYMBOLOGY_IDENTIFIER,
            MetaValue::SymbologyIdentifier("]Q1".to_owned()),
        );
        let d = observe(&result).expect("a port read");
        assert_eq!((d.eci, d.fnc1), (EciEvidence::NoEci, Fnc1::None));
    }

    #[test]
    fn reader_discrimination_is_pinned_on_real_rxing_readers() {
        // Invoke both QR readers directly on one render: the port states the
        // EC level as a letter, the general reader as its format-bits digit
        // (M = 0) — and both map to the same payload bytes.
        use rxing::Reader as _;
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(1), qrcode::EcLevel::M, |b| {
                b.push_numeric_data(b"12345")?;
                b.push_byte_data(b"abc")
            });
        let bitmap = || {
            let (w, h) = (luma.width() as usize, luma.height() as usize);
            let source = rxing::PlanarYUVLuminanceSource::new_with_all(
                luma.data().to_vec(),
                w,
                h,
                0,
                0,
                w,
                h,
                false,
                false,
            )
            .unwrap();
            rxing::BinaryBitmap::new(rxing::common::HybridBinarizer::new(source))
        };
        let port = rxing::qrcode::cpp_port::QrReader
            .decode(&mut bitmap())
            .unwrap();
        let general = rxing::qrcode::QRCodeReader.decode(&mut bitmap()).unwrap();
        let ec_level = |result: &rxing::RXingResult| match result
            .getRXingResultMetadata()
            .get(&MetaKey::ERROR_CORRECTION_LEVEL)
        {
            Some(MetaValue::ErrorCorrectionLevel(level)) => level.clone(),
            _ => String::new(),
        };
        assert_eq!(
            reader(Symbology::QrCode, Some(&ec_level(&port))),
            Some(Reader::Port)
        );
        assert_eq!(
            reader(Symbology::QrCode, Some(&ec_level(&general))),
            Some(Reader::Codewords(EcLevel::M))
        );
        assert_eq!(port.getRawBytes(), b"12345abc", "the port: the payload");
        assert_eq!(
            general.getRawBytes(),
            mixed_codewords(),
            "general: codewords"
        );
        assert_eq!(observe(&port).unwrap().raw, b"12345abc");
        assert_eq!(observe(&general).unwrap().raw, b"12345abc");
    }

    #[test]
    fn a_blank_image_yields_no_detection_and_never_panics() {
        // NotFound is a miss, not an error — the adapter returns empty. (The
        // catch_unwind boundary itself lives in engine::run_isolated, mod.rs.)
        let blank = LumaImage::new(vec![255u8; 48 * 48], 48, 48);
        assert!(decode(&blank, FormatFilter::All).is_empty());
    }

    #[test]
    fn parse_ec_maps_every_level_and_rejects_the_rest() {
        // parse_ec 47:9 / 48:9 / 50:9 — deleting the "L"/"M"/"H" arms drops the
        // level to the `_ => None` catch-all. Only "Q" was pinned (the clean-QR
        // decode uses Q); the other three arms were unexercised.
        assert_eq!(super::parse_ec("L"), Some(EcLevel::L));
        assert_eq!(super::parse_ec("M"), Some(EcLevel::M));
        assert_eq!(super::parse_ec("Q"), Some(EcLevel::Q));
        assert_eq!(super::parse_ec("H"), Some(EcLevel::H));
        assert_eq!(super::parse_ec("Z"), None);
        assert_eq!(super::parse_ec(""), None);
        assert_eq!(super::parse_ec("l"), None, "case-sensitive: only uppercase");
    }

    /// A committed fixture as a luma plane.
    fn fixture(rel: &str) -> LumaImage {
        let path = format!("{}/../../fixtures/{rel}", env!("CARGO_MANIFEST_DIR"));
        let img = image::open(&path).unwrap().to_luma8();
        let (w, h) = (img.width(), img.height());
        LumaImage::new(img.into_raw(), w, h)
    }

    /// The fixtures under `symbology/` holding several symbols: where the
    /// upstream post-filter and `multi_reader` are meant to differ.
    const SEVERAL_SYMBOLS: [&str; 6] = [
        "datamatrix-pair-japanese.png",
        "ean13-addon5-code128.png",
        "maxicode-over-code128.png",
        "mixed-code128-qr.png",
        "qr-small-datamatrix.png",
        "qr-twins-code128.png",
    ];

    #[test]
    fn a_lone_symbol_reads_the_same_through_the_scanner_reader_and_upstream() {
        // multi_reader's local modifications (THIRD-PARTY.md) decide which
        // copies survive and where points lie, never what a lone symbol
        // reads: on every committed single-symbol fixture, the unrestricted
        // pass and rxing 0.9.3's own helper over the same plane (hybrid
        // binarizer, TryHarder on) read the same formats and texts
        let dir = format!("{}/../../fixtures/symbology", env!("CARGO_MANIFEST_DIR"));
        let mut names: Vec<String> = std::fs::read_dir(&dir)
            .unwrap()
            .map(|entry| entry.unwrap().file_name().into_string().unwrap())
            .filter(|name| {
                std::path::Path::new(name).extension().is_some_and(|ext| {
                    ext.eq_ignore_ascii_case("png") || ext.eq_ignore_ascii_case("jpg")
                }) && !SEVERAL_SYMBOLS.contains(&name.as_str())
            })
            .collect();
        names.sort();
        assert!(names.len() >= 30, "the single-symbol set: {names:?}");
        let reads = |results: &[rxing::RXingResult]| {
            let mut reads: Vec<(String, String)> = results
                .iter()
                .map(|r| {
                    (
                        format!("{:?}", r.getBarcodeFormat()),
                        r.getText().to_owned(),
                    )
                })
                .collect();
            reads.sort();
            reads.dedup();
            reads
        };
        let mut read = 0;
        for name in &names {
            let luma = fixture(&format!("symbology/{name}"));
            let ours = super::decode_all(&luma, &mut rxing::DecodeHints::default(), &|_| false)
                .unwrap_or_default();
            let upstream = rxing::helpers::detect_multiple_in_luma_with_hints(
                luma.data().to_vec(),
                luma.width(),
                luma.height(),
                &mut rxing::DecodeHints::default(),
            )
            .unwrap_or_default();
            assert_eq!(reads(&ours), reads(&upstream), "{name}");
            read += usize::from(!ours.is_empty());
        }
        assert!(read >= 25, "{read} of {} fixtures read", names.len());
    }

    #[test]
    fn an_rmqr_only_pass_reads_rmqr_and_nothing_else() {
        // The score cells and envelope probes of an rMQR symbol decode that
        // symbology alone. rxing 0.9.1's multi-use dispatcher has no rMQR
        // arm, so a pass restricted to it ran no reader at all and every
        // cell failed: the pass reads the committed rMQR fixture — the
        // content the unrestricted pass reads — and nothing of another
        // symbology.
        let rmqr = fixture("symbology/rmqr-url-kanji.png");
        let only = FormatFilter::Only(Symbology::RectangularMicroQrCode);
        let found = decode(&rmqr, only);
        let [d] = &found[..] else {
            panic!("one rMQR read: {found:?}");
        };
        assert_eq!(d.symbology, Symbology::RectangularMicroQrCode);
        assert_eq!(d.raw, b"https://qrc-ai.com/\x93\xfa\x96\x7b");
        let all = decode(&rmqr, FormatFilter::All);
        assert!(
            all.iter()
                .any(|a| a.symbology == d.symbology && a.raw == d.raw),
            "{all:?}"
        );
        for rel in ["symbology/microqr.png", "clean/gen_v2_l.png"] {
            assert!(decode(&fixture(rel), only).is_empty(), "{rel}");
        }
    }

    #[test]
    fn an_rmqr_only_pass_reads_a_light_on_dark_symbol() {
        // the pass of its own asks for inverted symbols as the general one
        // does
        let rmqr = fixture("symbology/rmqr-url-kanji.png");
        let inverted = LumaImage::new(
            rmqr.data().iter().map(|&p| 255 - p).collect(),
            rmqr.width(),
            rmqr.height(),
        );
        let only = FormatFilter::Only(Symbology::RectangularMicroQrCode);
        let found = decode(&inverted, only);
        assert!(
            found
                .iter()
                .any(|d| d.raw == b"https://qrc-ai.com/\x93\xfa\x96\x7b"),
            "{found:?}"
        );
    }

    #[test]
    fn a_set_of_rmqr_and_a_linear_format_reads_each_in_its_pass() {
        // rMQR without QR Code or Micro QR is read in a pass of its own; the
        // general pass still runs for the rest of the set
        let set = FormatFilter::Set(crate::engine::Formats::of(&[
            Symbology::RectangularMicroQrCode,
            Symbology::Ean13,
        ]));
        for (rel, symbology) in [
            ("symbology/ean13.png", Symbology::Ean13),
            (
                "symbology/rmqr-url-kanji.png",
                Symbology::RectangularMicroQrCode,
            ),
        ] {
            let found = decode(&fixture(rel), set);
            assert!(
                found.iter().any(|d| d.symbology == symbology),
                "{rel}: {found:?}"
            );
        }
    }

    #[test]
    fn databar_readers_preserve_content_at_independent_scales_and_respect_filters() {
        for (path, symbology, text) in [
            (
                "symbology/databar-small-regression.png",
                Symbology::DataBar,
                "09506000134352",
            ),
            (
                "symbology/databar-expanded-bwipp-regression.png",
                Symbology::DataBarExpanded,
                "(01)09506000134352(10)DEMO",
            ),
        ] {
            let original = fixture(path);
            let longest = original.width().max(original.height());
            let small = crate::transform::downscale_to(&original, longest * 3 / 4);
            assert!(longest * 4 >= small.width().max(small.height()) * 5);
            for plane in [&original, &small] {
                for filter in [FormatFilter::All, FormatFilter::Only(symbology)] {
                    let reads = decode(plane, filter);
                    assert!(!reads.is_empty(), "{path} {filter:?}");
                    assert!(
                        reads.iter().all(|read| read.symbology == symbology
                            && read.raw == text.as_bytes()
                            && read.needs_confirmation),
                        "{reads:?}"
                    );
                }
                assert!(decode(plane, FormatFilter::QrFamily).is_empty());
            }
        }
        assert!(
            decode(
                &fixture("symbology/ean13.png"),
                FormatFilter::Only(Symbology::DataBarExpanded)
            )
            .is_empty()
        );
    }

    #[test]
    fn only_filter_actually_excludes_other_symbologies() {
        // decode 92:55 — `Some(formats_for(sym)).filter(|set| !set.is_empty())`.
        // Deleting the `!` inverts the filter: the (never-empty) format set is
        // dropped, so `possible` becomes None → the pass decodes EVERYTHING.
        // The prior Only(QrCode) test could not catch this (a QR still decodes
        // unrestricted). Restrict a QR image to a NON-QR format: the original
        // returns the QR to nobody; the mutant leaks it through.
        let luma = render(b"only-qr", qrcode::EcLevel::M);
        let found = decode(&luma, FormatFilter::Only(Symbology::Ean13));
        assert!(
            found.iter().all(|d| d.symbology != Symbology::QrCode),
            "Only(Ean13) must NOT return a QR (mutant drops the restriction): {:?}",
            found.iter().map(|d| d.symbology).collect::<Vec<_>>()
        );
    }

    /// rxing result points at `pairs`.
    fn rxing_points(pairs: &[(f32, f32)]) -> Vec<rxing::Point> {
        pairs.iter().map(|&(x, y)| rxing::Point { x, y }).collect()
    }

    /// The footprint an rxing reader measured at `pairs`, before validation.
    fn measured(kind: super::Kind, pairs: &[(f32, f32)]) -> super::Footprint {
        super::Footprint {
            kind,
            points: pairs
                .iter()
                .map(|&(x, y)| crate::report::Point { x, y })
                .collect(),
            detector: Some(EngineKind::Rxing),
        }
    }

    #[test]
    fn only_the_samplers_exact_origin_default_is_unprojected() {
        // rxing 0.9.3's grid sampler leaves a corner no sampling region
        // covers at exactly (0,0); a corner on one edge of the image, or
        // anywhere else, is a measurement
        let at = |x, y| rxing::Point { x, y };
        assert!(super::unprojected(at(0.0, 0.0)));
        for (x, y) in [(0.0, 12.5), (12.5, 0.0), (0.5, 0.5), (12.5, 30.5)] {
            assert!(!super::unprojected(at(x, y)), "({x}, {y})");
        }
    }

    #[test]
    fn footprints_keep_what_each_reader_measured() {
        // never completed or extended: the port's four sampler corners (TL,
        // TR, BL, BR, half a pixel in) become the outer-corner quad TL, TR,
        // BR, BL; any other QR-family point set is partial as measured, an
        // unprojected corner dropped; each other symbology keeps its own
        // shape, and two points are a scan line only for a linear reader
        use super::Kind::{Partial, Quad, Segment};
        let footprint = |symbology, reader, pairs: &[(f32, f32)]| {
            super::footprint(symbology, reader, &rxing_points(pairs))
        };
        let port = Some(Reader::Port);
        let corners = [(10.5, 10.5), (50.5, 10.5), (10.5, 50.5), (50.5, 50.5)];
        let outer = [(10.0, 10.0), (50.0, 10.0), (50.0, 50.0), (10.0, 50.0)];
        for symbology in [
            Symbology::QrCode,
            Symbology::MicroQrCode,
            Symbology::RectangularMicroQrCode,
        ] {
            let quad = footprint(symbology, port, &corners);
            assert_eq!(quad, measured(Quad, &outer), "{symbology:?}");
        }
        let [top_left, top_right, _, bottom_right] = corners;
        assert_eq!(
            footprint(
                Symbology::QrCode,
                port,
                &[top_left, top_right, (0.0, 0.0), bottom_right]
            ),
            measured(Partial, &[top_left, top_right, bottom_right])
        );
        let three = &corners[..3];
        assert_eq!(
            footprint(Symbology::QrCode, port, three),
            measured(Partial, three)
        );
        // the lineage reader's finder centres (BL, TL, TR), then its
        // alignment pattern when found
        let lineage = Some(Reader::Codewords(EcLevel::M));
        let centres = [(20.5, 40.5), (20.5, 20.5), (40.5, 20.5), (37.5, 37.5)];
        for n in [3, 4] {
            let points = &centres[..n];
            assert_eq!(
                footprint(Symbology::QrCode, lineage, points),
                measured(Partial, points)
            );
        }
        // Data Matrix and Aztec: their four corners as measured
        let square = [(5.0, 5.0), (25.0, 5.0), (25.0, 25.0), (5.0, 25.0)];
        for symbology in [Symbology::DataMatrix, Symbology::Aztec] {
            assert_eq!(footprint(symbology, None, &square), measured(Quad, &square));
            let three = &square[..3];
            assert_eq!(footprint(symbology, None, three), measured(Partial, three));
        }
        // PDF417: TL, BL, TR, BR, then the codeword area's four vertices —
        // the symbol corners TL, TR, BR, BL when all eight are present
        let vertices = [
            (2.0, 3.0),
            (2.0, 30.0),
            (60.0, 3.0),
            (60.0, 30.0),
            (8.0, 3.0),
            (8.0, 30.0),
            (54.0, 3.0),
            (54.0, 30.0),
        ];
        let symbol = [(2.0, 3.0), (60.0, 3.0), (60.0, 30.0), (2.0, 30.0)];
        let pdf417 = |points: &[(f32, f32)]| footprint(Symbology::Pdf417, None, points);
        assert_eq!(pdf417(&vertices), measured(Quad, &symbol));
        assert_eq!(pdf417(&vertices[..4]), measured(Partial, &vertices[..4]));
        for symbology in [
            Symbology::DataMatrix,
            Symbology::Aztec,
            Symbology::Pdf417,
            Symbology::MaxiCode,
            Symbology::DataBar,
            Symbology::DataBarExpanded,
        ] {
            let two = &square[..2];
            let partial = footprint(symbology, None, two);
            assert_eq!(partial, measured(Partial, two), "{symbology:?}");
        }
        // linear symbologies: the scan line's two points; any other count
        // (an add-on's points appended) is partial
        let line = [(3.0, 20.0), (45.0, 20.0), (90.0, 20.0), (120.0, 20.0)];
        for symbology in [Symbology::Ean13, Symbology::Code128, Symbology::Itf] {
            let two = &line[..2];
            assert_eq!(footprint(symbology, None, two), measured(Segment, two));
            for n in [1, 3, 4] {
                let points = &line[..n];
                assert_eq!(
                    footprint(symbology, None, points),
                    measured(Partial, points),
                    "{symbology:?} {n}"
                );
            }
        }
        for (symbology, reader) in [
            (Symbology::QrCode, port),
            (Symbology::Pdf417, None),
            (Symbology::Ean13, None),
        ] {
            let nothing = footprint(symbology, reader, &[]);
            assert_eq!(nothing, super::Footprint::unavailable(), "{symbology:?}");
        }
    }

    #[test]
    fn only_the_ports_four_projected_corners_frame_a_matrix_region() {
        // the matrix region masks a decoded QR symbol out of the non-QR
        // completion plane: only the port's four sampler corners measure its
        // outline. An unprojected (0,0) corner, three points, or the lineage
        // reader's finder centres (inside the outline, the fourth corner
        // completed) frame none. The port's sampler always returns four
        // corners: what three port points locate is recorded, not a contract
        let corner = |(x, y): (f32, f32)| crate::report::Point { x, y };
        let port = |pairs: &[(f32, f32)]| {
            let result = port_result("abc", b"abc".to_vec(), "]Q1").with_point(rxing_points(pairs));
            let read = observe(&result).expect("a plain port read of its own text");
            (read.location, read.matrix_region)
        };
        // TL, TR, BL, BR as the port reports them; located TL, TR, BR, BL
        let [top_left, top_right, bottom_left, bottom_right] =
            [(10.5, 10.5), (50.5, 10.5), (10.5, 50.5), (50.5, 50.5)];
        let outline = [top_left, top_right, bottom_right, bottom_left].map(corner);
        assert_eq!(
            port(&[top_left, top_right, bottom_left, bottom_right]),
            (Some(outline), Some(outline))
        );
        let unprojected = [top_left, top_right, bottom_right, (0.0, 0.0)].map(corner);
        assert_eq!(
            port(&[top_left, top_right, (0.0, 0.0), bottom_right]),
            (Some(unprojected), None)
        );
        // incidental, not a completion: the lineage rule for finder centres
        // (BL, TL, TR) applied to the port's TL, TR, BL order
        let incidental = [top_left, top_right, (-29.5, 50.5), bottom_left].map(corner);
        assert_eq!(
            port(&[top_left, top_right, bottom_left]),
            (Some(incidental), None)
        );
        let lineage = |pairs: &[(f32, f32)]| {
            let result = general_reader_result(mixed_codewords(), "0", &[b"abc"])
                .with_point(rxing_points(pairs));
            let read = observe(&result).expect("the reader's own codewords");
            (read.location, read.matrix_region)
        };
        // the finder centres BL, TL, TR, then an alignment pattern
        let centres = [(20.5, 40.5), (20.5, 20.5), (40.5, 20.5)];
        let [bottom_left, top_left, top_right] = centres;
        let completed = [bottom_left, top_left, top_right, (40.5, 40.5)].map(corner);
        assert_eq!(lineage(&centres), (Some(completed), None));
        let aligned = [bottom_left, top_left, top_right, (37.5, 37.5)];
        assert_eq!(lineage(&aligned), (Some(aligned.map(corner)), None));
    }

    /// The committed `DataBar` Expanded symbol, downscaled to `side` pixels
    /// along its longer side.
    fn databar_expanded(side: u32) -> LumaImage {
        let symbol = fixture("symbology/databar-expanded-bwipp-regression.png");
        crate::transform::downscale_to(&symbol, side)
    }

    /// What a pass read: each result's format and text, in order.
    fn reads(results: &[rxing::RXingResult]) -> Vec<(rxing::BarcodeFormat, &str)> {
        results
            .iter()
            .map(|result| (*result.getBarcodeFormat(), result.getText()))
            .collect()
    }

    /// No read at all.
    const NOTHING: [(rxing::BarcodeFormat, &str); 0] = [];

    const EXPANDED_TEXT: &str = "(01)09506000134352(10)DEMO";

    /// What the upstream reader stack alone reads under the hints `decode`
    /// builds for a pass restricted to `only` (`None`: every format).
    fn upstream(luma: &LumaImage, only: Option<rxing::BarcodeFormat>) -> Vec<rxing::RXingResult> {
        let mut hints = rxing::DecodeHints {
            AlsoInverted: Some(true),
            PossibleFormats: only.map(|format| std::collections::HashSet::from([format])),
            ..Default::default()
        };
        super::decode_all(luma, &mut hints, &|_| false).unwrap_or_default()
    }

    /// `left` and `right` side by side on a white plane, top-aligned.
    fn beside(left: &LumaImage, right: &LumaImage) -> LumaImage {
        let width = left.width() + right.width();
        let height = left.height().max(right.height());
        let mut plane = vec![255u8; (width * height) as usize];
        for (image, offset) in [(left, 0), (right, left.width())] {
            let side = image.width() as usize;
            for y in 0..image.height() {
                let row = &image.data()[y as usize * side..][..side];
                let start = (y * width + offset) as usize;
                plane[start..start + side].copy_from_slice(row);
            }
        }
        LumaImage::new(plane, width, height)
    }

    #[test]
    fn the_patched_databar_expanded_pass_only_runs_when_no_expanded_symbol_was_read() {
        // At a quarter of the committed size both readers read the symbol:
        // the decode publishes one read, so the patched pass, which would
        // have added a second, did not run. At half the size the upstream
        // reader stops at an internal false finder and the patched pass reads
        // the symbol: one read again.
        use rxing::BarcodeFormat::RSS_EXPANDED;
        let quarter = databar_expanded(223);
        assert_eq!(
            reads(&upstream(&quarter, Some(RSS_EXPANDED))),
            [(RSS_EXPANDED, EXPANDED_TEXT)]
        );
        assert_eq!(
            reads(&super::decode_expanded(&quarter, &|_| false).unwrap()),
            [(RSS_EXPANDED, EXPANDED_TEXT)],
            "the patched pass reads the quarter-size symbol as well"
        );
        let half = databar_expanded(446);
        assert_eq!(
            reads(&upstream(&half, Some(RSS_EXPANDED))),
            NOTHING,
            "the upstream reader misses the half-size symbol"
        );
        for plane in [&quarter, &half] {
            let found = decode(plane, FormatFilter::Only(Symbology::DataBarExpanded));
            let [read] = &found[..] else {
                panic!("one read of the {}-pixel symbol: {found:?}", plane.width());
            };
            assert_eq!(
                (read.symbology, read.raw.as_slice()),
                (Symbology::DataBarExpanded, EXPANDED_TEXT.as_bytes())
            );
        }
    }

    #[test]
    fn the_patched_databar_expanded_pass_reads_a_vertical_symbol() {
        // TryHarder gives the patched reader its quarter-turn pass: the
        // half-size symbol turned a quarter clockwise, which the upstream
        // reader misses in both orientations, is read with its element
        // string — the walk holds it for confirmation like any such read
        use rxing::BarcodeFormat::RSS_EXPANDED;
        let upright = databar_expanded(446);
        let (width, height) = (upright.width(), upright.height());
        let mut turned = vec![0u8; upright.data().len()];
        for y in 0..height {
            for x in 0..width {
                // (x, y) moves to (height - 1 - y, x) in a height-wide image
                turned[(x * height + (height - 1 - y)) as usize] =
                    upright.data()[(y * width + x) as usize];
            }
        }
        let vertical = LumaImage::new(turned, height, width);
        assert_eq!(
            reads(&upstream(&vertical, Some(RSS_EXPANDED))),
            NOTHING,
            "the upstream reader misses the vertical symbol"
        );
        let found = decode(&vertical, FormatFilter::Only(Symbology::DataBarExpanded));
        let [read] = &found[..] else {
            panic!("one read of the vertical symbol: {found:?}");
        };
        assert_eq!(
            (read.symbology, read.raw.as_slice(), read.needs_confirmation),
            (Symbology::DataBarExpanded, EXPANDED_TEXT.as_bytes(), true)
        );
    }

    #[test]
    fn the_patched_databar_expanded_pass_runs_beside_a_read_of_another_symbol() {
        // An unrestricted pass over the half-size symbol with a QR code to
        // its right: the upstream readers read the QR code and miss the
        // expanded symbol in the region left of it, so the patched pass still
        // runs and the decode publishes both symbols. A read of another
        // symbol never stands for the expanded symbol the upstream reader
        // missed.
        let qr = render(b"a second read", qrcode::EcLevel::M);
        let plane = beside(&databar_expanded(446), &qr);
        assert_eq!(
            reads(&upstream(&plane, None)),
            [(rxing::BarcodeFormat::QR_CODE, "a second read")]
        );
        let found = decode(&plane, FormatFilter::All);
        let published: Vec<_> = found
            .iter()
            .map(|read| (read.symbology, read.raw.as_slice()))
            .collect();
        assert_eq!(
            published,
            [
                (Symbology::QrCode, b"a second read".as_slice()),
                (Symbology::DataBarExpanded, EXPANDED_TEXT.as_bytes()),
            ]
        );
    }
}