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
//! Deterministic preprocessing — pure pixel ops + source planes access.
//!
//! Every function here is a pure deterministic mapping (no RNG, no wall
//! clock): same input ⇒ same output, the property the whole ladder and the
//! score contract stand on. RGB access is LAZY: channels materialize only
//! when the enhance stage actually runs (artistic-miss path).

use crate::error::{Result, ScanError};
use crate::input::{ImageInput, Limits, LumaImage, bt601, validate_buffer, validate_dims};
use crate::ladder::AlphaBackground;

/// Color channel selector for per-channel decode attempts.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum Channel {
    /// Red plane.
    R,
    /// Green plane.
    G,
    /// Blue plane.
    B,
}

/// Normalized scan source: the luma plane always, RGB retained when the
/// input had color (channel planes materialize lazily on demand).
#[derive(Debug, Clone)]
pub(crate) struct SourcePlanes {
    /// BT.601 luma plane — what stages S1/S2 consume.
    pub luma: LumaImage,
    /// Interleaved RGB (w*h*3) when the source carried color.
    rgb: Option<Vec<u8>>,
}

impl SourcePlanes {
    /// Luma-only planes (no color retained) — the alpha fallback's
    /// re-flatten seam.
    pub(crate) fn luma_only(luma: LumaImage) -> Self {
        Self { luma, rgb: None }
    }

    /// Whether the source carried color (channel planes available) —
    /// presence check only, no extraction.
    pub(crate) fn has_color(&self) -> bool {
        self.rgb.is_some()
    }

    /// Materialize one color channel as a luma plane. `None` for grayscale sources.
    pub(crate) fn channel(&self, channel: Channel) -> Option<LumaImage> {
        let rgb = self.rgb.as_ref()?;
        let offset = match channel {
            Channel::R => 0,
            Channel::G => 1,
            Channel::B => 2,
        };
        let data: Vec<u8> = rgb[offset..].iter().step_by(3).copied().collect();
        Some(LumaImage::new(data, self.luma.width(), self.luma.height()))
    }
}

/// Alpha-aware normalization result — the planes the ladder consumes plus
/// the retained alpha context when the input carried transparent pixels
/// under a flattening mode.
pub(crate) struct NormalizedInput {
    /// Scan planes (flattened when transparency was handled).
    pub planes: SourcePlanes,
    /// Alpha context for the fallback + envelope + report block.
    pub alpha: Option<crate::alpha::AlphaContext>,
}

/// Validate an [`ImageInput`] and normalize it into scan planes under the
/// default alpha handling — the historical two-arg seam the unit tests
/// exercise (every opaque input is untouched by the alpha path).
#[cfg(test)]
pub(crate) fn normalize(input: &ImageInput<'_>, limits: &Limits) -> Result<SourcePlanes> {
    normalize_with(input, limits, AlphaBackground::Auto).map(|normalized| normalized.planes)
}

/// Validate an [`ImageInput`] and normalize it into scan planes.
///
/// The single decode point of the crate: encoded bytes are dimension-probed
/// BEFORE full decode (decompression-bomb guard), raw buffers are
/// length-checked, and color is retained for the enhance stage. Inputs
/// carrying transparent pixels flatten over the configured background
/// BEFORE luma conversion and RGB extraction — every downstream stage sees
/// the composited image. Fully opaque inputs (and every input under
/// `alpha_background: none`) take the historical path, bit for bit.
pub(crate) fn normalize_with(
    input: &ImageInput<'_>,
    limits: &Limits,
    alpha_background: AlphaBackground,
) -> Result<NormalizedInput> {
    match *input {
        ImageInput::Luma8 {
            data,
            width,
            height,
        } => {
            let pixels = validate_dims(width, height, limits)?;
            validate_buffer(data.len(), pixels)?;
            Ok(NormalizedInput {
                planes: SourcePlanes {
                    luma: LumaImage::new(data.to_vec(), width, height),
                    rgb: None,
                },
                alpha: None,
            })
        }
        ImageInput::Rgba8 {
            data,
            width,
            height,
        } => {
            let pixels = validate_dims(width, height, limits)?;
            let bytes = pixels.checked_mul(4).ok_or(ScanError::PixelOverflow {
                width,
                height,
                max_pixels: limits.max_pixels,
            })?;
            validate_buffer(data.len(), bytes)?;
            // browser ImageData is color by contract — RGB always retained
            Ok(flatten_or_drop(data, width, height, alpha_background, true))
        }
        ImageInput::Encoded(bytes) => {
            let reader = image::ImageReader::new(std::io::Cursor::new(bytes))
                .with_guessed_format()
                .map_err(|e| ScanError::InvalidImage {
                    details: e.to_string(),
                })?;
            let (width, height) =
                reader
                    .into_dimensions()
                    .map_err(|e| ScanError::InvalidImage {
                        details: e.to_string(),
                    })?;
            validate_dims(width, height, limits)?;
            let mut reader = image::ImageReader::new(std::io::Cursor::new(bytes))
                .with_guessed_format()
                .map_err(|e| ScanError::InvalidImage {
                    details: e.to_string(),
                })?;
            // second wall behind the dimension probe: the decoder itself
            // refuses allocations past our pixel budget (malformed headers)
            let mut decode_limits = image::Limits::default();
            decode_limits.max_image_width = Some(limits.max_dimension);
            decode_limits.max_image_height = Some(limits.max_dimension);
            decode_limits.max_alloc = Some(limits.max_pixels.saturating_mul(8));
            reader.limits(decode_limits);
            let img = reader.decode().map_err(|e| ScanError::InvalidImage {
                details: e.to_string(),
            })?;
            if alpha_background != AlphaBackground::None && img.color().has_alpha() {
                // Borrow when the decoded image is already RGBA8 (the
                // dominant PNG class) — only exotic variants (Rgba16,
                // LumaA…) pay a conversion copy. The original `img` stays
                // intact for the opaque fall-through: routing a fully-
                // opaque input through an RGBA round-trip could drift luma
                // by ±1 vs the historical conversion, and opaque bit-parity
                // is contract.
                let colored = img.color().has_color();
                let converted;
                let rgba = if let Some(borrowed) = img.as_rgba8() {
                    borrowed
                } else {
                    converted = img.to_rgba8();
                    &converted
                };
                // early-exit routing test first: fully-opaque inputs (the
                // common case) pay one alpha-byte scan, never the stats
                if crate::alpha::has_transparency(rgba.as_raw()) {
                    let stats = crate::alpha::content_stats(rgba.as_raw());
                    let (w, h) = (rgba.width(), rgba.height());
                    return Ok(flatten(
                        rgba.as_raw(),
                        w,
                        h,
                        alpha_background,
                        colored,
                        &stats,
                    ));
                }
            }
            let rgb = img.color().has_color().then(|| img.to_rgb8().into_raw());
            let luma = img.into_luma8();
            let (w, h) = (luma.width(), luma.height());
            Ok(NormalizedInput {
                planes: SourcePlanes {
                    luma: LumaImage::new(luma.into_raw(), w, h),
                    rgb,
                },
                alpha: None,
            })
        }
    }
}

/// Raw-RGBA seam: flatten when transparent pixels exist under a flattening
/// mode, otherwise the historical drop-the-alpha loop (bit for bit).
fn flatten_or_drop(
    data: &[u8],
    width: u32,
    height: u32,
    mode: AlphaBackground,
    colored: bool,
) -> NormalizedInput {
    // early-exit routing test first: fully-opaque frames (every real
    // camera frame) pay one alpha-byte scan, never the stats pass
    if mode != AlphaBackground::None && crate::alpha::has_transparency(data) {
        let stats = crate::alpha::content_stats(data);
        return flatten(data, width, height, mode, colored, &stats);
    }
    let mut luma = Vec::with_capacity(data.len() / 4);
    let mut rgb = Vec::with_capacity(data.len() / 4 * 3);
    for px in data.as_chunks::<4>().0 {
        luma.push(bt601(px[0], px[1], px[2]));
        rgb.extend_from_slice(&px[..3]);
    }
    NormalizedInput {
        planes: SourcePlanes {
            luma: LumaImage::new(luma, width, height),
            rgb: Some(rgb),
        },
        alpha: None,
    }
}

/// Composite straight RGBA over the resolved background in ONE fused pass —
/// flattened planes for the ladder + the retained context for the
/// fallback/envelope/report.
fn flatten(
    data: &[u8],
    width: u32,
    height: u32,
    mode: AlphaBackground,
    colored: bool,
    stats: &crate::alpha::ContentStats,
) -> NormalizedInput {
    let bg = match mode {
        AlphaBackground::Auto => crate::alpha::auto_background(stats.content_luma),
        // both callers gate `none` out before flattening — the arm exists
        // only to keep the match total
        AlphaBackground::White | AlphaBackground::None => [255; 3],
        AlphaBackground::Black => [0; 3],
        AlphaBackground::Custom(custom) => custom,
    };
    let pixels = data.len() / 4;
    let mut luma = Vec::with_capacity(pixels);
    let mut rgb = colored.then(|| Vec::with_capacity(pixels * 3));
    let mut fg_luma = Vec::with_capacity(pixels);
    let mut alpha_plane = Vec::with_capacity(pixels);
    for px in data.as_chunks::<4>().0 {
        let a = px[3];
        let (r, g, b) = (
            crate::alpha::composite(px[0], bg[0], a),
            crate::alpha::composite(px[1], bg[1], a),
            crate::alpha::composite(px[2], bg[2], a),
        );
        luma.push(bt601(r, g, b));
        if let Some(rgb) = rgb.as_mut() {
            rgb.extend_from_slice(&[r, g, b]);
        }
        fg_luma.push(bt601(px[0], px[1], px[2]));
        alpha_plane.push(a);
    }
    let context =
        crate::alpha::AlphaContext::new(alpha_plane, fg_luma, width, height, stats, mode, bg);
    NormalizedInput {
        planes: SourcePlanes {
            luma: LumaImage::new(luma, width, height),
            rgb,
        },
        alpha: Some(context),
    }
}

/// Otsu binarization: maximize between-class variance, map `luma > t → 255`.
#[expect(
    clippy::cast_precision_loss,
    reason = "counts/sums are bounded by Limits::max_pixels (64MP·255 < 2^52) — exact in f64"
)]
#[expect(
    clippy::needless_range_loop,
    reason = "t is simultaneously the histogram index AND the candidate threshold value"
)]
pub(crate) fn otsu_threshold(img: &LumaImage) -> LumaImage {
    // four counters per value: on a single one, a run of equal pixels (most
    // of a clean or a binarized image) makes each increment wait for the
    // write of the one before it
    let histogram = histogram(img.data());
    let total: u64 = img.data().len() as u64;
    let weighted_sum: u64 = histogram
        .iter()
        .enumerate()
        .map(|(value, &count)| value as u64 * count)
        .sum();

    let mut best_threshold = 0usize;
    let mut best_variance = -1.0f64;
    let mut background_count = 0u64;
    let mut background_sum = 0u64;
    for t in 0..256 {
        background_count += histogram[t];
        if background_count == 0 {
            continue;
        }
        let foreground_count = total - background_count;
        if foreground_count == 0 {
            break;
        }
        background_sum += t as u64 * histogram[t];
        let background_mean = background_sum as f64 / background_count as f64;
        let foreground_mean = (weighted_sum - background_sum) as f64 / foreground_count as f64;
        let separation = background_mean - foreground_mean;
        let variance = background_count as f64 * foreground_count as f64 * separation * separation;
        if variance > best_variance {
            best_variance = variance;
            best_threshold = t;
        }
    }

    let threshold = u8::try_from(best_threshold).unwrap_or(u8::MAX);
    let data = img
        .data()
        .iter()
        .map(|&px| if px > threshold { 255 } else { 0 })
        .collect();
    LumaImage::new(data, img.width(), img.height())
}

/// Exact photometric inversion.
pub(crate) fn invert(img: &LumaImage) -> LumaImage {
    let data = img.data().iter().map(|&px| 255 - px).collect();
    LumaImage::new(data, img.width(), img.height())
}

/// Min-max contrast stretch to the full 0-255 range (flat images unchanged).
pub(crate) fn contrast_stretch(img: &LumaImage) -> LumaImage {
    // Fused min/max in ONE pass (was two separate `.min()`/`.max()` scans) —
    // identical (min, max) result, half the read traffic before the map pass.
    let Some((&first, rest)) = img.data().split_first() else {
        return img.clone(); // empty image: nothing to stretch
    };
    let (mut min, mut max) = (first, first);
    for &px in rest {
        min = min.min(px);
        max = max.max(px);
    }
    if min == max {
        return img.clone();
    }
    let range = u32::from(max - min);
    let data = img
        .data()
        .iter()
        .map(|&px| {
            let stretched = u32::from(px - min) * 255 / range;
            u8::try_from(stretched).unwrap_or(u8::MAX)
        })
        .collect();
    LumaImage::new(data, img.width(), img.height())
}

/// Deterministic box-average downscale so the longest side fits `max_side`.
/// No-op (clone) when the image already fits.
#[expect(
    clippy::cast_possible_truncation,
    reason = "every u64 here is a pixel index bounded by the u32 source dimensions"
)]
pub(crate) fn downscale_to(img: &LumaImage, max_side: u32) -> LumaImage {
    let (w, h) = (img.width(), img.height());
    let longest = w.max(h);
    if longest <= max_side {
        return img.clone();
    }
    let new_w = (u64::from(w) * u64::from(max_side) / u64::from(longest)).max(1) as u32;
    let new_h = (u64::from(h) * u64::from(max_side) / u64::from(longest)).max(1) as u32;

    let src = img.data();
    // Index arithmetic in usize: the admitted limits allow a source above
    // u32::MAX pixels (`max_pixels` is a u64), where a u32 product wraps.
    let mut data = Vec::with_capacity(new_w as usize * new_h as usize);
    for oy in 0..new_h {
        let y0 = (u64::from(oy) * u64::from(h) / u64::from(new_h)) as u32;
        let y1 =
            ((u64::from(oy) + 1) * u64::from(h) / u64::from(new_h)).max(u64::from(y0) + 1) as u32;
        for ox in 0..new_w {
            let x0 = (u64::from(ox) * u64::from(w) / u64::from(new_w)) as u32;
            let x1 = ((u64::from(ox) + 1) * u64::from(w) / u64::from(new_w)).max(u64::from(x0) + 1)
                as u32;
            let mut sum = 0u64;
            for y in y0..y1 {
                let row = y as usize * w as usize;
                for x in x0..x1 {
                    sum += u64::from(src[row + x as usize]);
                }
            }
            let count = u64::from(y1 - y0) * u64::from(x1 - x0);
            data.push(u8::try_from(sum / count).unwrap_or(u8::MAX));
        }
    }
    LumaImage::new(data, new_w, new_h)
}

/// v0.2-semantics contrast/brightness boost:
/// `clamp(((p · brightness) − 128) · contrast + 128)`.
/// Multiplicative contrast around the midpoint — distinct from
/// [`contrast_stretch`] (min-max): boost CRUSHES mid-tones outward, which is
/// what separates art texture from module structure on artistic codes.
pub(crate) fn contrast_boost(img: &LumaImage, contrast: f32, brightness: f32) -> LumaImage {
    let data = img
        .data()
        .iter()
        .map(|&px| {
            let adjusted = ((f32::from(px) * brightness) - 128.0) * contrast + 128.0;
            #[expect(
                clippy::cast_possible_truncation,
                clippy::cast_sign_loss,
                reason = "clamped to 0.0..=255.0 on the previous line"
            )]
            {
                adjusted.clamp(0.0, 255.0) as u8
            }
        })
        .collect();
    LumaImage::new(data, img.width(), img.height())
}

/// Separable windowed-minimum filter (grayscale erosion). Dark structures
/// GROW by `(k-1)/2` pixels in every direction — on blob/dot pixel styles
/// this closes the gaps between sub-module blobs so grid sampling reads
/// solid modules instead of gap-noise. `k` is the full window side; even
/// values are bumped to the next odd. Output is identical to the naive
/// `O(w·h·k)` fold; the sliding-deque core makes it `O(w·h)` regardless of
/// window size (a single value-pinned test guards the two-impl equivalence).
pub(crate) fn min_filter(img: &LumaImage, k: u32) -> LumaImage {
    morph_filter(img, k, MorphPick::Min)
}

/// Separable windowed-maximum filter (grayscale dilation) — the mirror of
/// [`min_filter`] for LIGHT blob structures (light-on-dark styles).
pub(crate) fn max_filter(img: &LumaImage, k: u32) -> LumaImage {
    morph_filter(img, k, MorphPick::Max)
}

/// Extremum direction for the morphological pass.
#[derive(Clone, Copy)]
enum MorphPick {
    Min,
    Max,
}

impl MorphPick {
    /// `true` when `candidate` makes `incumbent` redundant for every FUTURE
    /// window (i.e. candidate is at-least-as-extreme) — the monotonic-deque
    /// eviction test. `>=` / `<=` (not strict) keeps the LAST equal index,
    /// which matches the naive fold's value (ties pick the same u8 anyway).
    #[inline]
    fn dominates(self, candidate: u8, incumbent: u8) -> bool {
        match self {
            Self::Min => candidate <= incumbent,
            Self::Max => candidate >= incumbent,
        }
    }
}

/// 1D clamped-border windowed extremum via a monotonic deque — `out[i]` =
/// extremum over `src[i-r ..= i+r]` clamped to `[0, n-1]`. Amortized O(n):
/// each index enters and leaves `deque` once. Bit-identical to the naive
/// `fold` over the same clamped window. `deque`/`out` are caller-owned
/// scratch (reused across rows/cols), `src` may be strided via `stride`.
fn windowed_extremum_strided(
    src: &[u8],
    n: usize,
    stride: usize,
    r: usize,
    pick: MorphPick,
    deque: &mut Vec<usize>,
    out: &mut [u8],
) {
    deque.clear();
    // `head` points at the front (current extremum index) of `deque`.
    let mut head = 0usize;
    // seed the window for output 0: indices 0 ..= min(r, n-1)
    for j in 0..=r.min(n - 1) {
        let v = src[j * stride];
        while deque.len() > head && pick.dominates(v, src[deque[deque.len() - 1] * stride]) {
            deque.pop();
        }
        deque.push(j);
    }
    for i in 0..n {
        // window for i is [i-r, i+r] clamped; right edge enters first
        let hi = (i + r).min(n - 1);
        // push indices up to `hi` that have not been pushed yet
        // (already seeded up to min(r, n-1); subsequent i grow `hi` by ≤1)
        if i > 0 {
            let prev_hi = (i - 1 + r).min(n - 1);
            for j in (prev_hi + 1)..=hi {
                let v = src[j * stride];
                while deque.len() > head && pick.dominates(v, src[deque[deque.len() - 1] * stride])
                {
                    deque.pop();
                }
                deque.push(j);
            }
        }
        // expire the left edge: drop front indices < i-r
        let lo = i.saturating_sub(r);
        while deque[head] < lo {
            head += 1;
        }
        out[i * stride] = src[deque[head] * stride];
    }
}

fn morph_filter(img: &LumaImage, k: u32, pick: MorphPick) -> LumaImage {
    let r = ((k.max(3) | 1) / 2) as usize; // odd window, radius ≥ 1
    let (w, h) = (img.width() as usize, img.height() as usize);
    let (rx, ry) = (r.min(w.saturating_sub(1)), r.min(h.saturating_sub(1)));
    if rx == 0 && ry == 0 {
        return img.clone();
    }
    let src = img.data();
    let mut deque: Vec<usize> = Vec::with_capacity(2 * r + 2);
    // horizontal pass: out[y][x] = pick over src[y][x-rx ..= x+rx] (clamped)
    let mut horiz = vec![0u8; w * h];
    for y in 0..h {
        let row = &src[y * w..(y + 1) * w];
        let out = &mut horiz[y * w..(y + 1) * w];
        windowed_extremum_strided(row, w, 1, rx, pick, &mut deque, out);
    }
    // vertical pass on the horizontal result — stride = w (column walk).
    let mut data = vec![0u8; w * h];
    for x in 0..w {
        windowed_extremum_strided(&horiz[x..], h, w, ry, pick, &mut deque, &mut data[x..]);
    }
    #[expect(
        clippy::cast_possible_truncation,
        reason = "w/h come from the source image's u32 dimensions"
    )]
    LumaImage::new(data, w as u32, h as u32)
}

/// Deterministic gaussian blur (separable, via the image crate).
/// On artistic codes a light blur averages art texture into module means.
pub(crate) fn gaussian_blur(img: &LumaImage, sigma: f32) -> LumaImage {
    let Some(buffer) = image::ImageBuffer::<image::Luma<u8>, _>::from_raw(
        img.width(),
        img.height(),
        img.data().to_vec(),
    ) else {
        return img.clone();
    };
    let blurred = image::imageops::blur(&buffer, sigma);
    let (w, h) = (blurred.width(), blurred.height());
    LumaImage::new(blurred.into_raw(), w, h)
}

/// How many pixels of `data` hold each value: four counters per value, one
/// for each pixel position modulo four, added up at the end. The count is
/// the same sum; [`otsu_threshold`] says why it is split.
fn histogram(data: &[u8]) -> [u64; 256] {
    let mut lanes = [[0u64; 256]; 4];
    let (quads, rest) = data.as_chunks::<4>();
    for quad in quads {
        for (lane, &px) in lanes.iter_mut().zip(quad) {
            lane[usize::from(px)] += 1;
        }
    }
    for &px in rest {
        lanes[0][usize::from(px)] += 1;
    }
    let mut histogram = [0u64; 256];
    for lane in &lanes {
        for (count, own) in histogram.iter_mut().zip(lane) {
            *count += own;
        }
    }
    histogram
}

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

    use super::*;
    use crate::input::{ImageInput, Limits};

    fn luma(data: &[u8], w: u32, h: u32) -> LumaImage {
        LumaImage::new(data.to_vec(), w, h)
    }

    #[test]
    fn otsu_splits_a_bimodal_image_exactly() {
        let img = luma(&[10, 10, 200, 200], 2, 2);
        let out = otsu_threshold(&img);
        assert_eq!(out.data(), &[0, 0, 255, 255]);
    }

    #[test]
    fn min_filter_grows_dark_pixel_to_exact_kernel_block() {
        // single dark pixel at the center of a 5×5 white field
        let mut data = vec![255u8; 25];
        data[12] = 0;
        let out = min_filter(&luma(&data, 5, 5), 3);
        let mut want = [255u8; 25];
        for y in 1..=3 {
            for x in 1..=3 {
                want[y * 5 + x] = 0;
            }
        }
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn max_filter_is_the_exact_mirror_on_inverted_input() {
        let mut data = vec![0u8; 25];
        data[12] = 255;
        let out = max_filter(&luma(&data, 5, 5), 3);
        let mut want = [0u8; 25];
        for y in 1..=3 {
            for x in 1..=3 {
                want[y * 5 + x] = 255;
            }
        }
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn morph_filter_runs_the_vertical_pass_on_single_column_images() {
        // 1×3 column: rx = 0 but ry = 1 — the vertical pass must still run
        // (the early-return fires only when BOTH radii collapse).
        let out = min_filter(&luma(&[200, 5, 200], 1, 3), 3);
        assert_eq!(out.data(), &[5, 5, 5]);
        // true no-op case: 1×1
        let out = min_filter(&luma(&[42], 1, 1), 9);
        assert_eq!(out.data(), &[42]);
    }

    #[test]
    fn morph_filter_clamps_kernel_to_image_and_bumps_even_k() {
        // k=4 bumps to 5 (radius 2); on a 3×3 image the radius clamps to 2…
        // then to dim-1=2 — a corner dark pixel floods the full image.
        let mut data = vec![255u8; 9];
        data[0] = 7;
        let out = min_filter(&luma(&data, 3, 3), 4);
        assert!(out.data().iter().all(|&p| p == 7), "{:?}", out.data());
        // k below the floor (k=1) behaves as k=3
        let single = min_filter(&luma(&[9, 255], 2, 1), 1);
        assert_eq!(single.data(), &[9, 9]);
    }

    /// Naive O(w·h·k) clamped-window extremum — the REFERENCE the fast
    /// sliding-deque `morph_filter` must reproduce bit-for-bit. This is the
    /// exact algorithm the crate shipped before the deque rewrite.
    fn morph_naive(img: &LumaImage, k: u32, pick: fn(u8, u8) -> u8) -> Vec<u8> {
        let r = ((k.max(3) | 1) / 2) as usize;
        let (w, h) = (img.width() as usize, img.height() as usize);
        let (rx, ry) = (r.min(w.saturating_sub(1)), r.min(h.saturating_sub(1)));
        if rx == 0 && ry == 0 {
            return img.data().to_vec();
        }
        let src = img.data();
        let mut horiz = vec![0u8; w * h];
        for y in 0..h {
            let row = &src[y * w..(y + 1) * w];
            for x in 0..w {
                let lo = x.saturating_sub(rx);
                let hi = (x + rx).min(w - 1);
                horiz[y * w + x] = row[lo..=hi].iter().copied().fold(row[x], pick);
            }
        }
        let mut data = vec![0u8; w * h];
        for y in 0..h {
            let lo = y.saturating_sub(ry);
            let hi = (y + ry).min(h - 1);
            for x in 0..w {
                let mut acc = horiz[lo * w + x];
                for row in (lo + 1)..=hi {
                    acc = pick(acc, horiz[row * w + x]);
                }
                data[y * w + x] = acc;
            }
        }
        data
    }

    /// The deque rewrite is an O(w·h) optimization that MUST be output-
    /// identical to the naive fold for every shape and kernel — a divergence
    /// would silently change which artistic codes the morph rungs recover.
    /// Deterministic LCG covers a spread of dims (incl. 1×N, N×1, even/odd k).
    #[test]
    fn morph_deque_matches_naive_fold_exhaustively() {
        let mut seed = 0x9E37_79B9_7F4A_7C15u64;
        let mut next = |bound: u32| -> u32 {
            seed = seed
                .wrapping_mul(6_364_136_223_846_793_005)
                .wrapping_add(1_442_695_040_888_963_407);
            (seed >> 33) as u32 % bound
        };
        for _ in 0..240 {
            let w = 1 + next(40);
            let h = 1 + next(40);
            let k = 1 + next(23); // spans below-floor, even, odd, > dim
            #[expect(clippy::cast_possible_truncation, reason = "next(256) ∈ 0..256")]
            let data: Vec<u8> = (0..w * h).map(|_| next(256) as u8).collect();
            let img = luma(&data, w, h);
            assert_eq!(
                min_filter(&img, k).data(),
                &morph_naive(&img, k, u8::min)[..],
                "MIN mismatch w={w} h={h} k={k}"
            );
            assert_eq!(
                max_filter(&img, k).data(),
                &morph_naive(&img, k, u8::max)[..],
                "MAX mismatch w={w} h={h} k={k}"
            );
        }
    }

    #[test]
    fn otsu_flat_image_maps_to_white() {
        // Convention pinned: luma > otsu-threshold → 255 (flat lands all-white).
        let img = luma(&[128; 9], 3, 3);
        let out = otsu_threshold(&img);
        assert_eq!(out.data(), &[255; 9]);
    }

    #[test]
    fn invert_is_exact() {
        let img = luma(&[0, 128, 255], 3, 1);
        let out = invert(&img);
        assert_eq!(out.data(), &[255, 127, 0]);
    }

    #[test]
    fn contrast_stretch_min_max_full_range() {
        let img = luma(&[100, 150, 125], 3, 1);
        let out = contrast_stretch(&img);
        assert_eq!(out.data(), &[0, 255, 127]);
    }

    #[test]
    fn contrast_stretch_flat_image_unchanged() {
        let img = luma(&[7, 7, 7, 7], 2, 2);
        let out = contrast_stretch(&img);
        assert_eq!(out.data(), &[7, 7, 7, 7]);
    }

    #[test]
    fn downscale_averages_blocks_exactly() {
        // 4x4 with 2x2 uniform blocks of 0 / 40 / 200 / 100.
        #[rustfmt::skip]
        let img = luma(&[
            0, 0, 40, 40,
            0, 0, 40, 40,
            200, 200, 100, 100,
            200, 200, 100, 100,
        ], 4, 4);
        let out = downscale_to(&img, 2);
        assert_eq!((out.width(), out.height()), (2, 2));
        assert_eq!(out.data(), &[0, 40, 200, 100]);
    }

    #[test]
    fn downscale_noop_when_already_small() {
        let img = luma(&[1, 2, 3, 4], 2, 2);
        let out = downscale_to(&img, 512);
        assert_eq!(out.data(), img.data());
        assert_eq!((out.width(), out.height()), (2, 2));
    }

    #[test]
    fn contrast_boost_matches_v02_semantics() {
        let img = luma(&[100, 200, 128], 3, 1);
        let out = contrast_boost(&img, 2.0, 1.0);
        // ((100-128)*2)+128 = 72 · ((200-128)*2)+128 = 272→255 · 128 fixed point
        assert_eq!(out.data(), &[72, 255, 128]);
    }

    #[test]
    fn contrast_boost_brightness_applies_before_contrast() {
        let img = luma(&[100], 1, 1);
        let out = contrast_boost(&img, 2.0, 1.1);
        // ((100*1.1)-128)*2+128 = 92
        assert_eq!(out.data(), &[92]);
    }

    #[test]
    fn gaussian_blur_spreads_an_impulse_deterministically() {
        let mut data = vec![0u8; 25];
        data[12] = 255;
        let img = luma(&data, 5, 5);
        let a = gaussian_blur(&img, 1.0);
        let b = gaussian_blur(&img, 1.0);
        assert_eq!(a.data(), b.data(), "blur must be deterministic");
        assert!(a.data()[12] < 255, "center spread out");
        assert!(
            a.data()[11] > 0 && a.data()[7] > 0,
            "neighbors received mass"
        );
        assert_eq!((a.width(), a.height()), (5, 5));
    }

    #[test]
    fn rgba_source_extracts_channels() {
        // red px, green px
        let rgba = [255u8, 0, 0, 255, 0, 255, 0, 255];
        let planes = normalize(&ImageInput::rgba8(&rgba, 2, 1), &Limits::default()).unwrap();
        let r = planes.channel(Channel::R).expect("rgb retained");
        assert_eq!(r.data(), &[255, 0]);
        let g = planes.channel(Channel::G).expect("rgb retained");
        assert_eq!(g.data(), &[0, 255]);
    }

    #[test]
    fn encoded_color_source_extracts_channels_lazily() {
        // 2x1 png: pure blue then pure red
        let mut img = image::RgbImage::new(2, 1);
        img.put_pixel(0, 0, image::Rgb([0, 0, 255]));
        img.put_pixel(1, 0, image::Rgb([255, 0, 0]));
        let mut buf = Vec::new();
        image::DynamicImage::ImageRgb8(img)
            .write_to(&mut std::io::Cursor::new(&mut buf), image::ImageFormat::Png)
            .unwrap();

        let planes = normalize(&ImageInput::encoded(&buf), &Limits::default()).unwrap();
        let b = planes.channel(Channel::B).expect("color png has channels");
        assert_eq!(b.data(), &[255, 0]);
    }

    #[test]
    fn luma_source_has_no_channels() {
        let data = [0u8, 255];
        let planes = normalize(&ImageInput::luma8(&data, 2, 1), &Limits::default()).unwrap();
        assert!(planes.channel(Channel::R).is_none());
        assert_eq!(planes.luma.data(), &[0, 255]);
    }

    // ---------------------------------------------------------------------
    // Golden-value pins — expected outputs computed BY HAND (in comments)
    // from the algorithm, NOT frozen from `fn` output, so a regression in
    // the arithmetic is caught rather than blessed. Cover the otsu variance
    // argmax + tie-break, the separable morph passes end-to-end, and the
    // box-downscale dimension math + truncation.
    // ---------------------------------------------------------------------

    #[test]
    fn otsu_unbalanced_classes_pin_the_variance_argmax() {
        // 8 px @40 · 4 px @120 · 4 px @200 (total 16, weighted_sum 1600).
        // Between-class variance ω_bg·ω_fg·(μ_bg−μ_fg)² over the 3 candidate
        // thresholds that add mass:
        //   t=40  → 8·8·(40−160)²   = 64·14400 = 921600  ← unique max
        //   t=120 → 12·4·(66.67−200)² ≈ 48·17778 ≈ 853333
        //   t=200 → foreground empty, loop breaks
        // argmax threshold = 40, and the binarize step maps px>40 → 255. A
        // mutation that shifts the argmax to 120 would flip the 120-row to 0.
        #[rustfmt::skip]
        let img = luma(&[
            40,  40,  40,  40,
            40,  40,  40,  40,
            120, 120, 120, 120,
            200, 200, 200, 200,
        ], 4, 4);
        let out = otsu_threshold(&img);
        let want = [
            0u8, 0, 0, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255,
        ];
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn otsu_variance_tie_keeps_the_lower_threshold() {
        // 6 px @40 · 4 px @120 · 6 px @200 (total 16, weighted_sum 1920).
        //   t=40  → 6·10·(40−168)²  = 60·16384 = 983040
        //   t=120 → 10·6·(72−200)²  = 60·16384 = 983040  (EXACT f64 tie)
        // The comparison is strict `variance > best_variance`, so the FIRST
        // (lower) threshold 40 wins the tie. A `>=` mutation would advance to
        // 120 and drop the 120-cluster below the cut → observable flip.
        #[rustfmt::skip]
        let img = luma(&[
            40,  40,  40,  40,
            40,  40,  120, 120,
            120, 120, 200, 200,
            200, 200, 200, 200,
        ], 4, 4);
        let out = otsu_threshold(&img);
        // threshold 40 → px>40 ? 255 : 0
        let want = [
            0u8, 0, 0, 0, 0, 0, 255, 255, 255, 255, 255, 255, 255, 255, 255, 255,
        ];
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn otsu_uniform_zero_image_maps_to_black() {
        // All-zero: t=0 adds every pixel to background, foreground is empty →
        // the loop breaks at the first step with best_threshold still 0. The
        // binarize is px>0, so 0 is NOT > 0 → the whole image lands black.
        // (Mirror of `otsu_flat_image_maps_to_white`, which pins the >0 case.)
        let img = luma(&[0; 9], 3, 3);
        let out = otsu_threshold(&img);
        assert_eq!(out.data(), &[0; 9]);
    }

    #[test]
    fn min_filter_closes_a_one_pixel_gap_and_dilates_the_dark_bar() {
        // 8×8 white field with a dark bar on row 3 broken by a 1px light gap
        // at col 4. min_filter (windowed minimum, k=3 → radius 1) is a
        // grayscale erosion of the light / dilation of the dark.
        let mut data = [255u8; 64];
        data[3 * 8..4 * 8].copy_from_slice(&[255, 0, 0, 0, 255, 0, 0, 255]);
        let out = min_filter(&luma(&data, 8, 8), 3);
        // Horizontal pass: every row-3 cell has a dark neighbour, so the whole
        // row collapses to 0 (the col-4 gap closes AND the bar reaches the
        // borders). Vertical pass then grows that solid dark row up into row 2
        // and down into row 4. Rows 0,1,5,6,7 stay white.
        let mut want = [255u8; 64];
        for row in 2..=4 {
            for col in 0..8 {
                want[row * 8 + col] = 0;
            }
        }
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn max_filter_mirrors_the_gap_close_on_light_structures() {
        // Photometric mirror of the min case: dark field, a light bar on row 3
        // with a 1px dark gap at col 4. max_filter (windowed maximum) grows
        // the LIGHT structure, so the mirrored output is rows 2,3,4 all white.
        let mut data = [0u8; 64];
        data[3 * 8..4 * 8].copy_from_slice(&[0, 255, 255, 255, 0, 255, 255, 0]);
        let out = max_filter(&luma(&data, 8, 8), 3);
        let mut want = [0u8; 64];
        for row in 2..=4 {
            for col in 0..8 {
                want[row * 8 + col] = 255;
            }
        }
        assert_eq!(out.data(), &want[..]);
    }

    #[test]
    fn morph_filter_on_a_uniform_field_is_identity() {
        // No structure to erode/dilate: every window extremum is the field
        // value. This exercises the FULL two-pass path (an 8×8 does not hit
        // the collapsed-radius early return) yet must return the input.
        let img = luma(&[128u8; 64], 8, 8);
        assert_eq!(min_filter(&img, 3).data(), img.data());
        assert_eq!(max_filter(&img, 5).data(), img.data());
    }

    #[test]
    fn downscale_odd_dimension_uses_uneven_boxes() {
        // 5×5 → longest side 5 > max_side 2 → new dims (5·2/5)=2 each. The
        // source→dest box mapping is uneven: rows/cols split {0,1} | {2,3,4},
        // so the four output boxes cover 2×2, 2×3, 3×2, 3×3 source pixels.
        // Each box below is filled with one value so its mean is exact.
        #[rustfmt::skip]
        let img = luma(&[
            40,  40,  100, 100, 100,
            40,  40,  100, 100, 100,
            200, 200, 130, 130, 130,
            200, 200, 130, 130, 130,
            200, 200, 130, 130, 130,
        ], 5, 5);
        let out = downscale_to(&img, 2);
        assert_eq!((out.width(), out.height()), (2, 2));
        // (0,0)=mean(40)=40 · (0,1)=mean(100)=100 · (1,0)=mean(200)=200 ·
        // (1,1)=mean(130)=130
        assert_eq!(out.data(), &[40, 100, 200, 130]);
    }

    #[test]
    fn downscale_truncates_the_box_mean() {
        // 2×2 → 1×1: the single output pixel is the integer (truncating) mean
        // of all four. (10+20+30+41)/4 = 101/4 = 25 — NOT 25.25 rounded to 25
        // by luck; a `+1` or rounding mutation on the divide would read 26.
        let img = luma(&[10, 20, 30, 41], 2, 2);
        let out = downscale_to(&img, 1);
        assert_eq!((out.width(), out.height()), (1, 1));
        assert_eq!(out.data(), &[25]);
    }

    // ---------------------------------------------------------------------
    // Mutant-harvest pins (weekly deep-checks run 28740297335) — each test
    // documents WHICH surviving mutant its assertion traps, by line.
    // ---------------------------------------------------------------------

    /// `has_color` gates the ladder's per-channel enhance rungs; a `-> false`
    /// stub (:36) silently disables channel splitting for every color source
    /// (plain codes still decode off luma, so no e2e test notices). Pin the
    /// flag on both sides of the source kind.
    #[test]
    fn has_color_reflects_the_source_kind() {
        let rgba = [10u8, 20, 30, 255];
        let planes = normalize(&ImageInput::rgba8(&rgba, 1, 1), &Limits::default()).unwrap();
        assert!(planes.has_color(), "an rgba source retains color planes");
        let planes = normalize(&ImageInput::luma8(&[7], 1, 1), &Limits::default()).unwrap();
        assert!(!planes.has_color(), "a luma source has no color planes");
    }

    /// The variance argmax must start BELOW every real candidate. With two
    /// pixels {100, 101} the single computed variance is EXACTLY
    /// 1·1·(100−101)² = 1.0 (integers are exact in f64), so the −1.0 init
    /// admits it and t=100 wins → [0, 255]. A `delete -` on the init (:150)
    /// starts the argmax at +1.0; strict `>` then rejects the candidate, the
    /// threshold stays 0, and the whole image flips light → [255, 255].
    #[test]
    fn otsu_two_pixel_split_needs_the_negative_variance_init() {
        let img = luma(&[100, 101], 2, 1);
        let out = otsu_threshold(&img);
        assert_eq!(out.data(), &[0, 255]);
    }

    /// 2@0 · 3@5 · 1@20 pins the mean/weight arithmetic of the variance
    /// argmax (every quantity below is a dyadic rational — exact in f64):
    ///   t=0: ω 2·4 · (0 − 35/4)² = 8·76.5625 = 612.5
    ///   t=5: ω 5·1 · (3 − 20)²   = 5·289     = 1445   ← argmax → px > 5
    /// Four harvest survivors all flip the argmax to t=0, misreading the
    /// 5-cluster as light ([0,0,255,255,255,255]):
    ///   :164 `/`→`*` — `μ_fg` = rest·count = 140 → t=0 var 156 800 ≫ 1445
    ///   :166:48 `*`→`+` — var = `ω_bg` + `ω_fg`·sep² → t=0 308.25 > t=5 294
    ///   :166:74/:87 `*`→`/` — var ≈ `ω_bg`·`ω_fg` → t=0 8 > t=5 5
    #[test]
    fn otsu_argmax_weighs_class_balance_times_separation_squared() {
        let img = luma(&[0, 0, 5, 5, 5, 20], 6, 1);
        let out = otsu_threshold(&img);
        assert_eq!(out.data(), &[0, 0, 0, 0, 0, 255]);
    }

    /// The seed loop's `r.min(n − 1)` clamp (:334) is load-bearing for
    /// oversized radii: the fn contract clamps the window to [0, n−1] for ANY
    /// r, and `morph_filter`'s own radius clamp never exercises r ≥ n. The
    /// harvest mutants `n − 1` → `n + 1` / `n / 1` seed one index past the
    /// slice and die on out-of-bounds instead of returning the fully clamped
    /// extremum (the global min/max replicated).
    #[test]
    fn windowed_extremum_oversized_radius_clamps_at_the_seed() {
        let src = [7u8, 200, 3];
        let mut deque = Vec::new();
        let mut out = [0u8; 3];
        windowed_extremum_strided(&src, 3, 1, 5, MorphPick::Min, &mut deque, &mut out);
        assert_eq!(out, [3, 3, 3]);
        windowed_extremum_strided(&src, 3, 1, 5, MorphPick::Max, &mut deque, &mut out);
        assert_eq!(out, [200, 200, 200]);
    }

    /// r = 0 is a legal degenerate window ([i, i] — the identity map) that
    /// `morph_filter`'s radius floor (≥ 1) never produces — pin it by direct
    /// call. At i=1, `prev_hi` = (i−1+r).min(n−1) = 0 and the catch-up loop
    /// starts at `prev_hi + 1`; the harvest mutant `+`→`−` (:348) computes
    /// 0 − 1 and dies on usize underflow instead of walking [1, hi].
    #[test]
    fn windowed_extremum_zero_radius_is_identity() {
        let src = [9u8, 1, 5, 5, 2];
        let mut deque = Vec::new();
        let mut out = [0u8; 5];
        windowed_extremum_strided(&src, 5, 1, 0, MorphPick::Min, &mut deque, &mut out);
        assert_eq!(out, [9, 1, 5, 5, 2]);
        windowed_extremum_strided(&src, 5, 1, 0, MorphPick::Max, &mut deque, &mut out);
        assert_eq!(out, [9, 1, 5, 5, 2]);
    }

    /// A TRUE strided pass (stride > 1, asymmetric window) — the incremental
    /// catch-up `let prev_hi = (i - 1 + r).min(n - 1); for j in (prev_hi + 1)..=hi`
    /// only runs the STRIDED path via `morph_filter`'s vertical column walk.
    /// The window minimum/maximum ENTERS at the last index, so an `i - 1`
    /// mutation (→ `i + 1` / `i / 1`) fails to push the newly-arriving index
    /// and misreads the tail (in fact it walks the deque head off the end and
    /// panics). The `prev_hi + 1 → prev_hi * 1` slip is a proven idempotent
    /// re-push of the monotonic deque's back element (justified in the commit).
    #[test]
    fn windowed_extremum_strided_slides_with_a_real_stride() {
        // logical values [50,40,60,45,10] at stride-2 slots; 255 = filler.
        let src = [50u8, 255, 40, 255, 60, 255, 45, 255, 10];
        let mut deque = Vec::new();
        let mut out = [0u8; 9];
        windowed_extremum_strided(&src, 5, 2, 1, MorphPick::Min, &mut deque, &mut out);
        // window [i-1,i+1] clamped: min(50,40)=40 · min(50,40,60)=40 ·
        // min(40,60,45)=40 · min(60,45,10)=10 · min(45,10)=10
        assert_eq!(
            [out[0], out[2], out[4], out[6], out[8]],
            [40, 40, 40, 10, 10]
        );
        // MAX mirror — the extremum enters at the tail here too.
        windowed_extremum_strided(&src, 5, 2, 1, MorphPick::Max, &mut deque, &mut out);
        // max(50,40)=50 · max(50,40,60)=60 · max(40,60,45)=60 ·
        // max(60,45,10)=60 · max(45,10)=45
        assert_eq!(
            [out[0], out[2], out[4], out[6], out[8]],
            [50, 60, 60, 60, 45]
        );
    }

    /// Raw RGBA flattens only when both hold, a flattening mode and a
    /// transparent pixel: an opaque frame under `auto` and a transparent
    /// one under `none` take the drop-the-alpha loop (no alpha context, the
    /// luma of their straight RGB); the same transparent frame under
    /// `white` flattens.
    #[test]
    fn raw_rgba_flattens_only_transparency_under_a_flattening_mode() {
        let scan = |data: &[u8], mode| {
            normalize_with(&ImageInput::rgba8(data, 2, 1), &Limits::default(), mode).unwrap()
        };
        let straight = [bt601(10, 20, 30), bt601(200, 100, 50)];
        let opaque = scan(&[10, 20, 30, 255, 200, 100, 50, 255], AlphaBackground::Auto);
        assert!(
            opaque.alpha.is_none(),
            "an opaque frame keeps no alpha context"
        );
        assert_eq!(opaque.planes.luma.data(), straight);
        let transparent = [10, 20, 30, 0, 200, 100, 50, 255];
        let kept = scan(&transparent, AlphaBackground::None);
        assert!(kept.alpha.is_none(), "`none` never flattens");
        assert_eq!(kept.planes.luma.data(), straight);
        let flattened = scan(&transparent, AlphaBackground::White);
        assert!(
            flattened.alpha.is_some(),
            "`white` flattens a transparent frame"
        );
        assert_eq!(flattened.planes.luma.data(), [255, straight[1]]);
    }

    #[test]
    fn flattened_rgba_retains_exact_rgb_capacity_and_pixels() {
        let rgba = [10, 20, 30, 128].repeat(17);
        let normalized = normalize_with(
            &ImageInput::rgba8(&rgba, 17, 1),
            &Limits::default(),
            AlphaBackground::White,
        )
        .unwrap();

        // Inspect the retained Vec: cloning or channel extraction can hide
        // excess capacity. This pins capacity, not allocator calls or RSS.
        let rgb = normalized.planes.rgb.as_ref().unwrap();
        assert_eq!(rgb.len(), 51);
        assert_eq!(rgb.capacity(), 51);
        assert_eq!(rgb.as_slice(), [132, 137, 142].repeat(17));
        assert_eq!(normalized.planes.luma.width(), 17);
        assert_eq!(normalized.planes.luma.height(), 1);
        assert_eq!(normalized.planes.luma.data(), [136; 17]);

        let alpha = normalized.alpha.unwrap().into_report(false, None);
        assert_eq!(alpha.mode, crate::report::AlphaMode::White);
        assert_eq!(alpha.background, "white");
        assert_eq!(alpha.coverage.to_bits(), 1.0_f32.to_bits());
        assert_eq!(alpha.content_luma, 18);
    }

    #[test]
    fn the_histogram_counts_every_pixel_once_at_any_length() {
        // lengths around the four-pixel stride, and values that repeat
        // within a stride and across strides
        for len in 0..=13_usize {
            let data: Vec<u8> = (0..len)
                .map(|i| [7, 7, 200, 7, 0, 255, 200][i % 7])
                .collect();
            let mut want = [0u64; 256];
            for &px in &data {
                want[usize::from(px)] += 1;
            }
            assert_eq!(histogram(&data), want, "{len} pixels");
        }
    }
}