rust-j2k 0.5.0

Decodes JPEG 2000 images in pure Rust, for programs that need to read them without linking a C library.
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
//! Decoder output: the image area on the reference grid, and one integer
//! component per output channel, each in raster order on its own sample grid,
//! plus the metadata a caller needs to interpret the samples (bit depth,
//! signedness, sub-sampling).

use crate::codestream::MainHeader;
use crate::codestream::markers::{Rect, Siz, Transform};
use crate::pipeline::Samples;
use crate::{DecodeReport, Error, Jp2Metadata, Result};

/// A decoded image: the image area on the reference grid, plus its components.
///
/// [`width`](Self::width) and [`height`](Self::height) describe the *reference
/// grid* image area (`Xsiz - XOsiz` by `Ysiz - YOsiz`), which is the coordinate
/// space the components are registered against. Under a resolution reduction
/// of `r` levels they are that area at the reduced resolution:
/// `ceil(Xsiz / 2^r) - ceil(XOsiz / 2^r)` by the same in y. A sub-sampled component covers
/// that same area with fewer samples, so its own
/// [`Component::width`]/[`Component::height`] can be smaller. With unit
/// sub-sampling, the common case, they are equal. A decode of part of the
/// image (a window or a tile in
/// [`region`](crate::DecodeOptions::region)) has that part as its area, in the
/// same formulas with the part's bounds for `XOsiz..Xsiz` and `YOsiz..Ysiz`.
///
/// Components are in output-channel order. For a raw codestream that is SIZ
/// order; a JP2 file's palette, channel definitions and sRGB option can change
/// the channels (see [`components`](Self::components)). The codestream's
/// inter-component (color) transform, and a JP2 file's palette and channel
/// definitions, are part of decoding (unless
/// [`raw_channels`](crate::DecodeOptions::raw_channels) is set); no color
/// conversion is applied unless the caller asks for sRGB output.
///
/// The struct is `#[non_exhaustive]`, so fields can be added without a
/// breaking change, and [`decode`](crate::decode) is the normal producer. To
/// build one by hand, such as an expected image in a test harness, use
/// [`Image::new`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Image {
    /// The image area's width: reference-grid points, or points of the
    /// reduced grid under a resolution reduction.
    pub width: u32,
    /// The image area's height, as [`width`](Self::width).
    pub height: u32,
    /// One entry per output channel, or per entry of
    /// [`components`](crate::DecodeOptions::components) when it is set. For a
    /// raw codestream, and for a JP2 file
    /// with no palette, no channel definitions and as-coded output, that is one
    /// per SIZ component, in SIZ order. A palette makes one channel per
    /// palette column, channel definitions put the color channels in color
    /// order, and sRGB output can change the count (a monochrome profile can
    /// give three). Never empty in decoder output.
    pub components: Vec<Component>,
    /// What the JP2 wrapper said about the samples: their color space and
    /// what each channel is. `None` for a raw codestream.
    pub jp2: Option<Jp2Metadata>,
    /// What the decode left out. A strict decode (the default) gives the
    /// complete report, [`DecodeReport::default`]; with
    /// [`strict`](crate::DecodeOptions::strict) off it lists what was missing
    /// or skipped. `Image`'s `PartialEq` compares the report too, so two
    /// images with the same samples and different reports are not equal.
    pub report: DecodeReport,
}

/// One decoded component: its own sample grid, its declared depth and sign, and
/// the sub-sampling that maps it onto the image's reference grid.
///
/// `samples` is row-major, `width * height` entries, each already
/// DC-level-shifted and clamped to the declared depth.
///
/// A channel made by a JP2 palette (`pclr`) is different: its depth and sign
/// come from the palette's `Bi` (for a direct channel `i`, from column `i`),
/// and its samples are the palette entries as stored (for a direct channel,
/// the component's samples). Its samples can fall outside the range that depth
/// and sign declare, as in OpenJPEG.
///
/// `#[non_exhaustive]`, like [`Image`]; build one by hand with
/// [`Component::new`].
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct Component {
    /// Component width in samples.
    pub width: u32,
    /// Component height in samples.
    pub height: u32,
    /// Bits per sample as declared in SIZ `Ssiz`, or by the palette for a
    /// palette channel: 1 to 31 for unsigned samples, 1 to 32 for signed ones
    /// (the `i32` container holds both).
    ///
    /// Except in a palette channel (see [`Component`]), unsigned samples run
    /// from 0 to `2^bit_depth - 1`; signed samples from
    /// `-2^(bit_depth - 1)` to `2^(bit_depth - 1) - 1`. To map a signed
    /// sample to an unsigned one, add `2^(bit_depth - 1)` (do it in `i64`,
    /// since the sum overflows `i32` at 32 bits).
    pub bit_depth: u8,
    /// Whether samples are signed (SIZ component sign bit, or the palette's).
    pub signed: bool,
    /// Horizontal sub-sampling factor (SIZ `XRsiz`); `1` means no
    /// sub-sampling.
    pub x_sampling: u8,
    /// Vertical sub-sampling factor (SIZ `YRsiz`); `1` means no
    /// sub-sampling.
    pub y_sampling: u8,
    /// `width * height` samples, row-major.
    pub samples: Vec<i32>,
}

impl Image {
    /// Package `components` with the reference-grid image area they are
    /// registered against, and no JP2 metadata ([`jp2`](Self::jp2) is `None`).
    /// The values are stored as given; only [`decode`](crate::decode) vouches
    /// for their consistency.
    #[must_use]
    pub fn new(width: u32, height: u32, components: Vec<Component>) -> Self {
        Self {
            width,
            height,
            components,
            jp2: None,
            report: DecodeReport::default(),
        }
    }

    /// The component at `index` in [`components`](Self::components) order,
    /// or `None` if out of range.
    pub fn component(&self, index: usize) -> Option<&Component> {
        self.components.get(index)
    }
}

impl Component {
    /// Package a component's samples with their geometry and interpretation.
    /// The values are stored as given; only [`decode`](crate::decode) vouches
    /// for their consistency.
    #[must_use]
    pub fn new(
        width: u32,
        height: u32,
        bit_depth: u8,
        signed: bool,
        x_sampling: u8,
        y_sampling: u8,
        samples: Vec<i32>,
    ) -> Self {
        Self {
            width,
            height,
            bit_depth,
            signed,
            x_sampling,
            y_sampling,
            samples,
        }
    }

    /// Sample at `(x, y)` on this component's own grid, or `None` if out of bounds.
    pub fn sample(&self, x: u32, y: u32) -> Option<i32> {
        if x >= self.width || y >= self.height {
            return None;
        }
        self.samples
            .get((y as usize) * (self.width as usize) + x as usize)
            .copied()
    }
}

/// The per-component sample planes a tiled decode reconstructs into: one plane
/// per SIZ component, sized to that component's whole grid, which each tile
/// writes its own rectangle of.
///
/// Tiles are decoded independently — their own coordinate frame, their own
/// header, their own wavelet pyramid — and the canvas is where they meet again.
/// A tile-component's reconstructed raster is placed at the tile's offset on the
/// component grid; the tiles partition that grid exactly, so every sample is
/// written once. Nothing is blended and no tile overlaps another: the wavelet
/// transform is applied per tile, which is why a tiled encode can show seams,
/// and reproducing them is correct.
///
/// A plane is allocated when its first tile arrives. A tile that covers the
/// whole plane, as the only tile of an image does, becomes the plane: its
/// raster is moved in rather than copied, so the decode never holds two
/// image-sized buffers for one component.
pub(crate) struct Canvas {
    planes: Vec<Option<Samples>>,
    /// Each component's grid at the decode's reduction, over the decoded area
    /// (the whole image, or a window of it): the rectangle a tile's placement
    /// is clipped to.
    rects: Vec<Rect>,
    /// Each component's wavelet, which fixes its plane's arithmetic.
    transforms: Vec<Transform>,
    /// Whether the decode returns each component. Only these get a plane.
    kept: Vec<bool>,
    /// The components the decode returns, in output order.
    order: Vec<usize>,
    /// Whether the decoded area is a window smaller than the image, so a
    /// tile may reach past it. Without one, a tile outside the canvas is a
    /// fault.
    windowed: bool,
}

impl Canvas {
    /// The bytes the planes of the components kept take, once each has
    /// its samples.
    pub(crate) fn bytes(&self) -> u64 {
        self.rects
            .iter()
            .zip(&self.kept)
            .filter(|(_, kept)| **kept)
            .map(|(rect, _)| rect.area().saturating_mul(4))
            .fold(0, u64::saturating_add)
    }

    /// A canvas of every component over the whole image, at `reduction`.
    #[cfg(test)]
    pub(crate) fn new(header: &MainHeader, reduction: u8) -> Result<Self> {
        let order: Vec<usize> = (0..header.siz.components.len()).collect();
        Self::over(header, &header.siz, reduction, &order)
    }

    /// Record each component's grid at the reduced size [`assemble`] will
    /// expect, and its wavelet. `area` is the SIZ of what the decode returns:
    /// `header`'s own, or one [`Siz::windowed`] to a window. `order` lists the
    /// components to keep, in output order, each at most once.
    ///
    /// A plane's arithmetic follows its component's wavelet — 5/3 reconstructs
    /// exact integers, 9/7 reals — which is why `parse` rejects a codestream
    /// whose tiles disagree about a component's wavelet: it would ask one plane
    /// to hold both.
    pub(crate) fn over(
        header: &MainHeader,
        area: &Siz,
        reduction: u8,
        order: &[usize],
    ) -> Result<Self> {
        let count = area.components.len();
        let (mut rects, mut transforms) = (Vec::with_capacity(count), Vec::with_capacity(count));
        let mut kept = vec![false; count];
        for &index in order {
            let slot = kept.get_mut(index).ok_or_else(|| {
                Error::inconsistent(format!("`SIZ` declares no component {index}"))
            })?;
            *slot = true;
        }
        for index in 0..count {
            rects.push(
                area.component_rect(index)
                    .ok_or_else(|| {
                        Error::inconsistent(format!("`SIZ` declares no component {index}"))
                    })?
                    .reduced(reduction),
            );
            transforms.push(
                header
                    .components
                    .get(index)
                    .ok_or_else(|| {
                        Error::inconsistent(format!("no coding parameters for component {index}"))
                    })?
                    .coding
                    .transform,
            );
        }
        Ok(Canvas {
            planes: (0..count).map(|_| None).collect(),
            rects,
            transforms,
            kept,
            order: order.to_vec(),
            windowed: area.image_rect() != header.siz.image_rect(),
        })
    }

    /// Whether the decode returns component `index`.
    pub(crate) fn keeps(&self, index: usize) -> bool {
        self.kept.get(index).copied().unwrap_or(false)
    }

    /// Write the part of one tile-component's reconstructed raster that falls
    /// inside its component's canvas into that plane. `rect` is the
    /// tile-component's rectangle on the component grid, at the same
    /// reduction the canvas was built at. A component the decode does not
    /// return is dropped.
    pub(crate) fn place(&mut self, index: usize, rect: Rect, samples: Samples) -> Result<()> {
        let ((plane, canvas), transform) = self
            .planes
            .get_mut(index)
            .zip(self.rects.get(index))
            .zip(self.transforms.get(index))
            .ok_or_else(|| Error::inconsistent(format!("no canvas plane for component {index}")))?;
        if samples.len() as u64 != rect.area() {
            return Err(Error::inconsistent(format!(
                "component {index} of a tile reconstructed {} samples but its {}x{} rectangle \
                 holds {}",
                samples.len(),
                rect.width(),
                rect.height(),
                rect.area(),
            )));
        }
        if !matches!(
            (transform, &samples),
            (Transform::Reversible53, Samples::Reversible(_))
                | (Transform::Irreversible97, Samples::Irreversible(_))
        ) {
            return Err(Error::inconsistent(format!(
                "a tile reconstructed component {index} on the other wavelet's arithmetic"
            )));
        }
        if !self.kept.get(index).copied().unwrap_or(false) {
            return Ok(());
        }
        // A tile that covers the whole plane writes every sample of it, so its
        // raster is the plane.
        if rect == *canvas {
            *plane = Some(samples);
            return Ok(());
        }
        // The tiles partition the image, so without a window each one falls
        // inside the canvas. A window keeps the part of a tile inside it.
        let clip = rect.intersect(canvas);
        if !self.windowed && clip != rect {
            return Err(Error::inconsistent(format!(
                "a tile's component {index} rectangle {rect:?} falls outside the canvas {canvas:?}",
            )));
        }
        if clip.is_empty() {
            return Ok(());
        }
        let plane = plane.get_or_insert_with(|| zeroed(*transform, canvas.area() as usize));
        let copy = Crop {
            dst_stride: canvas.width() as usize,
            src_stride: rect.width() as usize,
            width: clip.width() as usize,
            height: clip.height() as usize,
            src: ((clip.x0 - rect.x0) as usize, (clip.y0 - rect.y0) as usize),
            dst: (
                (clip.x0 - canvas.x0) as usize,
                (clip.y0 - canvas.y0) as usize,
            ),
        };
        match (plane, samples) {
            (Samples::Reversible(dst), Samples::Reversible(src)) => copy.run(dst, &src),
            (Samples::Irreversible(dst), Samples::Irreversible(src)) => copy.run(dst, &src),
            _ => {
                return Err(Error::inconsistent(format!(
                    "a tile reconstructed component {index} on the other wavelet's arithmetic"
                )));
            }
        }
        Ok(())
    }

    /// The finished planes of the components the decode returns, in output
    /// order, ready for [`assemble`]. A plane no tile reached is all zeros.
    pub(crate) fn into_planes(mut self) -> Vec<Samples> {
        let mut out = Vec::with_capacity(self.order.len());
        for &index in &self.order {
            // `over` checked every index of `order`.
            let plane = self.planes[index].take().unwrap_or_else(|| {
                zeroed(self.transforms[index], self.rects[index].area() as usize)
            });
            out.push(plane);
        }
        out
    }
}

/// A `width` by `height` rectangle copied from one raster to another, from
/// `src` to `dst` (each the `(x, y)` of its top-left in its raster). The
/// caller has already clipped it to both.
struct Crop {
    dst_stride: usize,
    src_stride: usize,
    width: usize,
    height: usize,
    src: (usize, usize),
    dst: (usize, usize),
}

impl Crop {
    fn run<T: Copy>(&self, dst: &mut [T], src: &[T]) {
        for row in 0..self.height {
            let from = (self.src.1 + row) * self.src_stride + self.src.0;
            let to = (self.dst.1 + row) * self.dst_stride + self.dst.0;
            dst[to..to + self.width].copy_from_slice(&src[from..from + self.width]);
        }
    }
}

/// A zeroed plane of `count` samples on `transform`'s arithmetic.
fn zeroed(transform: Transform, count: usize) -> Samples {
    match transform {
        Transform::Reversible53 => Samples::Reversible(vec![0; count]),
        Transform::Irreversible97 => Samples::Irreversible(vec![0.0; count]),
    }
}

/// Copy a `src_width`-wide raster into `dst` (a `stride`-wide raster) with its
/// top-left at `(left, top)`. The caller has already checked that it fits.
pub(crate) fn blit<T: Copy>(
    dst: &mut [T],
    stride: usize,
    src: &[T],
    src_width: usize,
    left: usize,
    top: usize,
) {
    if src_width == 0 {
        return;
    }
    for (row, line) in src.chunks_exact(src_width).enumerate() {
        let start = (top + row) * stride + left;
        dst[start..start + src_width].copy_from_slice(line);
    }
}

/// Final stage: apply the inverse DC level shift, clamp to the component depth,
/// and package the reconstructed samples with their geometry.
///
/// The component geometry follows the SIZ reference-grid equations (ISO/IEC
/// 15444-1 §B.2): for sub-sampling factors `XRsiz`/`YRsiz`,
///
/// ```text
/// width  = ceil(Xsiz / XRsiz) - ceil(XOsiz / XRsiz)
/// height = ceil(Ysiz / YRsiz) - ceil(YOsiz / YRsiz)
/// ```
///
/// which reduces to the image area `Xsiz - XOsiz` by `Ysiz - YOsiz` under unit
/// sub-sampling. The image area itself is carried on the [`Image`].
///
/// The inverse DC level shift (§G.1.2) adds `2^(depth-1)` back to *unsigned*
/// components (the encoder subtracted it before the forward transform); signed
/// components are left as-is. Samples are then clamped to the declared depth
/// and sign before being packed row-major into a [`Component`].
///
/// `samples` carries one reconstructed sample vector per SIZ component, in SIZ
/// order — [`Canvas::into_planes`] output. Each is level-shifted and clamped
/// on its own component's depth and sign, then packed with that component's
/// geometry.
#[cfg(test)]
pub(crate) fn assemble(header: &MainHeader, samples: Vec<Samples>, reduction: u8) -> Result<Image> {
    let order: Vec<usize> = (0..header.siz.components.len()).collect();
    assemble_over(&header.siz, samples, &order, reduction)
}

/// [`assemble`] over `area`, the SIZ of what the decode returns (the
/// codestream's own, or one [`Siz::windowed`] to a window), for the
/// components `order` lists: `samples[i]` is component `order[i]`'s plane.
pub(crate) fn assemble_over(
    area: &Siz,
    samples: Vec<Samples>,
    order: &[usize],
    reduction: u8,
) -> Result<Image> {
    if samples.len() != order.len() {
        return Err(Error::inconsistent(format!(
            "decoded {} components but the decode returns {}",
            samples.len(),
            order.len(),
        )));
    }
    if samples.is_empty() {
        return Err(Error::inconsistent("`SIZ` declares no components"));
    }

    let components = samples
        .into_iter()
        .zip(order)
        .map(|(component_samples, &index)| {
            assemble_component(area, index, component_samples, reduction)
        })
        .collect::<Result<Vec<_>>>()?;

    // At a reduction the image area shrinks with its components, by the same
    // halve-and-round-up per dropped level.
    let (image_width, image_height) = area.image_extent_at(reduction);
    Ok(Image::new(image_width, image_height, components))
}

/// Set tile `tile`'s samples to 0 in every component of `image`, a decode at
/// `reduction` over `area` (see [`assemble_over`]) of the components `order`
/// lists: what a tile no tile-part of reached gives, after the DC level
/// shift, as `opj_decompress -allow-partial` writes it. `siz` is the
/// codestream's, which places the tile.
pub(crate) fn zero_tile(
    image: &mut Image,
    siz: &Siz,
    area: &Siz,
    order: &[usize],
    tile: u32,
    reduction: u8,
) {
    for (component, &comp) in image.components.iter_mut().zip(order) {
        let (Some(rect), Some(canvas)) = (
            siz.tile_component_rect(tile, comp),
            area.component_rect(comp),
        ) else {
            continue;
        };
        let canvas = canvas.reduced(reduction);
        let clip = rect.reduced(reduction).intersect(&canvas);
        if clip.is_empty() {
            continue;
        }
        let width = component.width as usize;
        let x0 = (clip.x0 - canvas.x0) as usize;
        let x1 = (clip.x1 - canvas.x0) as usize;
        for y in clip.y0..clip.y1 {
            let row = (y - canvas.y0) as usize;
            if let Some(line) = component
                .samples
                .get_mut(row * width + x0..row * width + x1)
            {
                line.fill(0);
            }
        }
    }
}

/// Round to the nearest integer, level-shift, clamp, and package one
/// component's reconstructed samples.
///
/// This is the *only* place the irreversible path rounds. It happens after the
/// inverse color transform, matching `opj_tcd_dc_level_shift_decode`, which
/// calls `opj_lrintf` and then adds the DC level shift and clamps:
///
/// ```c
/// OPJ_INT64 l_value_int = (OPJ_INT64)opj_lrintf(l_value);
/// *l_dest = opj_int64_clamp(l_value_int + l_tccp->m_dc_level_shift, l_min, l_max);
/// ```
///
/// `opj_lrintf` is `lrintf` on GCC and Clang — the build that produced the
/// committed oracles — and `lrintf` rounds under the default floating-point
/// mode, which is ties-to-even. Its MSVC arms (`cvtss2si`, `fistp`) round
/// ties-to-even too. Rust's `f32::round` rounds ties *away from zero*, so `2.5`
/// would become `3` where the oracle gives `2`; `round_ties_even` agrees.
///
/// OpenJPEG tried the away-from-zero form and reverted it, leaving the evidence
/// in `opj_includes.h`:
///
/// ```c
/// /* commented out line breaks many tests */
/// /* return (long)((f>0.0f) ? (f + 0.5f):(f -0.5f)); */
/// ```
fn assemble_component(
    siz: &Siz,
    index: usize,
    samples: Samples,
    reduction: u8,
) -> Result<Component> {
    let comp = siz
        .components
        .get(index)
        .ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;

    let depth = comp.bit_depth;
    // The standard allows 1..=38 (Table A-11) and `decode_siz` enforces it;
    // this defensive restatement keeps the shift arithmetic below well-defined
    // for callers that assemble a header by hand. Legal depths whose range
    // does not fit the i32 sample container (33..=38, and unsigned 32) fall
    // through to the container check, which rejects them as Unsupported.
    if !(1..=38).contains(&depth) {
        return Err(Error::marker(format!(
            "component {index} has bit depth {depth}, outside the standard's range of 1 to 38"
        )));
    }
    if comp.x_sampling == 0 || comp.y_sampling == 0 {
        return Err(Error::marker(format!(
            "component {index} sub-sampling factor is zero"
        )));
    }

    // Safe now that the zero-factor case above is excluded.
    let (width, height) = siz
        .component_extent_at(index, reduction)
        .ok_or_else(|| Error::inconsistent(format!("`SIZ` declares no component {index}")))?;

    let expected = (width as usize) * (height as usize);
    if samples.len() != expected {
        return Err(Error::inconsistent(format!(
            "component {index} decoded {} samples but its geometry is {width}x{height} = {expected}",
            samples.len()
        )));
    }

    // Level-shift offset and the clamp bounds, all in i64 so the `1 << 31`
    // signed-32-bit case and the unsigned `2^depth - 1` upper bound cannot
    // overflow during the computation.
    let (shift, lo, hi): (i64, i64, i64) = if comp.signed {
        (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
    } else {
        (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
    };

    // The output container is `i32`; reject depths whose clamp range cannot be
    // represented (e.g. unsigned 32-bit, whose max is `2^32 - 1`). Checked once
    // so the per-sample cast below is always exact.
    if hi > i32::MAX as i64 || lo < i32::MIN as i64 {
        return Err(Error::unsupported(format!(
            "component {index} depth {depth} ({}) exceeds the i32 sample container",
            if comp.signed { "signed" } else { "unsigned" }
        )));
    }

    let shifted: Vec<i32> = match samples {
        Samples::Reversible(values) => values
            .into_iter()
            .map(|v| (v as i64 + shift).clamp(lo, hi) as i32)
            .collect(),
        // The irreversible path arrives unrounded.
        Samples::Irreversible(values) => round_shift_clamp(values, depth, shift, lo, hi),
    };

    Ok(Component {
        width,
        height,
        bit_depth: depth,
        signed: comp.signed,
        x_sampling: comp.x_sampling,
        y_sampling: comp.y_sampling,
        samples: shifted,
    })
}

/// `1.5 * 2^23`. For `-2^22 <= x < 2^22`, `x + ROUND_MAGIC` lies in
/// `[2^23, 2^24]`, where consecutive `f32` values are exactly 1 apart (2^24
/// itself is reached only by rounding up from just below it, and its bit
/// pattern still follows on by one), so the addition itself rounds `x` to an
/// integer, ties to even under the default rounding mode, and that integer is
/// the sum's bit pattern minus `ROUND_MAGIC`'s. [`round_shift_clamp`] clamps
/// first, so `x` is at most `2^22 - 1` there.
const ROUND_MAGIC: f32 = 12_582_912.0;

/// The deepest component [`round_shift_clamp`] rounds with [`ROUND_MAGIC`].
/// Before the level shift, a `depth`-bit component's range is
/// `[-2^(depth-1), 2^(depth-1) - 1]` whatever its sign, which stays inside
/// `±2^22` up to 23 bits. Deeper components take the `round_ties_even` path.
const MAGIC_MAX_DEPTH: u8 = 23;

/// Round each irreversible sample to the nearest integer, ties to even, then
/// add the level shift `shift` and clamp to `lo..=hi`, in one pass.
///
/// This gives exactly what `(v.round_ties_even() as i32 as i64 + shift)
/// .clamp(lo, hi)` gives, including NaN to `shift` and the infinities to the
/// clamp ends, without a `rintf` call per sample: baseline x86-64 has no
/// rounding instruction, so `round_ties_even` is a libm call there. The clamp
/// moves ahead of the rounding, in `f32` before the shift; that is the same
/// result because the bounds are integers and rounding is monotonic.
fn round_shift_clamp(values: Vec<f32>, depth: u8, shift: i64, lo: i64, hi: i64) -> Vec<i32> {
    if depth > MAGIC_MAX_DEPTH {
        // `as i32` saturates, so a value outside the container cannot wrap
        // before the clamp sees it.
        return values
            .into_iter()
            .map(|v| (v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32)
            .collect();
    }
    // Exact: both bounds are at most 2^22 in magnitude here.
    let low = (lo - shift) as f32;
    let high = (hi - shift) as f32;
    let shift = shift as i32;
    let magic = ROUND_MAGIC.to_bits() as i32;
    values
        .into_iter()
        .map(|v| {
            // NaN becomes 0, as `NaN as i32` did on the general path.
            let v = if v.is_nan() { 0.0 } else { v };
            let v = if v < low {
                low
            } else if v > high {
                high
            } else {
                v
            };
            (v + ROUND_MAGIC).to_bits() as i32 - magic + shift
        })
        .collect()
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::codestream::markers::{Qcd, QuantStyle, Transform};

    /// A minimal single-component header: an image of `x_size` by `y_size` at the
    /// origin with unit sub-sampling. Only the SIZ fields `assemble` reads
    /// matter; COD/QCD are filler. Tests tweak offsets/sampling on the result.
    fn header(x_size: u32, y_size: u32, bit_depth: u8, signed: bool) -> MainHeader {
        let qcd = Qcd {
            style: QuantStyle::None,
            guard_bits: 1,
            steps: vec![],
        };
        MainHeader::single_component(
            (x_size, y_size),
            (bit_depth, signed),
            (0, Transform::Reversible53),
            qcd,
        )
    }

    /// Assemble a single-component image: most of these tests predate the
    /// component axis and care only about level shift, clamping, and geometry.
    fn assemble1(header: &MainHeader, samples: Vec<i32>) -> Result<Image> {
        assemble(header, vec![Samples::Reversible(samples)], 0)
    }

    /// The single component `assemble` produces, for tests that only care about
    /// the samples and not the enclosing image area.
    fn only(img: &Image) -> &Component {
        assert_eq!(img.components.len(), 1, "assemble emits one component");
        img.component(0).unwrap()
    }

    #[test]
    fn unsigned_adds_level_shift_and_clamps() {
        // 8-bit unsigned: shift = 128, clamp to [0, 255].
        let h = header(2, 2, 8, false);
        let img = assemble1(&h, vec![0, -128, 127, 200]).unwrap();
        // 0 -> 128 (mid), -128 -> 0 (low edge), 127 -> 255 (high edge),
        // 200 -> 328 clamps to 255.
        assert_eq!(only(&img).samples, vec![128, 0, 255, 255]);
        // And the low edge under-shoot also clamps.
        let img = assemble1(&header(1, 1, 8, false), vec![-200]).unwrap();
        assert_eq!(only(&img).samples, vec![0]);
    }

    #[test]
    fn signed_is_unshifted_and_clamps() {
        // 8-bit signed: no shift, clamp to [-128, 127].
        let h = header(2, 2, 8, true);
        let img = assemble1(&h, vec![0, 50, 200, -200]).unwrap();
        assert_eq!(only(&img).samples, vec![0, 50, 127, -128]);
    }

    #[test]
    fn wider_depths_round_trip_edges() {
        // 12-bit unsigned: shift = 2048, clamp to [0, 4095].
        let img = assemble1(&header(1, 4, 12, false), vec![-2048, 0, 2047, 9999]).unwrap();
        assert_eq!(only(&img).samples, vec![0, 2048, 4095, 4095]);
        // 16-bit signed: clamp to [-32768, 32767], no shift.
        let img = assemble1(&header(1, 3, 16, true), vec![-40000, 12345, 40000]).unwrap();
        assert_eq!(only(&img).samples, vec![-32768, 12345, 32767]);
    }

    #[test]
    fn geometry_uses_siz_image_area() {
        let mut h = header(6, 5, 8, false);
        h.siz.x_offset = 2;
        h.siz.y_offset = 1;
        // width = 6 - 2 = 4, height = 5 - 1 = 4.
        let img = assemble1(&h, vec![0; 16]).unwrap();
        assert_eq!((img.width, img.height), (4, 4));
        let c = only(&img);
        assert_eq!((c.width, c.height), (4, 4));
        assert_eq!(c.bit_depth, 8);
        assert!(!c.signed);
        assert_eq!(c.sample(3, 3), Some(128));
        assert_eq!(c.sample(4, 0), None);
    }

    #[test]
    fn geometry_honors_sub_sampling() {
        let mut h = header(8, 8, 8, false);
        h.siz.components[0].x_sampling = 2;
        h.siz.components[0].y_sampling = 2;
        let img = assemble1(&h, vec![0; 16]).unwrap();
        // The image area stays on the reference grid ...
        assert_eq!((img.width, img.height), (8, 8));
        // ... while the component carries ceil(8/2) - ceil(0/2) = 4 per axis.
        let c = only(&img);
        assert_eq!((c.width, c.height), (4, 4));
        assert_eq!((c.x_sampling, c.y_sampling), (2, 2));
    }

    /// The irreversible path rounds once, here, and rounds ties to even —
    /// matching `opj_lrintf` under the default floating-point mode. Rust's
    /// `f32::round` rounds ties away from zero and would disagree at every
    /// half-integer.
    #[test]
    fn irreversible_samples_round_ties_to_even() {
        // 8-bit signed: no level shift, clamp to [-128, 127].
        let h = header(5, 1, 8, true);
        let img = assemble(
            &h,
            vec![Samples::Irreversible(vec![0.5, 1.5, 2.5, -0.5, -2.5])],
            0,
        )
        .unwrap();
        assert_eq!(only(&img).samples, vec![0, 2, 2, 0, -2]);

        // Away-from-zero would have given [1, 2, 3, -1, -3].
        let away: Vec<i32> = [0.5f32, 1.5, 2.5, -0.5, -2.5]
            .iter()
            .map(|v| v.round() as i32)
            .collect();
        assert_ne!(away, only(&img).samples);
    }

    /// A reconstructed value outside the `i32` container saturates rather than
    /// wrapping, before the depth clamp sees it.
    #[test]
    fn irreversible_samples_saturate_into_the_container() {
        let h = header(2, 1, 16, true);
        let img = assemble(&h, vec![Samples::Irreversible(vec![1e30, -1e30])], 0).unwrap();
        assert_eq!(only(&img).samples, vec![32767, -32768]);
    }

    /// What [`round_shift_clamp`] must equal: round ties to even, saturate into
    /// `i32`, shift, clamp.
    fn reference(v: f32, shift: i64, lo: i64, hi: i64) -> i32 {
        (v.round_ties_even() as i32 as i64 + shift).clamp(lo, hi) as i32
    }

    /// The level shift and clamp bounds `assemble_component` derives.
    fn bounds(depth: u8, signed: bool) -> (i64, i64, i64) {
        if signed {
            (0, -(1i64 << (depth - 1)), (1i64 << (depth - 1)) - 1)
        } else {
            (1i64 << (depth - 1), 0, (1i64 << depth) - 1)
        }
    }

    /// Check `values` through [`round_shift_clamp`] against [`reference`].
    fn check_against_reference(values: Vec<f32>, depth: u8, signed: bool) {
        let (shift, lo, hi) = bounds(depth, signed);
        let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
        for (v, g) in values.iter().zip(got) {
            assert_eq!(
                g,
                reference(*v, shift, lo, hi),
                "depth {depth} signed {signed} input {v:e} (bits {:#010x})",
                v.to_bits()
            );
        }
    }

    /// The `f32` values within `ulps` steps of `x` on either side, `x` included.
    fn window(x: f32, ulps: u32, out: &mut Vec<f32>) {
        let (mut up, mut down) = (x, x);
        out.push(x);
        for _ in 0..ulps {
            up = up.next_up();
            down = down.next_down();
            out.push(up);
            out.push(down);
        }
    }

    /// Values every depth must handle: zeros, NaNs, infinities, extremes, and
    /// the neighborhoods of 2^22, 2^23 and 2^24 where `ROUND_MAGIC` stops
    /// being exact.
    fn special_values() -> Vec<f32> {
        let mut v = vec![
            0.0,
            -0.0,
            f32::NAN,
            -f32::NAN,
            f32::from_bits(0x7fc0_0001),
            f32::from_bits(0xffbf_ffff),
            f32::INFINITY,
            f32::NEG_INFINITY,
            f32::MAX,
            f32::MIN,
            f32::MIN_POSITIVE,
            -f32::MIN_POSITIVE,
            f32::from_bits(1),
            -f32::from_bits(1),
            1e30,
            -1e30,
            2147483648.0,
            -2147483648.0,
            4294967296.0,
        ];
        for p in [21, 22, 23, 24, 25] {
            let x = (1u32 << p) as f32;
            for x in [x, -x, x + 0.5, -x - 0.5, x - 0.5, -x + 0.5] {
                window(x, 8, &mut v);
            }
        }
        v
    }

    /// Ties to even, the level shift and the clamp, bit for bit against
    /// `round_ties_even`, over every half-integer in and around each depth's
    /// range (with neighbors), every `f32` near the clamp ends and zero, and
    /// the special values.
    #[test]
    fn round_shift_clamp_matches_round_ties_even() {
        // 1..=16 run the ROUND_MAGIC path at every width used in practice; 22
        // and 23 are its deepest; 24 and 32 are the fallback.
        let depths = (1..=16).chain([22, 23, 24, 32]);
        for depth in depths {
            for signed in [false, true] {
                if !signed && depth == 32 {
                    continue; // Rejected before rounding: exceeds i32.
                }
                let (shift, lo, hi) = bounds(depth, signed);
                let (low, high) = (lo - shift, hi - shift);
                let mut values = special_values();
                if depth <= 16 {
                    // Every half-integer and integer across the range and two
                    // past each end, with two f32 steps either side.
                    for n in (2 * (low - 2))..=(2 * (high + 2)) {
                        window(n as f32 / 2.0, 2, &mut values);
                    }
                }
                // Every f32 within 256 steps of each half-integer near the
                // clamp ends and near zero.
                for center in [low, high, 0] {
                    for n in (2 * (center - 4))..=(2 * (center + 4)) {
                        window(n as f32 / 2.0, 256, &mut values);
                    }
                }
                check_against_reference(values, depth, signed);
            }
        }
    }

    /// Spot checks through `assemble`, so a wrong result shows as a sample.
    #[test]
    fn irreversible_ties_and_specials_through_assemble() {
        // 8-bit unsigned: shift 128, clamp [0, 255]; 127.5 rounds to 128 and
        // clamps to 255, -128.5 rounds to -128 (even) and lands on 0.
        let h = header(8, 1, 8, false);
        let values = vec![
            -0.0,
            126.5,
            127.5,
            -127.5,
            -128.5,
            f32::NAN,
            f32::INFINITY,
            f32::NEG_INFINITY,
        ];
        let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
        assert_eq!(only(&img).samples, vec![128, 254, 255, 0, 0, 128, 255, 0]);
        // 24-bit signed takes the fallback: 2^23 - 1.5 rounds to 2^23 - 2,
        // and 2^23 - 0.5 is not an f32, so its neighbor 2^23 - 1 is exact.
        let h = header(3, 1, 24, true);
        let values = vec![8_388_606.5, -8_388_607.5, 1e9];
        let img = assemble(&h, vec![Samples::Irreversible(values)], 0).unwrap();
        assert_eq!(only(&img).samples, vec![8_388_606, -8_388_608, 8_388_607]);
    }

    /// Every one of the 2^32 `f32` bit patterns, at each depth 1..=16 and 23,
    /// signed and unsigned. Run with
    /// `cargo test --release -- --ignored every_f32`.
    #[test]
    #[ignore = "slow: about 30 CPU-minutes on a release build, spread over all cores"]
    fn round_shift_clamp_matches_round_ties_even_on_every_f32() {
        const CHUNK: u32 = 1 << 20;
        let depths: Vec<u8> = (1..=16).chain([23]).collect();
        let threads = std::thread::available_parallelism().map_or(4, |n| n.get());
        std::thread::scope(|scope| {
            for t in 0..threads {
                let depths = &depths;
                scope.spawn(move || {
                    let mut chunk = t as u64;
                    while chunk < (1u64 << 32) / CHUNK as u64 {
                        let start = chunk as u32 * CHUNK;
                        let values: Vec<f32> =
                            (start..=start + (CHUNK - 1)).map(f32::from_bits).collect();
                        for &depth in depths {
                            for signed in [false, true] {
                                let (shift, lo, hi) = bounds(depth, signed);
                                let got = round_shift_clamp(values.clone(), depth, shift, lo, hi);
                                for (v, g) in values.iter().zip(got) {
                                    assert_eq!(
                                        g,
                                        reference(*v, shift, lo, hi),
                                        "depth {depth} signed {signed} bits {:#010x}",
                                        v.to_bits()
                                    );
                                }
                            }
                        }
                        chunk += threads as u64;
                    }
                });
            }
        });
    }

    #[test]
    fn sample_count_mismatch_is_inconsistent() {
        let h = header(4, 4, 8, false); // expects 16 samples
        let err = assemble1(&h, vec![0; 15]).unwrap_err();
        assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
    }

    #[test]
    fn depth_beyond_i32_container_is_unsupported() {
        // Unsigned 32-bit's upper bound (2^32 - 1) cannot fit in i32, and the
        // standard-legal 33..=38 depths (Table A-11) exceed it either way —
        // legal-but-undecodable, so Unsupported rather than Marker.
        for (depth, signed) in [(32, false), (33, false), (33, true), (38, true)] {
            let h = header(1, 1, depth, signed);
            let err = assemble1(&h, vec![0]).unwrap_err();
            assert!(matches!(err, Error::Unsupported(_)), "{depth} got {err:?}");
        }
        // Signed 32-bit fits exactly and is accepted.
        let img = assemble1(&header(1, 1, 32, true), vec![i32::MIN]).unwrap();
        assert_eq!(only(&img).samples, vec![i32::MIN]);
    }

    #[test]
    fn bad_depth_is_rejected() {
        // 0 and 39+ are illegal encodings (Table A-11), not missing features.
        for depth in [0, 39] {
            let h = header(1, 1, depth, false);
            assert!(matches!(assemble1(&h, vec![0]), Err(Error::Marker(_))));
        }
    }

    fn rect(x0: u32, y0: u32, x1: u32, y1: u32) -> Rect {
        Rect { x0, y0, x1, y1 }
    }

    #[test]
    fn a_tile_covering_the_canvas_is_moved_in() {
        let h = header(4, 2, 8, false);
        let mut canvas = Canvas::new(&h, 0).unwrap();
        let samples = vec![1, 2, 3, 4, 5, 6, 7, 8];
        let at = samples.as_ptr();
        canvas
            .place(0, rect(0, 0, 4, 2), Samples::Reversible(samples))
            .unwrap();
        match canvas.into_planes().as_slice() {
            [Samples::Reversible(plane)] => {
                assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]);
                assert_eq!(plane.as_ptr(), at, "the tile's buffer is the plane");
            }
            other => panic!("expected one reversible plane, got {other:?}"),
        }
    }

    #[test]
    fn partial_tiles_are_copied_into_one_plane() {
        let h = header(4, 2, 8, false);
        let mut canvas = Canvas::new(&h, 0).unwrap();
        canvas
            .place(0, rect(2, 0, 4, 2), Samples::Reversible(vec![3, 4, 7, 8]))
            .unwrap();
        canvas
            .place(0, rect(0, 0, 2, 2), Samples::Reversible(vec![1, 2, 5, 6]))
            .unwrap();
        match canvas.into_planes().as_slice() {
            [Samples::Reversible(plane)] => assert_eq!(plane, &[1, 2, 3, 4, 5, 6, 7, 8]),
            other => panic!("expected one reversible plane, got {other:?}"),
        }
    }

    #[test]
    fn a_plane_no_tile_reached_is_zeros() {
        let mut h = header(2, 1, 8, false);
        h.components[0].coding.transform = Transform::Irreversible97;
        match Canvas::new(&h, 0).unwrap().into_planes().as_slice() {
            [Samples::Irreversible(plane)] => assert_eq!(plane, &[0.0, 0.0]),
            other => panic!("expected one irreversible plane, got {other:?}"),
        }
    }

    #[test]
    fn a_tile_on_the_other_wavelet_is_inconsistent() {
        let h = header(2, 2, 8, false);
        for area in [rect(0, 0, 2, 2), rect(0, 0, 1, 2)] {
            let mut canvas = Canvas::new(&h, 0).unwrap();
            let samples = Samples::Irreversible(vec![0.0; area.area() as usize]);
            let err = canvas.place(0, area, samples).unwrap_err();
            assert!(
                matches!(err, Error::Inconsistent(_)),
                "{area:?} got {err:?}"
            );
        }
    }

    #[test]
    fn a_tile_past_the_canvas_is_inconsistent_without_a_window() {
        let h = header(4, 2, 8, false);
        let mut canvas = Canvas::new(&h, 0).unwrap();
        let err = canvas
            .place(0, rect(2, 0, 6, 2), Samples::Reversible(vec![0; 8]))
            .unwrap_err();
        assert!(matches!(err, Error::Inconsistent(_)), "got {err:?}");
        // Under a window the same tile is cut to it.
        let mut area = h.siz.clone();
        area.x_offset = 2;
        let mut canvas = Canvas::over(&h, &area, 0, &[0]).unwrap();
        canvas
            .place(
                0,
                rect(0, 0, 4, 2),
                Samples::Reversible(vec![1, 2, 3, 4, 5, 6, 7, 8]),
            )
            .unwrap();
        match canvas.into_planes().as_slice() {
            [Samples::Reversible(plane)] => assert_eq!(plane, &[3, 4, 7, 8]),
            other => panic!("expected one reversible plane, got {other:?}"),
        }
    }
}