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
//! rqrr wrapper — the geometry + metadata engine (quirc lineage).
//!
//! Always through `decode_to` raw bytes: rqrr's `decode()` forces UTF-8.
//! rqrr parses ECI designators and DISCARDS them (verified on 0.11.0), so the
//! adapter re-derives the segment structure from the sampled grid with the
//! scanner's own codeword path — interpretation is OUR job, once, in
//! `engine::content`. The verified stream decides the payload bytes too:
//! rqrr's own conversion is not the truth (0.11.0 still writes the Kanji values
//! 5949-5951 as Shift JIS DF FD..DF FF — `value + 0x8140 <= 0x9FFC` —
//! where ISO 18004 §7.4.6 gives 9F FD..9F FF). Which orientation verifies is
//! checked, never assumed ([`settle`]); the read publishes the stream and
//! format of that orientation, and none when no orientation decides. A grid
//! rqrr cannot decode is the rescue input in the orientation whose codewords
//! verify ([`rescue_input`]: a mirrored FNC1 symbol), decided once for at
//! most [`MAX_CANDIDATES`] grids per pass.

use rqrr::BitGrid as _;

use super::content::{EciEvidence, EngineReading, Fnc1, Segments};
use super::locate::{Frame, LocateHint};
use super::occurrence::{UNIT_PIXEL, rqrr_footprint};
use super::{MaskedStream, RawDetection, Refusal};
use crate::input::LumaImage;
use crate::report::{EcLevel, EngineKind, Point, Symbology};
use crate::rescue::bitstream::PortRead;
use crate::rescue::{Acceptance, MAX_CANDIDATES, Margin, Rederived, RescueCandidate, Unverified};

/// rqrr `ecc_level` is the QR format-info two-bit field: M=0 · L=1 · H=2 · Q=3.
/// Pinned empirically by the engine tests (generated at known EC levels).
fn map_ec(level: u16) -> Option<EcLevel> {
    match level {
        0 => Some(EcLevel::M),
        1 => Some(EcLevel::L),
        2 => Some(EcLevel::H),
        3 => Some(EcLevel::Q),
        _ => None,
    }
}

/// One rqrr pass over an image.
pub(super) struct Pass {
    /// Decodes the scanner publishes.
    pub(super) found: Vec<RawDetection>,
    /// Grids detected but not decoded — the S5 rescue inputs.
    pub(super) rescue: Vec<RescueCandidate>,
    /// The decodes the scanner refused: what they withhold in the ladder.
    pub(super) refused: Vec<Refusal>,
}

/// rqrr's binarization of a luma plane, `true` where it paints a pixel
/// black: the adaptive threshold of the pinned `PreparedImage::prepare`
/// (quirc lineage), computed here so that rqrr receives the bitmap ready.
///
/// Two running averages sweep every row, one from each end; each step is
/// `average * (span - 1) / span + pixel`, with `span` an eighth of the
/// width. A pixel is black when it is under 95 % of the mean of the two
/// averages at its column.
///
/// rqrr divides three times per pixel, and two of those divisions sit on
/// the path from one step of a sweep to the next: they set the pace of the
/// whole pass. Here a step shifts when `span` is a power of two (a width
/// of 512, 1024 or 2048) and multiplies by the reciprocal of `span`
/// otherwise ([`quotient`]), and the comparison is cross-multiplied. Same
/// integers, same bitmap: the test `binarize_matches_rqrr` reads rqrr's
/// own back.
///
/// An average stays within `255 * span`, so the product a step divides
/// stays within `255 * span²`: the reciprocal is exact while `255 * span³`
/// fits 64 bits (a width of three million pixels), and the division itself
/// answers past that.
fn binarize(luma: &LumaImage) -> Vec<bool> {
    let span = (luma.width() as usize / 8).max(1);
    let wide = span as u64;
    if span.is_power_of_two() {
        let shift = span.trailing_zeros();
        binarize_with(luma, span, |average| (average * (span - 1)) >> shift)
    } else if wide
        .checked_pow(3)
        .is_some_and(|cube| cube.checked_mul(255).is_some())
    {
        let reciprocal = reciprocal(wide);
        binarize_with(luma, span, |average| {
            quotient(average * (span - 1), reciprocal)
        })
    } else {
        binarize_with(luma, span, |average| average * (span - 1) / span)
    }
}

/// `⌈2⁶⁴ / span⌉` for a `span` of two or more.
fn reciprocal(span: u64) -> u64 {
    // one more than ⌊(2⁶⁴ - 1) / span⌋, whether `span` divides 2⁶⁴ or not
    u64::MAX / span + 1
}

/// `⌊n / span⌋` from the [`reciprocal`] of `span`, exact while `n * span`
/// fits 64 bits: `reciprocal * span` is `2⁶⁴ + e` with `e < span`, so
/// `n * reciprocal / 2⁶⁴` is `n / span` plus `n * e / (span * 2⁶⁴)`, a
/// surplus under `1 / span` that cannot reach the next whole number.
#[expect(
    clippy::cast_possible_truncation,
    reason = "the high half of a 128-bit product, and no more than n"
)]
fn quotient(n: usize, reciprocal: u64) -> usize {
    ((u128::from(reciprocal) * n as u128) >> 64) as usize
}

/// [`binarize`] under one way to take `average * (span - 1) / span`.
fn binarize_with(luma: &LumaImage, span: usize, decay: impl Fn(usize) -> usize) -> Vec<bool> {
    let width = luma.width() as usize;
    let mut black = Vec::with_capacity(luma.data().len());
    let mut sums = vec![0usize; width];
    let scale = (200 * span) as u64;
    // rqrr's `avg_u` and `avg_v`: neither restarts at a new row, and the one
    // that ended a row at the right edge sweeps the next row from there
    let (mut forward, mut backward) = (0usize, 0usize);
    for row in luma.data().chunks_exact(width.max(1)) {
        sums.fill(0);
        for (x, (&front, &back)) in row.iter().zip(row.iter().rev()).enumerate() {
            forward = decay(forward) + usize::from(front);
            backward = decay(backward) + usize::from(back);
            sums[x] += forward;
            sums[width - 1 - x] += backward;
        }
        // `pixel < sum * 95 / (200 * span)` without the division: for whole
        // numbers, p < ⌊a / b⌋ exactly when (p + 1) · b ≤ a. The two
        // products rqrr takes stay in its `usize`; ours is wider, so that a
        // 32-bit target cannot wrap it
        black.extend(
            row.iter()
                .zip(&sums)
                .map(|(&pixel, &sum)| (u64::from(pixel) + 1) * scale <= (sum * 95) as u64),
        );
        std::mem::swap(&mut forward, &mut backward);
    }
    black
}

/// One rqrr pass. `orient_candidates`: the caller consumes the rescue
/// candidates (the ladder), so the first [`MAX_CANDIDATES`] undecodable grids
/// get their orientation decided here — once, carried in the candidate. A
/// caller that discards them (score cells, envelope probes) pays no RS for
/// them: the grid as sampled, as before.
pub(super) fn decode(luma: &LumaImage, orient_candidates: bool) -> Pass {
    let width = luma.width() as usize;
    let black = binarize(luma);
    let mut prepared =
        rqrr::PreparedImage::prepare_from_bitmap(width, luma.height() as usize, |x, y| {
            black[y * width + x]
        });

    let mut pass = Pass {
        found: Vec::new(),
        rescue: Vec::new(),
        refused: Vec::new(),
    };
    let mut oriented = 0;
    for grid in prepared.detect_grids() {
        let mut decoded = Vec::new();
        let Ok(meta) = grid.decode_to(&mut decoded) else {
            // RS or the parser gave up — but the grid + format info may
            // still read: that stream is the S5 erasure-rescue input
            let input = if orient_candidates && oriented < MAX_CANDIDATES {
                oriented += 1;
                rescue_input(&grid)
            } else {
                sampled_input(&grid)
            };
            pass.rescue.extend(input);
            continue;
        };
        let bounds = corners(&grid);
        let (derived, orientation) = rederive_decoded(&grid, &decoded);
        let (raw, eci, fnc1, segments, parsed, margin) = match account(decoded, derived) {
            Account::Read {
                raw,
                eci,
                fnc1,
                segments,
                parsed,
                margin,
            } => (raw, eci, fnc1, segments, parsed, margin),
            Account::Refused { rqrr, port } => {
                pass.refused
                    .extend(Refusal::new(port, Some(rqrr), Some(bounds)));
                continue;
            }
        };
        // a word errors alone took past the Annex B reserve publishes nothing
        // unless another read confirms its content: S5 may rescue its grid
        if matches!(margin, Margin::Known(margin) if margin < 0) {
            let input = if orient_candidates && oriented < MAX_CANDIDATES {
                oriented += 1;
                rescue_input(&grid)
            } else {
                sampled_input(&grid)
            };
            pass.rescue.extend(input);
        }
        // a grid that decided nothing: the re-read may still locate the
        // declarations, at rqrr's bounds and measured version
        let locate = match (&eci, map_ec(meta.ecc_level)) {
            (EciEvidence::Unobserved, Some(ec)) => Some(LocateHint {
                points: bounds,
                frame: Frame::GridBounds,
                inverted: false,
                ec,
                versions: u8::try_from(meta.version.0).map_or(1..=40, |version| version..=version),
                modifier: None,
                declarations: true,
            }),
            _ => None,
        };
        let mut read = RawDetection {
            symbology: Symbology::QrCode,
            raw,
            eci,
            masked_stream: None,
            corners: Some(bounds),
            version: None,
            ec: None,
            mask: None,
            fnc1,
            parsed,
            engine: EngineKind::Rqrr,
            segments,
            engine_reading: EngineReading::None,
            location: Some(bounds),
            matrix_region: Some(bounds),
            footprint: rqrr_footprint(bounds, grid.grid.size(), UNIT_PIXEL),
            locate,
            needs_confirmation: false,
            margin,
        };
        publish_orientation(&mut read, orientation);
        pass.found.push(read);
    }
    pass
}

/// The stream and format of the orientation that decided an rqrr read —
/// none when nothing did: the synthetic-UEC input must error-correct under
/// the version/EC/mask published beside it.
fn publish_orientation(read: &mut RawDetection, orientation: Option<Oriented>) {
    let Some((meta, raw_data)) = orientation else {
        return;
    };
    read.masked_stream = Some(masked(&raw_data));
    read.version = u8::try_from(meta.version.0).ok();
    read.ec = map_ec(meta.ecc_level);
    read.mask = u8::try_from(meta.mask).ok();
}

/// The detected grid's corners, in attempt-image pixels.
#[expect(
    clippy::cast_precision_loss,
    reason = "corner coordinates are bounded by Limits::max_dimension (10k) — exact in f32 (2^24)"
)]
fn corners<G>(grid: &rqrr::Grid<G>) -> [Point; 4] {
    grid.bounds.map(|p| Point {
        x: p.x as f32,
        y: p.y as f32,
    })
}

/// A grid rqrr detected but could not decode, read in one orientation —
/// `None` when its format information does not read there.
fn candidate<G>(
    grid: &rqrr::Grid<G>,
    read: Result<(rqrr::MetaData, rqrr::RawData), rqrr::DeQRError>,
    transposed: bool,
) -> Option<RescueCandidate> {
    let (meta, raw_data) = read.ok()?;
    Some(RescueCandidate {
        stream: masked(&raw_data),
        corners: corners(grid),
        pixel: UNIT_PIXEL,
        version: u8::try_from(meta.version.0).ok()?,
        ec: map_ec(meta.ecc_level)?,
        mask: u8::try_from(meta.mask).ok()?,
        inverted: false, // stamped by the ladder per attempt
        transposed,
        rederived: None,
    })
}

/// The S5 input of a grid the caller does not re-derive: as sampled, no
/// RS spent on it.
fn sampled_input<G: rqrr::BitGrid>(grid: &rqrr::Grid<G>) -> Option<RescueCandidate> {
    candidate(grid, grid.get_raw_data(), false)
}

/// The input of a grid rqrr detected but could not decode, in the
/// orientation whose codewords error-correct (plain RS, as every
/// re-derivation outside S5 accepts them), carrying that re-derivation so
/// the ladder never repeats it. rqrr's mirrored retry decodes a mirrored
/// symbol's transpose and its parser may then refuse it (FNC1 modes): the
/// candidate must be that orientation to locate the symbol's declarations or
/// prove it malformed. A sampled grid that parses stands; one that parses
/// malformed stands only when the transpose does not error-correct to
/// another result — two different verifying orientations decide nothing
/// (no parse, no refusal). When neither verifies — the erasure case S5
/// exists for — the sampled grid stays the input. Per grid: at most one
/// extra raw read of rqrr's own grid and two clean RS passes, no image
/// sampling.
fn rescue_input<G: rqrr::BitGrid>(grid: &rqrr::Grid<G>) -> Option<RescueCandidate> {
    let rederive = |candidate: &RescueCandidate| {
        crate::rescue::rederive(
            &candidate.stream,
            candidate.version,
            candidate.ec,
            candidate.mask,
            Acceptance::Engine,
        )
    };
    let decided = |mut candidate: RescueCandidate, derived: Rederived| {
        candidate.rederived = Some(derived);
        candidate
    };
    let sampled = sampled_input(grid);
    let sampled_derived = sampled.as_ref().map(rederive);
    if matches!(sampled_derived, Some(Rederived::Parsed { .. })) {
        return sampled
            .zip(sampled_derived)
            .map(|(candidate, derived)| decided(candidate, derived));
    }
    let transposed = candidate(
        grid,
        rqrr::Grid::new(Transposed(&grid.grid)).get_raw_data(),
        true,
    );
    let transposed_derived = transposed.as_ref().map(rederive);
    match (sampled, sampled_derived, transposed, transposed_derived) {
        // malformed as sampled: it stands unless the transpose verifies to
        // another result
        (Some(sampled), Some(malformed @ Rederived::Malformed { .. }), _, other) => {
            let stands = match &other {
                None | Some(Rederived::Unverified(_)) => true,
                Some(other) => *other == malformed,
            };
            Some(decided(
                sampled,
                if stands {
                    malformed
                } else {
                    Rederived::Unverified(Unverified::Ambiguous)
                },
            ))
        }
        // the sampled grid does not verify: the transpose when it does
        (_, _, Some(transposed), Some(derived)) if !matches!(derived, Rederived::Unverified(_)) => {
            Some(decided(transposed, derived))
        }
        (sampled, _, _, _) => sampled.map(|candidate| {
            decided(
                candidate,
                Rederived::Unverified(Unverified::NothingVerifies),
            )
        }),
    }
}

/// What the scanner makes of one rqrr decode.
#[derive(Debug, PartialEq, Eq)]
enum Account {
    /// Published: the payload, what was observed of its declarations and
    /// double-byte segments, and the correction margin of its word.
    Read {
        raw: Vec<u8>,
        eci: EciEvidence,
        fnc1: Fnc1,
        segments: Segments,
        parsed: bool,
        margin: Margin,
    },
    /// Refused: the stream rqrr decoded is not one ISO 18004 defines (rqrr
    /// reads a `111xxxxx` designator as one byte, an assignment number past
    /// 999999 like any other). Carries what the refusal withholds by: rqrr's
    /// own bytes, for rqrr's reads, and what rxing's port reports.
    Refused {
        rqrr: Vec<u8>,
        port: Option<PortRead>,
    },
}

/// rqrr decoded `decoded`; the re-derivation of its grid decides.
fn account(decoded: Vec<u8>, derived: Rederived) -> Account {
    match derived {
        // the RS-verified stream of the orientation rqrr decoded ([`settle`])
        // is the truth, bytes included — rqrr's own conversion is not
        Rederived::Parsed { parsed, margin } => Account::Read {
            raw: parsed.bytes,
            eci: EciEvidence::from_marks(parsed.eci),
            fnc1: parsed.fnc1,
            segments: Segments::Observed(parsed.segments),
            parsed: true,
            margin: Margin::Known(margin),
        },
        // no orientation verifies (or both do): nothing observable of the
        // declarations; rqrr decoded the symbol, so its stream held no FNC1
        // indicator. Its word is past the scanner's bounded decoder when no
        // orientation verifies — rqrr's correction has no degree bound — so
        // a known negative margin; two orientations that verify differently
        // say nothing of it
        Rederived::Unverified(reason) => Account::Read {
            raw: decoded,
            eci: EciEvidence::Unobserved,
            fnc1: Fnc1::None,
            segments: Segments::NotObserved,
            parsed: false,
            margin: match reason {
                Unverified::NothingVerifies => Margin::Known(-1),
                Unverified::Ambiguous => Margin::Unknown,
            },
        },
        Rederived::Malformed { port } => Account::Refused {
            rqrr: decoded,
            port,
        },
    }
}

/// One orientation of rqrr's grid as read: its format information and its
/// still-masked stream.
type Oriented = (rqrr::MetaData, rqrr::RawData);

/// Which orientation of rqrr's grid decided ([`settle`]).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Decision {
    /// The grid as sampled.
    Sampled,
    /// Its transpose — the orientation rqrr's mirrored retry decodes.
    Transposed,
    /// Neither: no orientation verifies, or both verify to different
    /// results.
    Neither,
}

/// Re-derive what rqrr decoded: the grid as sampled and, when [`settle`]
/// needs it, its transpose (`MirroredGrid` swaps x and y). Each is unmasked
/// with the format information read from it. Returns what stands and the
/// orientation that decided it, as read — its stream and format are the
/// ones published beside the read.
fn rederive_decoded<G: rqrr::BitGrid>(
    grid: &rqrr::Grid<G>,
    decoded: &[u8],
) -> (Rederived, Option<Oriented>) {
    let derive = |read: &Option<Oriented>| {
        read.as_ref().map_or(
            Rederived::Unverified(Unverified::NothingVerifies),
            |(meta, raw_data)| rederive_sampled(meta, raw_data),
        )
    };
    let sampled = grid.get_raw_data().ok();
    let mut transposed = None;
    let (derived, decision) = settle(
        derive(&sampled),
        || {
            transposed = rqrr::Grid::new(Transposed(&grid.grid)).get_raw_data().ok();
            derive(&transposed)
        },
        decoded,
    );
    let orientation = match decision {
        Decision::Sampled => sampled,
        Decision::Transposed => transposed,
        Decision::Neither => None,
    };
    (derived, orientation)
}

/// Which re-derivation of an rqrr decode stands. The RS-verified grid is
/// the truth: a sampled stream reproducing rqrr's bytes (up to rqrr's Kanji
/// conversion) is the one it decoded; otherwise the transpose is read too.
/// When exactly one orientation verifies, its parse decides — whatever rqrr
/// wrote: a transposed parse is deliberately NOT checked against rqrr's
/// bytes (rqrr's correction has no degree bound; the scanner's bounded RS
/// is the stricter evidence), and a malformed one refuses. The same result
/// both ways is no ambiguity (a transpose-symmetric grid): it stands. Two
/// different results decide nothing (`Unverified`, ambiguous) — never a
/// refusal on ambiguity; no orientation verifying decides nothing either
/// (`Unverified`, nothing verifies). The transpose is read only when needed.
fn settle(
    sampled: Rederived,
    transposed: impl FnOnce() -> Rederived,
    decoded: &[u8],
) -> (Rederived, Decision) {
    if matches!(&sampled, Rederived::Parsed { parsed, .. } if rqrr_converts_to(&parsed.bytes, decoded))
    {
        return (sampled, Decision::Sampled);
    }
    let other = transposed();
    match (sampled, other) {
        (Rederived::Unverified(_), Rederived::Unverified(_)) => (
            Rederived::Unverified(Unverified::NothingVerifies),
            Decision::Neither,
        ),
        (Rederived::Unverified(_), other) => (other, Decision::Transposed),
        (sampled, Rederived::Unverified(_)) => (sampled, Decision::Sampled),
        // one parse both ways: the word rqrr read is either, so the worse
        // of their margins
        (
            Rederived::Parsed { parsed, margin },
            Rederived::Parsed {
                parsed: theirs,
                margin: their_margin,
            },
        ) if parsed == theirs => (
            Rederived::Parsed {
                parsed,
                margin: margin.min(their_margin),
            },
            Decision::Sampled,
        ),
        (sampled, other) if other == sampled => (sampled, Decision::Sampled),
        _ => (
            Rederived::Unverified(Unverified::Ambiguous),
            Decision::Neither,
        ),
    }
}

/// Whether rqrr's conversion of the codewords that carry `parsed` is
/// `decoded`: equal, but for the Kanji values 5949-5951 — Shift JIS 9F
/// FD..9F FF by ISO 18004 §7.4.6, DF FD..DF FF by rqrr 0.10.1.
fn rqrr_converts_to(parsed: &[u8], decoded: &[u8]) -> bool {
    parsed.len() == decoded.len()
        && parsed
            .iter()
            .zip(decoded)
            .enumerate()
            .all(|(i, (&ours, &theirs))| {
                ours == theirs
                    || ((ours, theirs) == (0x9F, 0xDF)
                        && matches!(parsed.get(i + 1), Some(0xFD..=0xFF)))
            })
}

/// One orientation through the scanner's codeword path, under rqrr's own
/// acceptance (plain RS — see [`Acceptance::Engine`]).
fn rederive_sampled(meta: &rqrr::MetaData, raw_data: &rqrr::RawData) -> Rederived {
    let (Ok(version), Some(ec), Ok(mask)) = (
        u8::try_from(meta.version.0),
        map_ec(meta.ecc_level),
        u8::try_from(meta.mask),
    ) else {
        return Rederived::Unverified(Unverified::NothingVerifies);
    };
    crate::rescue::rederive(&masked(raw_data), version, ec, mask, Acceptance::Engine)
}

/// rqrr's sampled stream, still masked.
fn masked(raw_data: &rqrr::RawData) -> MaskedStream {
    MaskedStream {
        bits: raw_data.data[..raw_data.len.div_ceil(8)].to_vec(),
        bit_len: raw_data.len,
    }
}

/// A grid with x and y swapped — what rqrr's mirrored retry reads (a
/// left-right mirrored symbol samples as a transposed one).
struct Transposed<'g, G>(&'g G);

impl<G: rqrr::BitGrid> rqrr::BitGrid for Transposed<'_, G> {
    fn size(&self) -> usize {
        self.0.size()
    }

    fn bit(&self, y: usize, x: usize) -> bool {
        self.0.bit(x, y)
    }
}

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

    use super::{
        Account, Decision, Transposed, account, binarize, decode, quotient, reciprocal,
        rederive_sampled, rescue_input, settle,
    };
    use crate::engine::content::{ContentKey, EciEvidence, EciMark, Fnc1, Segments};
    use crate::input::LumaImage;
    use crate::report::{EcLevel, EngineKind, Symbology};
    use crate::rescue::bitstream::{Parsed, PortRead};
    use crate::rescue::{Acceptance, Margin, Rederived, Unverified, test_symbols};

    fn parsed_bytes(bytes: &[u8]) -> Rederived {
        Rederived::Parsed {
            parsed: Parsed {
                bytes: bytes.to_vec(),
                eci: Vec::new(),
                fnc1: Fnc1::None,
                structured_append: false,
                segments: Vec::new(),
                byte_segments: Vec::new(),
            },
            margin: 0,
        }
    }

    /// No orientation error-corrects.
    fn nothing() -> Rederived {
        Rederived::Unverified(Unverified::NothingVerifies)
    }

    /// Both orientations error-correct, to different results.
    fn ambiguous() -> Rederived {
        Rederived::Unverified(Unverified::Ambiguous)
    }

    fn malformed() -> Rederived {
        Rederived::Malformed { port: None }
    }

    /// (name, sampled, transposed — `None`: must not be read, rqrr's bytes,
    /// what stands)
    type SettleCase = (
        &'static str,
        Rederived,
        Option<Rederived>,
        Vec<u8>,
        Rederived,
    );

    /// A malformed re-derivation whose tolerant reading is `bytes`.
    fn malformed_reading(bytes: &[u8]) -> Rederived {
        Rederived::Malformed {
            port: Some(PortRead {
                bytes: bytes.to_vec(),
                signalled: true,
                fnc1: Fnc1::None,
            }),
        }
    }

    /// The orientation table: how the sampled grid and its transpose settle
    /// rqrr's decode.
    fn settle_cases() -> Vec<SettleCase> {
        [one_orientation_cases(), both_orientation_cases()].concat()
    }

    /// Cases one orientation settles (or neither does).
    fn one_orientation_cases() -> Vec<SettleCase> {
        let abc: &[u8] = b"abc";
        vec![
            (
                "reproduces",
                parsed_bytes(abc),
                None,
                abc.to_vec(),
                parsed_bytes(abc),
            ),
            (
                "rqrr's Kanji conversion",
                parsed_bytes(&[0x9F, 0xFD]),
                None,
                vec![0xDF, 0xFD],
                parsed_bytes(&[0x9F, 0xFD]),
            ),
            (
                "mirrored",
                nothing(),
                Some(parsed_bytes(abc)),
                abc.to_vec(),
                parsed_bytes(abc),
            ),
            (
                "mirrored, other bytes",
                nothing(),
                Some(parsed_bytes(b"xyz")),
                abc.to_vec(),
                parsed_bytes(b"xyz"),
            ),
            (
                "mirrored malformed",
                nothing(),
                Some(malformed()),
                abc.to_vec(),
                malformed(),
            ),
            (
                "neither",
                nothing(),
                Some(nothing()),
                abc.to_vec(),
                nothing(),
            ),
        ]
    }

    /// Cases where the sampled grid verifies without reproducing rqrr's
    /// decode, so the transpose is read too.
    fn both_orientation_cases() -> Vec<SettleCase> {
        let abc: &[u8] = b"abc";
        vec![
            (
                "malformed, transpose parses",
                malformed(),
                Some(parsed_bytes(abc)),
                abc.to_vec(),
                ambiguous(),
            ),
            (
                "malformed both ways, identical",
                malformed(),
                Some(malformed()),
                abc.to_vec(),
                malformed(),
            ),
            (
                "malformed both ways, different readings",
                malformed_reading(abc),
                Some(malformed_reading(b"xyz")),
                abc.to_vec(),
                ambiguous(),
            ),
            (
                "other bytes both ways, identical",
                parsed_bytes(b"xyz"),
                Some(parsed_bytes(b"xyz")),
                abc.to_vec(),
                parsed_bytes(b"xyz"),
            ),
            (
                "malformed, transpose unverified",
                malformed(),
                Some(nothing()),
                abc.to_vec(),
                malformed(),
            ),
            (
                "other bytes, transpose parses",
                parsed_bytes(b"xyz"),
                Some(parsed_bytes(abc)),
                abc.to_vec(),
                ambiguous(),
            ),
            (
                "other bytes, transpose malformed",
                parsed_bytes(b"xyz"),
                Some(malformed()),
                abc.to_vec(),
                ambiguous(),
            ),
            (
                "other bytes alone",
                parsed_bytes(b"xyz"),
                Some(nothing()),
                abc.to_vec(),
                parsed_bytes(b"xyz"),
            ),
            (
                // 9F FC is an ordinary Kanji pair rqrr converts right
                "not rqrr's Kanji conversion",
                parsed_bytes(&[0x9F, 0xFC]),
                Some(parsed_bytes(&[0xDF, 0xFC])),
                vec![0xDF, 0xFC],
                ambiguous(),
            ),
        ]
    }

    #[test]
    fn an_ambiguous_orientation_is_unverified_never_refused() {
        // The RS-verified grid is the truth: when one orientation verifies,
        // its parse decides — whatever rqrr wrote — and a malformed one
        // refuses. Nothing is decided when no orientation verifies, or when
        // both verify with DIFFERENT results (crafted grids only); never a
        // refusal on ambiguity. The same result both ways is no ambiguity (a
        // transpose-symmetric grid). The transpose is read only when the
        // sampled stream does not reproduce rqrr's decode.
        for (name, sampled, transposed, decoded, stands) in settle_cases() {
            let consulted = transposed.is_some();
            let (settled, decision) = settle(
                sampled.clone(),
                || {
                    transposed
                        .clone()
                        .unwrap_or_else(|| panic!("{name}: the transpose is not needed"))
                },
                &decoded,
            );
            assert_eq!(settled, stands, "{name} (transpose consulted: {consulted})");
            // the orientation published beside the read is the one that
            // decided: none when nothing did
            let expected = if matches!(settled, Rederived::Unverified(_)) {
                Decision::Neither
            } else if settled == sampled {
                Decision::Sampled
            } else {
                Decision::Transposed
            };
            assert_eq!(decision, expected, "{name}");
        }
    }

    #[test]
    fn one_parse_both_ways_stands_with_the_worse_margin() {
        // the same parse of two different words: the result stands as it
        // did, and the word rqrr read may be either
        let xyz = |margin| match parsed_bytes(b"xyz") {
            Rederived::Parsed { parsed, .. } => Rederived::Parsed { parsed, margin },
            other => other,
        };
        assert_eq!(
            settle(xyz(3), || xyz(-1), b"abc"),
            (xyz(-1), Decision::Sampled)
        );
        assert_eq!(settle(xyz(-1), || xyz(3), b"abc").0, xyz(-1));
    }

    /// For the one grid rqrr detects in `luma`: rqrr's bytes, then the
    /// re-derivations of its sampled grid and of the transpose.
    fn orientations(luma: &LumaImage) -> (Vec<u8>, Rederived, Rederived) {
        let width = luma.width() as usize;
        let data = luma.data();
        let mut prepared =
            rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
                data[y * width + x]
            });
        let grids = prepared.detect_grids();
        assert_eq!(grids.len(), 1);
        let grid = &grids[0];
        let mut decoded = Vec::new();
        grid.decode_to(&mut decoded)
            .expect("rqrr decodes the render");
        let derive = |read: Result<(rqrr::MetaData, rqrr::RawData), rqrr::DeQRError>| {
            read.map_or(nothing(), |(meta, raw_data)| {
                rederive_sampled(&meta, &raw_data)
            })
        };
        let sampled = derive(grid.get_raw_data());
        let transposed = derive(rqrr::Grid::new(Transposed(&grid.grid)).get_raw_data());
        (decoded, sampled, transposed)
    }

    #[test]
    fn orientations_verify_exactly_as_rqrr_decoded_them() {
        // differential: on real renders exactly one orientation verifies —
        // the one rqrr decoded (its mirrored retry reads the transpose) —
        // and it reproduces rqrr's bytes up to rqrr's Kanji conversion
        let eci4 = |b: &mut qrcode::bits::Bits| {
            b.push_eci_designator(4)?;
            b.push_byte_data(&[0xA1])
        };
        let kanji = |b: &mut qrcode::bits::Bits| b.push_kanji_data(&[0x9F, 0xFD]);
        let (v3, m) = (qrcode::Version::Normal(3), qrcode::EcLevel::M);
        // v3-M: 26 parity codewords, no error — a margin of 13
        let located = |bytes: &[u8]| Rederived::Parsed {
            parsed: Parsed {
                bytes: bytes.to_vec(),
                eci: vec![EciMark { value: 4, start: 0 }],
                fnc1: Fnc1::None,
                structured_append: false,
                segments: Vec::new(),
                byte_segments: std::iter::once(0..bytes.len()).collect(),
            },
            margin: 13,
        };
        let kanji_pair = || Rederived::Parsed {
            parsed: Parsed {
                bytes: vec![0x9F, 0xFD],
                eci: Vec::new(),
                fnc1: Fnc1::None,
                structured_append: false,
                segments: vec![crate::engine::content::DoubleByteSpan {
                    mode: crate::engine::content::DoubleByteMode::Kanji,
                    start: 0,
                    end: 2,
                }],
                byte_segments: Vec::new(),
            },
            margin: 13,
        };
        let cases: [(&str, LumaImage, bool, Rederived, Vec<u8>); 4] = [
            (
                "ECI 4",
                test_symbols::from_segments(v3, m, eci4),
                false,
                located(&[0xA1]),
                vec![0xA1],
            ),
            (
                "mirrored ECI 4",
                test_symbols::from_segments_mirrored(v3, m, eci4),
                true,
                located(&[0xA1]),
                vec![0xA1],
            ),
            (
                "Kanji 9F FD",
                test_symbols::from_segments(v3, m, kanji),
                false,
                kanji_pair(),
                vec![0xDF, 0xFD],
            ),
            (
                "mirrored Kanji 9F FD",
                test_symbols::from_segments_mirrored(v3, m, kanji),
                true,
                kanji_pair(),
                vec![0xDF, 0xFD],
            ),
        ];
        for (name, luma, mirrored, verified, rqrr_bytes) in cases {
            let (decoded, sampled, transposed) = orientations(&luma);
            assert_eq!(decoded, rqrr_bytes, "{name}: rqrr's own bytes");
            let (right, wrong) = if mirrored {
                (transposed, sampled)
            } else {
                (sampled, transposed)
            };
            assert_eq!(right, verified, "{name}: the orientation rqrr decoded");
            assert_eq!(wrong, nothing(), "{name}: the other one");
            let (again_decoded, sampled, transposed) = orientations(&luma);
            assert_eq!(
                settle(sampled, || transposed, &again_decoded),
                (
                    verified,
                    if mirrored {
                        Decision::Transposed
                    } else {
                        Decision::Sampled
                    }
                ),
                "{name}"
            );
        }
    }

    /// Render a QR to a luma plane (default 4-module quiet zone, 6px modules)
    /// and report the symbol version the encoder chose.
    fn render(content: &[u8], ec: qrcode::EcLevel) -> (LumaImage, u8) {
        let code = qrcode::QrCode::with_error_correction_level(content, ec).unwrap();
        let version = match code.version() {
            qrcode::Version::Normal(v) => u8::try_from(v).unwrap(),
            qrcode::Version::Micro(_) => 0,
        };
        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), version)
    }

    #[test]
    fn decodes_a_clean_qr_with_geometry_version_and_meta() {
        // 21-byte payload overflows v1-M (14-byte cap), so the encoder picks
        // v2+. rqrr is the geometry engine: corners/version/mask/ec are all
        // measured here (the rxing QR path leaves them None).
        let (luma, version) = render(b"https://qrc-ai.com/v2", qrcode::EcLevel::M);
        assert!(version >= 2, "want a v2+ symbol, got v{version}");
        let pass = decode(&luma, true);
        let d = pass.found.first().expect("rqrr decodes a clean QR");
        assert_eq!(d.raw, b"https://qrc-ai.com/v2");
        assert_eq!(d.symbology, Symbology::QrCode);
        assert_eq!(d.engine, EngineKind::Rqrr);
        assert_eq!(d.version, Some(version));
        assert_eq!(d.ec, Some(EcLevel::M));
        assert!(d.mask.is_some_and(|m| m <= 7), "mask {:?}", d.mask);
        assert!(d.masked_stream.is_some(), "rqrr exposes the sampled stream");
        let corners = d.corners.expect("rqrr reports corners");
        let side = luma.width() as f32;
        assert!(
            corners
                .iter()
                .all(|p| p.x >= 0.0 && p.x < side && p.y >= 0.0 && p.y < side),
            "{corners:?}"
        );
        assert_eq!(d.fnc1, Fnc1::None, "a plain byte-mode QR is not FNC1");
        assert_eq!(d.eci, EciEvidence::NoEci, "observed: no designator");
        assert!(d.parsed, "the scanner's parser read the stream");
    }

    #[test]
    fn rejects_fnc1_symbols_so_rxing_owns_gs1() {
        // rqrr's mode dispatch rejects the FNC1 indicators (0x5/0x9), so a
        // GS1 FNC1-in-first-position symbol yields NO decoded payload here —
        // the documented reason rxing is the GS1 engine. The grid is still
        // detected (it lands in the erasure-rescue vec), just never decoded.
        let mut bits = qrcode::bits::Bits::new(qrcode::Version::Normal(3));
        bits.push_fnc1_first_position().unwrap();
        bits.push_byte_data(b"0109506000134352").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());
        let luma = LumaImage::new(img.into_raw(), w, h);
        let pass = decode(&luma, true);
        assert!(
            pass.found.is_empty(),
            "rqrr must not decode FNC1: {:?}",
            pass.found
        );
    }

    #[test]
    fn a_blank_image_yields_no_detection_and_never_panics() {
        // No finder patterns → detect_grids finds nothing. (The panic-isolation
        // boundary itself lives in engine::run_isolated, exercised in mod.rs;
        // the adapter's own job is to return empty on a QR-less image.)
        let blank = LumaImage::new(vec![255u8; 48 * 48], 48, 48);
        let pass = decode(&blank, true);
        assert!(pass.found.is_empty() && pass.rescue.is_empty() && pass.refused.is_empty());
    }

    #[test]
    fn rqrr_decodes_carry_the_rederived_declaration() {
        // rqrr drops the ECI 4 designator; the adapter re-derives it from
        // the sampled stream, and the bytes agree with rqrr's
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(3), qrcode::EcLevel::M, |b| {
                b.push_numeric_data(b"12345")?;
                b.push_eci_designator(4)?;
                b.push_byte_data(&[0xA1])
            });
        let pass = decode(&luma, true);
        let d = pass.found.first().expect("rqrr decodes the clean render");
        assert_eq!(d.raw, b"12345\xA1");
        assert_eq!(
            d.eci,
            EciEvidence::Located(vec![EciMark { value: 4, start: 5 }])
        );
    }

    #[test]
    fn the_verified_stream_decides_the_payload_and_its_account() {
        let parsed = |bytes: &[u8], eci: Vec<EciMark>| Rederived::Parsed {
            parsed: Parsed {
                bytes: bytes.to_vec(),
                eci,
                fnc1: Fnc1::None,
                structured_append: false,
                segments: Vec::new(),
                byte_segments: Vec::new(),
            },
            margin: 2,
        };
        let read = |raw: &[u8], eci: EciEvidence, parsed: bool, margin: Margin| Account::Read {
            raw: raw.to_vec(),
            eci,
            fnc1: Fnc1::None,
            segments: if parsed {
                Segments::Observed(Vec::new())
            } else {
                Segments::NotObserved
            },
            parsed,
            margin,
        };
        let eci4 = vec![EciMark { value: 4, start: 0 }];
        // equal bytes: the located declaration
        assert_eq!(
            account(vec![0xA1], parsed(&[0xA1], eci4.clone())),
            read(&[0xA1], EciEvidence::Located(eci4), true, Margin::Known(2))
        );
        // rqrr's own conversion differs (its Kanji inversion): the verified
        // bytes are the payload, never rqrr's
        assert_eq!(
            account(vec![0xDF, 0xFD], parsed(&[0x9F, 0xFD], Vec::new())),
            read(&[0x9F, 0xFD], EciEvidence::NoEci, true, Margin::Known(2))
        );
        // no orientation verifies: rqrr's bytes, nothing observable of the
        // declarations, and no FNC1 (rqrr decodes neither mode); rqrr took a
        // word the scanner's bounded decoder refuses — a known negative
        // margin; two orientations that verify differently say nothing of it
        assert_eq!(
            account(b"abc".to_vec(), nothing()),
            read(b"abc", EciEvidence::Unobserved, false, Margin::Known(-1))
        );
        assert_eq!(
            account(b"abc".to_vec(), ambiguous()),
            read(b"abc", EciEvidence::Unobserved, false, Margin::Unknown)
        );
        // malformed: refused, with what the refusal withholds by — rqrr's
        // own bytes for rqrr's reads, and what the port reports
        let port = PortRead {
            bytes: b"xyz".to_vec(),
            signalled: true,
            fnc1: Fnc1::None,
        };
        assert_eq!(
            account(
                b"abc".to_vec(),
                Rederived::Malformed {
                    port: Some(port.clone())
                }
            ),
            Account::Refused {
                rqrr: b"abc".to_vec(),
                port: Some(port),
            }
        );
        assert_eq!(
            account(b"abc".to_vec(), malformed()),
            Account::Refused {
                rqrr: b"abc".to_vec(),
                port: None,
            }
        );
    }

    /// rqrr's own bytes for every grid of `luma` it decodes.
    fn rqrr_bytes(luma: &LumaImage) -> Vec<Vec<u8>> {
        let width = luma.width() as usize;
        let data = luma.data();
        let mut prepared =
            rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
                data[y * width + x]
            });
        prepared
            .detect_grids()
            .into_iter()
            .filter_map(|grid| {
                let mut raw = Vec::new();
                grid.decode_to(&mut raw).ok().map(|_| raw)
            })
            .collect()
    }

    #[test]
    fn rqrrs_kanji_inversion_yields_to_the_verified_stream() {
        // Shift JIS 9F FD is the 13-bit Kanji value 5949 (ISO 18004 §7.4.6);
        // rqrr 0.10.1 writes it DF FD, the re-derivation 9F FD
        let luma =
            test_symbols::from_segments(qrcode::Version::Normal(3), qrcode::EcLevel::M, |b| {
                b.push_kanji_data(&[0x9F, 0xFD])
            });
        assert_eq!(rqrr_bytes(&luma), vec![vec![0xDF, 0xFD]], "rqrr's bytes");
        let pass = decode(&luma, true);
        let d = pass.found.first().expect("rqrr decodes the clean render");
        assert_eq!(d.raw, vec![0x9F, 0xFD]);
        assert_eq!(d.eci, EciEvidence::NoEci);
        assert!(d.parsed);
    }

    #[test]
    fn a_mirrored_decode_is_rederived_on_the_transposed_grid() {
        // rqrr decodes a mirrored symbol through its mirrored retry; the
        // sampled grid does not verify, its transpose does
        let luma = test_symbols::from_segments_mirrored(
            qrcode::Version::Normal(3),
            qrcode::EcLevel::M,
            |b| {
                b.push_eci_designator(4)?;
                b.push_byte_data(&[0xA1])
            },
        );
        let pass = decode(&luma, true);
        let d = pass
            .found
            .first()
            .expect("rqrr decodes the mirrored render");
        assert_eq!(d.raw, vec![0xA1]);
        assert_eq!(
            d.eci,
            EciEvidence::Located(vec![EciMark { value: 4, start: 0 }])
        );
        assert!(d.parsed);
    }

    /// The raw reads of the one grid rqrr detects in `luma`: as sampled and
    /// transposed.
    fn raw_reads(luma: &LumaImage) -> (Option<super::Oriented>, Option<super::Oriented>) {
        let width = luma.width() as usize;
        let data = luma.data();
        let mut prepared =
            rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
                data[y * width + x]
            });
        let grid = prepared.detect_grids().remove(0);
        (
            grid.get_raw_data().ok(),
            rqrr::Grid::new(Transposed(&grid.grid)).get_raw_data().ok(),
        )
    }

    #[test]
    fn a_mirrored_decode_publishes_the_verified_stream() {
        // The read publishes the stream and format of the orientation that
        // decided — the transpose for a mirrored symbol — and they
        // error-correct errors-only under the published version/EC/mask
        // (the synthetic-UEC input). As sampled, a mirrored format word
        // still decodes, to another word (rqrr's format decoder corrects
        // past three bit errors: L/mask 0 reads as H/mask 2): the decode
        // published that format with the unmirrored stream before.
        let eci4 = |b: &mut qrcode::bits::Bits| {
            b.push_eci_designator(4)?;
            b.push_byte_data(&[0xA1])
        };
        let (v3, m) = (qrcode::Version::Normal(3), qrcode::EcLevel::M);
        let (l0, width) = test_symbols::masked_colors(
            qrcode::Version::Normal(2),
            qrcode::EcLevel::L,
            qrcode::canvas::MaskPattern::Checkerboard,
            eci4,
        );
        let cases = [
            ("upright", test_symbols::from_segments(v3, m, eci4), false),
            (
                "mirrored",
                test_symbols::from_segments_mirrored(v3, m, eci4),
                true,
            ),
            (
                "mirrored L0",
                test_symbols::render(&test_symbols::mirror(&l0, width), width),
                true,
            ),
        ];
        for (name, luma, mirrored) in cases {
            let (sampled, transposed) = raw_reads(&luma);
            let (_, expected) = (if mirrored { &transposed } else { &sampled })
                .as_ref()
                .unwrap();
            let pass = decode(&luma, true);
            let d = pass.found.first().expect("rqrr decodes the render");
            let stream = d.masked_stream.as_ref().expect("the verified stream");
            assert_eq!(stream.bits, super::masked(expected).bits, "{name}");
            let (version, ec, mask) = (d.version.unwrap(), d.ec.unwrap(), d.mask.unwrap());
            let Rederived::Parsed { parsed, .. } =
                crate::rescue::rederive(stream, version, ec, mask, Acceptance::Engine)
            else {
                panic!("{name}: the published stream error-corrects");
            };
            assert_eq!(parsed.bytes, vec![0xA1], "{name}");
            if name == "mirrored L0" {
                let (meta, _) = sampled.as_ref().expect("the sampled format decodes");
                assert_eq!(
                    (meta.ecc_level, meta.mask),
                    (2, 2),
                    "{name}: H/2 as sampled"
                );
                assert_eq!((ec, mask), (EcLevel::L, 0), "{name}");
            }
        }
    }

    #[test]
    fn a_read_nothing_decided_publishes_no_stream_or_format() {
        let mut read = crate::engine::RawDetection::qr(
            b"abc",
            EciEvidence::Unobserved,
            Fnc1::None,
            EngineKind::Rqrr,
        );
        super::publish_orientation(&mut read, None);
        assert!(read.masked_stream.is_none());
        assert_eq!((read.version, read.ec, read.mask), (None, None, None));
    }

    #[test]
    fn orientation_is_decided_for_at_most_four_grids_per_pass() {
        // Six FNC1 symbols rqrr detects but cannot decode: the first four
        // grids get their orientation decided (and carry that
        // re-derivation), the rest stay as sampled with no RS spent — and a
        // pass whose caller discards candidates spends none at all.
        let gs1 = |b: &mut qrcode::bits::Bits| {
            b.push_fnc1_first_position()?;
            b.push_numeric_data(b"0109506000134352")
        };
        let symbol = test_symbols::masked_colors(
            qrcode::Version::Normal(2),
            qrcode::EcLevel::M,
            qrcode::canvas::MaskPattern::Checkerboard,
            gs1,
        );
        let luma = test_symbols::row(&vec![symbol; 6]);
        let pass = decode(&luma, true);
        assert!(pass.found.is_empty());
        assert_eq!(pass.rescue.len(), 6, "rqrr detects every grid");
        let decided = pass
            .rescue
            .iter()
            .filter(|candidate| candidate.rederived.is_some())
            .count();
        assert_eq!(decided, crate::rescue::MAX_CANDIDATES);
        assert!(
            pass.rescue[..crate::rescue::MAX_CANDIDATES]
                .iter()
                .all(|candidate| matches!(candidate.rederived, Some(Rederived::Parsed { .. })))
        );
        let discarded = decode(&luma, false);
        assert_eq!(discarded.rescue.len(), 6);
        assert!(discarded.rescue.iter().all(|c| c.rederived.is_none()));
    }

    #[test]
    fn orientation_is_decided_for_at_most_four_reads_past_the_reserve_per_pass() {
        // The same bound on the other rescue input: six "abc" symbols at
        // v1-M, five codewords corrected — one past the Annex B reserve
        // (⌊(10 − 2)/2⌋ − 5 = −1). Each is published and each is a rescue
        // input; the first four carry their decided orientation, the rest
        // stay as sampled, and a caller that discards candidates decides none
        let data = test_symbols::stream("0100 00000011 01100001 01100010 01100011 0000");
        let symbol = test_symbols::codeword_colors(
            qrcode::Version::Normal(1),
            qrcode::EcLevel::M,
            &data,
            &[6, 8, 10, 12, 14],
        );
        let luma = test_symbols::row(&vec![symbol; 6]);
        let pass = decode(&luma, true);
        assert_eq!(pass.found.len(), 6, "rqrr decodes every grid");
        assert!(
            pass.found
                .iter()
                .all(|read| read.raw == b"abc" && read.margin == Margin::Known(-1)),
            "{:?}",
            pass.found
        );
        assert_eq!(pass.rescue.len(), 6);
        let decided = pass
            .rescue
            .iter()
            .filter(|candidate| candidate.rederived.is_some())
            .count();
        assert_eq!(decided, crate::rescue::MAX_CANDIDATES);
        let discarded = decode(&luma, false);
        assert_eq!(discarded.rescue.len(), 6);
        assert!(discarded.rescue.iter().all(|c| c.rederived.is_none()));
    }

    #[test]
    fn a_malformed_designator_decode_is_refused() {
        // rqrr reads a 111xxxxx designator as one byte and returns "abc";
        // the verified stream violates ISO 18004 Table 4: no detection, no
        // rescue input (rqrr did decode it), one refusal whose bytes withhold
        // rqrr's reads where the grid is — mirrored or not (the transposed
        // grid is re-derived too)
        let data =
            test_symbols::stream("0111 11100000 0100 00000011 01100001 01100010 01100011 0000");
        for luma in [
            test_symbols::from_codewords(qrcode::Version::Normal(1), qrcode::EcLevel::M, &data),
            test_symbols::from_codewords_mirrored(
                qrcode::Version::Normal(1),
                qrcode::EcLevel::M,
                &data,
            ),
        ] {
            let pass = decode(&luma, true);
            assert!(pass.found.is_empty(), "{:?}", pass.found);
            assert!(pass.rescue.is_empty());
            let [refusal] = &pass.refused[..] else {
                panic!("one refused stream: {:?}", pass.refused);
            };
            assert_eq!(refusal.rqrr.as_deref(), Some(&b"abc"[..]));
            assert_eq!(refusal.port, None, "the port refuses it too");
            assert!(refusal.place.is_some(), "the grid's bounds");
        }
        // above the register: rxing's port signals a designator and reads
        // "abc" — one record names that content too
        let data = test_symbols::stream(
            "0111 11001111 01000010 01000000 0100 00000011 01100001 01100010 01100011 0000",
        );
        let luma =
            test_symbols::from_codewords(qrcode::Version::Normal(1), qrcode::EcLevel::M, &data);
        let pass = decode(&luma, true);
        assert!(pass.found.is_empty());
        let [refusal] = &pass.refused[..] else {
            panic!("one refused stream: {:?}", pass.refused);
        };
        assert_eq!(refusal.rqrr.as_deref(), Some(&b"abc"[..]));
        assert_eq!(
            refusal.port,
            Some(ContentKey {
                raw: b"abc".to_vec(),
                eci: EciEvidence::Signalled,
                fnc1: Fnc1::None,
            })
        );
    }

    #[test]
    fn an_undecoded_grid_is_the_rescue_input_in_the_orientation_that_verifies() {
        // rqrr's parser refuses FNC1, so FNC1 symbols land in the rescue
        // inputs: unmirrored, the sampled grid verifies; mirrored, rqrr's
        // retry decoded the transpose — that orientation is the input, and
        // its clean re-derivation reads the symbol (or proves it malformed)
        let gs1 = |b: &mut qrcode::bits::Bits| {
            b.push_eci_designator(26)?;
            b.push_fnc1_first_position()?;
            b.push_numeric_data(b"0109506000134352")
        };
        let (v3, m) = (qrcode::Version::Normal(3), qrcode::EcLevel::M);
        let second_then_first = test_symbols::stream(
            "1001 00100101 0101 0100 00000011 01100001 01100010 01100011 0000",
        );
        let v1 = qrcode::Version::Normal(1);
        let cases = [
            ("ECI 26 GS1", test_symbols::from_segments(v3, m, gs1), false),
            (
                "mirrored ECI 26 GS1",
                test_symbols::from_segments_mirrored(v3, m, gs1),
                true,
            ),
            (
                "mirrored FNC1 second then first",
                test_symbols::from_codewords_mirrored(v1, m, &second_then_first),
                true,
            ),
        ];
        for (name, luma, transposed) in cases {
            let pass = decode(&luma, true);
            assert!(pass.found.is_empty() && pass.refused.is_empty(), "{name}");
            assert_eq!(pass.rescue.len(), 1, "{name}");
            let candidate = &pass.rescue[0];
            assert_eq!(candidate.transposed, transposed, "{name}");
            let derived = crate::rescue::rederive(
                &candidate.stream,
                candidate.version,
                candidate.ec,
                candidate.mask,
                Acceptance::Scanner,
            );
            if name.contains("second then first") {
                assert_eq!(
                    derived,
                    Rederived::Malformed {
                        port: Some(PortRead {
                            bytes: b"37abc".to_vec(),
                            signalled: false,
                            fnc1: Fnc1::First,
                        })
                    },
                    "{name}"
                );
            } else {
                let Rederived::Parsed { parsed, .. } = derived else {
                    panic!("{name}: {derived:?}");
                };
                assert_eq!(parsed.bytes, b"0109506000134352", "{name}");
                assert_eq!(
                    parsed.eci,
                    vec![EciMark {
                        value: 26,
                        start: 0
                    }],
                    "{name}"
                );
                assert_eq!(parsed.fnc1, Fnc1::First, "{name}");
            }
        }
        // a grid neither orientation verifies stays the sampled input
        let luma = test_symbols::from_corrupted_codewords(
            v1,
            m,
            &test_symbols::stream("0101 0100 00000011 01100001 01100010 01100011 0000"),
            &[0, 2, 4, 6, 8, 10],
        );
        let pass = decode(&luma, true);
        assert!(pass.found.is_empty(), "{:?}", pass.found);
        assert_eq!(pass.rescue.len(), 1);
        assert!(!pass.rescue[0].transposed);
        // the same input through the decode-failure branch directly
        let width = luma.width() as usize;
        let data = luma.data();
        let mut prepared =
            rqrr::PreparedImage::prepare_from_greyscale(width, luma.height() as usize, |x, y| {
                data[y * width + x]
            });
        let grid = prepared.detect_grids().remove(0);
        let input = rescue_input(&grid).expect("the format information reads");
        assert!(!input.transposed);
    }

    fn symbol_grid(colors: &[qrcode::Color]) -> rqrr::Grid<rqrr::SimpleGrid> {
        assert_eq!(colors.len(), 25 * 25);
        rqrr::Grid::new(rqrr::SimpleGrid::from_func(25, |x, y| {
            colors[y * 25 + x] == qrcode::Color::Dark
        }))
    }

    /// Actual sampled/transposed codewords, with the L/0 -> H/2 format
    /// relation checked before imposing any syndrome or payload constraints.
    fn dual_words(colors: &[qrcode::Color]) -> [Vec<u8>; 2] {
        let grid = symbol_grid(colors);
        // Convert each large raw reading before retaining the other orientation.
        let read = |(meta, raw): (rqrr::MetaData, rqrr::RawData), ec, mask| {
            assert_eq!((meta.version.0, meta.ecc_level, meta.mask), (2, ec, mask));
            assert_eq!(raw.len, 359);
            crate::matrix::zigzag::unmask_to_codewords(
                &raw.data,
                raw.len,
                2,
                u8::try_from(meta.mask).unwrap(),
            )
            .unwrap()
        };
        [
            read(grid.get_raw_data().unwrap(), 1, 0),
            read(
                rqrr::Grid::new(Transposed(&grid.grid))
                    .get_raw_data()
                    .unwrap(),
                2,
                2,
            ),
        ]
    }

    fn bits_of(bytes: &[u8]) -> Vec<bool> {
        bytes
            .iter()
            .flat_map(|byte| (0..8).map(move |bit| byte & (0x80 >> bit) != 0))
            .collect()
    }

    /// Affine GF(2) constraints only construct a fixture. The tests below
    /// independently re-encode its parity and check both real re-derivations.
    fn dual_constraints(colors: &[qrcode::Color], prefix_lengths: [usize; 2]) -> Vec<bool> {
        let mut constraints = Vec::new();
        for (i, word) in dual_words(colors).iter().enumerate() {
            let blocks = crate::matrix::deinterleave::deinterleave(word, 2, i + 1);
            let mut data = Vec::new();
            for block in blocks {
                constraints.extend(bits_of(&crate::matrix::gf256::syndromes(
                    &block.bytes,
                    block.npar,
                )));
                data.extend_from_slice(&block.bytes[..block.bytes.len() - block.npar]);
            }
            constraints.extend_from_slice(&bits_of(&data)[..prefix_lengths[i]]);
        }
        constraints
    }

    /// Solve one bounded binary system; free variables are zero. Inconsistent
    /// constraints fail the fixture, never skip the behavioral assertion.
    fn solve_fixture(mut rows: Vec<Vec<bool>>, variables: usize) -> Vec<bool> {
        let mut pivots = Vec::new();
        for column in 0..variables {
            let rank = pivots.len();
            let Some(pivot) = (rank..rows.len()).find(|&row| rows[row][column]) else {
                continue;
            };
            rows.swap(rank, pivot);
            let pivot_row = rows[rank].clone();
            for row in rows.iter_mut().skip(rank + 1) {
                if row[column] {
                    for (value, &pivot) in row.iter_mut().zip(&pivot_row).skip(column) {
                        *value ^= pivot;
                    }
                }
            }
            pivots.push(column);
        }
        assert!(
            rows.iter().skip(pivots.len()).all(|row| !row[variables]),
            "dual-orientation fixture constraints must have a solution"
        );
        let mut solution = vec![false; variables];
        for (row, &column) in rows.iter().zip(&pivots).rev() {
            solution[column] = row[variables]
                ^ row[..variables]
                    .iter()
                    .zip(&solution)
                    .skip(column + 1)
                    .fold(false, |sum, (&coefficient, &value)| {
                        sum ^ (coefficient & value)
                    });
        }
        solution
    }

    fn dual_symbol(prefixes: [&str; 2]) -> Vec<qrcode::Color> {
        let (mut colors, width) = test_symbols::masked_colors(
            qrcode::Version::Normal(2),
            qrcode::EcLevel::L,
            qrcode::canvas::MaskPattern::Checkerboard,
            |bits| bits.push_byte_data(b"A"),
        );
        assert_eq!(width, 25);
        let positions = crate::matrix::zigzag::zigzag_positions(2);
        assert_eq!(positions.len(), 359);
        let prefixes = prefixes.map(|prefix| {
            prefix
                .bytes()
                .filter(|byte| !byte.is_ascii_whitespace())
                .map(|byte| {
                    assert!(matches!(byte, b'0' | b'1'));
                    byte == b'1'
                })
                .collect::<Vec<_>>()
        });
        let lengths = [prefixes[0].len(), prefixes[1].len()];
        // v2-L: one block with 10 parity bytes; v2-H: one with 28.
        let target = [
            vec![false; 80],
            prefixes[0].clone(),
            vec![false; 224],
            prefixes[1].clone(),
        ]
        .concat();
        let initial = dual_constraints(&colors, lengths);
        assert_eq!(initial.len(), target.len());
        let mut rows: Vec<Vec<bool>> = initial
            .iter()
            .zip(&target)
            .map(|(&value, &wanted)| {
                let mut row = vec![false; positions.len() + 1];
                row[positions.len()] = value ^ wanted;
                row
            })
            .collect();
        for (column, &(y, x)) in positions.iter().enumerate() {
            colors[y * width + x] = !colors[y * width + x];
            let changed = dual_constraints(&colors, lengths);
            for ((row, &value), &original) in rows.iter_mut().zip(&changed).zip(&initial) {
                row[column] = value ^ original;
            }
            colors[y * width + x] = !colors[y * width + x];
        }
        let solution = solve_fixture(rows, positions.len());
        for (&toggle, &(y, x)) in solution.iter().zip(&positions) {
            if toggle {
                colors[y * width + x] = !colors[y * width + x];
            }
        }
        assert_eq!(dual_constraints(&colors, lengths), target);
        // An independent encoder checks both complete words. Syndrome zero
        // from the construction path alone is not a parity oracle.
        for (i, word) in dual_words(&colors).iter().enumerate() {
            let blocks = crate::matrix::deinterleave::deinterleave(word, 2, i + 1);
            let data: Vec<u8> = blocks
                .iter()
                .flat_map(|block| {
                    block.bytes[..block.bytes.len() - block.npar]
                        .iter()
                        .copied()
                })
                .collect();
            let ec = [qrcode::EcLevel::L, qrcode::EcLevel::H][i];
            let (data, parity) =
                qrcode::ec::construct_codewords(&data, qrcode::Version::Normal(2), ec).unwrap();
            assert_eq!([data, parity].concat(), *word, "orientation {i} parity");
        }
        colors
    }

    #[test]
    fn rescue_input_compares_real_malformed_orientations() {
        // The two masks make sampled mode 0111 transpose to mode 0100.
        // An oversized byte count is malformed in both readers; an empty
        // byte segment can instead precede a tolerant ECI or a terminator.
        let invalid_eci = "0111 111";
        let oversized_count = "0100 11111111";
        let above_register = "0100 00000000 0111 11001111 01000010 01000000 0000";
        let empty_byte_segment = Rederived::Parsed {
            parsed: Parsed {
                bytes: Vec::new(),
                eci: Vec::new(),
                fnc1: Fnc1::None,
                structured_append: false,
                segments: Vec::new(),
                byte_segments: std::iter::once(0..0).collect(),
            },
            margin: 14,
        };
        for (prefix, other, expected) in [
            (oversized_count, malformed(), malformed()),
            (above_register, malformed_reading(b""), ambiguous()),
            ("0100 00000000 0000", empty_byte_segment, ambiguous()),
        ] {
            let colors = dual_symbol([invalid_eci, prefix]);
            let mut grid = symbol_grid(&colors);
            grid.bounds = [
                rqrr::Point { x: 11, y: 13 },
                rqrr::Point { x: 211, y: 17 },
                rqrr::Point { x: 207, y: 219 },
                rqrr::Point { x: 9, y: 215 },
            ];
            let (meta, raw) = grid.get_raw_data().unwrap();
            let (other_meta, other_raw) = rqrr::Grid::new(Transposed(&grid.grid))
                .get_raw_data()
                .unwrap();
            assert_eq!((meta.version.0, meta.ecc_level, meta.mask), (2, 1, 0));
            assert_eq!(
                (other_meta.version.0, other_meta.ecc_level, other_meta.mask),
                (2, 2, 2)
            );
            assert_eq!(rederive_sampled(&meta, &raw), malformed());
            assert_eq!(rederive_sampled(&other_meta, &other_raw), other);
            let input = rescue_input(&grid).expect("both formats read");
            assert_eq!(input.rederived, Some(expected));
            assert_eq!((input.version, input.ec, input.mask), (2, EcLevel::L, 0));
            assert_eq!(input.corners, super::corners(&grid));
            assert_eq!(input.stream.bits, super::masked(&raw).bits);
            assert_eq!(input.stream.bit_len, raw.len);
            assert!(!input.transposed);
            assert!(!input.inverted);
        }
    }

    #[test]
    fn an_ambiguous_real_decode_retains_its_grid_bound_declaration_hint() {
        let colors = dual_symbol([
            "0111 11100000 0100 00000001 01000001 0000",
            "0100 00000000 0000",
        ]);
        let luma = test_symbols::render(&colors, 25);
        let mut prepared = rqrr::PreparedImage::prepare_from_greyscale(
            luma.width() as usize,
            luma.height() as usize,
            |x, y| luma.data()[y * luma.width() as usize + x],
        );
        let grids = prepared.detect_grids();
        assert_eq!(grids.len(), 1);
        let grid = &grids[0];
        let mut raw = Vec::new();
        let decoded_meta = grid
            .decode_to(&mut raw)
            .expect("rqrr tolerates the malformed ECI");
        assert_eq!(raw, b"A");
        assert_eq!(
            (
                decoded_meta.version.0,
                decoded_meta.ecc_level,
                decoded_meta.mask
            ),
            (2, 1, 0)
        );
        let (meta, sampled) = grid.get_raw_data().unwrap();
        let (other_meta, other_raw) = rqrr::Grid::new(Transposed(&grid.grid))
            .get_raw_data()
            .unwrap();
        assert_eq!(rederive_sampled(&meta, &sampled), malformed());
        let Rederived::Parsed { parsed, margin } = rederive_sampled(&other_meta, &other_raw) else {
            panic!("the actual transpose must independently verify");
        };
        assert_eq!(parsed.bytes.as_slice(), b"");
        assert_eq!(parsed.byte_segments.len(), 1);
        assert_eq!(parsed.byte_segments[0], 0..0);
        assert_eq!(parsed.eci, []);
        assert_eq!(parsed.fnc1, Fnc1::None);
        assert_eq!(parsed.segments, []);
        assert!(!parsed.structured_append);
        assert_eq!(margin, 14);
        let bounds = super::corners(grid);
        let pass = decode(&luma, true);
        assert_eq!(pass.found.len(), 1);
        assert!(pass.refused.is_empty());
        assert!(pass.rescue.is_empty());
        let read = &pass.found[0];
        assert_eq!(read.raw, b"A");
        assert_eq!(read.eci, EciEvidence::Unobserved);
        assert_eq!(read.margin, Margin::Unknown);
        assert_eq!(read.segments, Segments::NotObserved);
        assert_eq!(read.fnc1, Fnc1::None);
        assert!(!read.parsed);
        assert!(read.masked_stream.is_none());
        assert_eq!((read.version, read.ec, read.mask), (None, None, None));
        assert_eq!(read.corners, Some(bounds));
        assert_eq!(read.location, Some(bounds));
        assert_eq!(
            read.locate,
            Some(crate::engine::locate::LocateHint {
                points: bounds,
                frame: crate::engine::locate::Frame::GridBounds,
                inverted: false,
                ec: EcLevel::L,
                versions: 2..=2,
                modifier: None,
                declarations: true,
            })
        );
    }

    /// A plane of `width` × `height` pixels: runs, ramps and noise, so the
    /// two averages cross the pixels often.
    fn textured(width: u32, height: u32, seed: u32) -> LumaImage {
        let mut state = seed;
        let data = (0..width * height)
            .map(|i| {
                state = state.wrapping_mul(1_664_525).wrapping_add(1_013_904_223);
                let (x, y) = (i % width, i / width);
                let noise = (state >> 24) as u8;
                match (x / 5 + y / 3 + seed) % 4 {
                    0 => noise,
                    1 => 255 - (noise / 8),
                    2 => noise / 8,
                    _ => u8::try_from(x * 255 / width).unwrap(),
                }
            })
            .collect();
        LumaImage::new(data, width, height)
    }

    /// The bitmap the pinned rqrr computes from the same plane, read back pixel
    /// by pixel (`1` is its black).
    fn rqrr_bitmap(luma: &LumaImage) -> Vec<bool> {
        let (width, height) = (luma.width() as usize, luma.height() as usize);
        let prepared = rqrr::PreparedImage::prepare_from_greyscale(width, height, |x, y| {
            luma.data()[y * width + x]
        });
        (0..height)
            .flat_map(|y| (0..width).map(move |x| (x, y)))
            .map(|(x, y)| u8::from(prepared.get_pixel_at(x, y)) == 1)
            .collect()
    }

    #[test]
    fn binarize_matches_rqrr() {
        // widths whose eighth is 1, a power of two and neither; one row,
        // several rows, an odd count of rows (the sweeps trade ends)
        let widths = [1, 2, 7, 8, 15, 16, 17, 24, 31, 32, 64, 100, 128, 200, 257];
        for (seed, width) in (0..).zip(widths) {
            for height in [1, 2, 3, 8] {
                let luma = textured(width, height, seed);
                assert_eq!(
                    binarize(&luma),
                    rqrr_bitmap(&luma),
                    "{width}×{height}, seed {seed}"
                );
            }
        }
        // the sizes the scanner works at, and a real symbol
        for (width, height) in [(512, 3), (640, 5), (1024, 2), (1536, 2), (2048, 1)] {
            let luma = textured(width, height, 9);
            assert_eq!(binarize(&luma), rqrr_bitmap(&luma), "{width}×{height}");
        }
        let (symbol, _) = render(b"https://example.com/threshold", qrcode::EcLevel::M);
        assert_eq!(binarize(&symbol), rqrr_bitmap(&symbol));
        let blank = LumaImage::new(vec![255; 64 * 64], 64, 64);
        assert_eq!(binarize(&blank), rqrr_bitmap(&blank));
    }

    #[test]
    fn the_reciprocal_divides_exactly_up_to_its_bound() {
        // 255 * span³ fits 64 bits up to a span of 416 670; the largest
        // product a sweep divides there is 255 * span * (span - 1)
        for span in [2_usize, 3, 5, 12, 25, 64, 75, 1_000, 4_103, 416_670] {
            let reciprocal = reciprocal(span as u64);
            let top = 255 * span * (span - 1);
            let multiples = [1, 2, 254, 255 * (span - 1) - 1, 255 * (span - 1)];
            let around = multiples
                .iter()
                .flat_map(|k| [k * span - 1, k * span, k * span + 1]);
            for n in [0, 1, span - 1, top - 1, top].into_iter().chain(around) {
                assert_eq!(quotient(n, reciprocal), n / span, "{n} / {span}");
            }
        }
    }

    #[test]
    fn binarize_matches_rqrr_at_and_past_the_reach_of_the_reciprocal() {
        // one row each: the reciprocal on the last span it serves, the
        // division on the next
        for span in [416_670, 416_671] {
            let luma = textured(span * 8 + 5, 1, 3);
            assert_eq!(binarize(&luma), rqrr_bitmap(&luma), "span {span}");
        }
    }
}