j2k-native 0.7.2

Pure-Rust JPEG 2000 and HTJ2K codec engine for j2k
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
// SPDX-License-Identifier: MIT OR Apache-2.0

use alloc::vec::Vec;

use crate::error::err;
use crate::j2c::{self, Header};
use crate::jp2::colr::EnumeratedColorspace;
use crate::jp2::{self, DecodedImage, ImageBoxes};
use crate::{
    checked_decode_byte_len3, convert_color_space, interleave_and_convert,
    interleave_and_convert_region, resolve_palette_indices, try_resize_decode_elements,
    validate_and_reorder_channels, validate_interleaved_output_buffer, validate_roi, Bitmap,
    ColorSpace, DecodedComponents, DecodedNativeComponents, DecoderContext, DecodingError,
    FormatError, HtCodeBlockDecoder, Result, CODESTREAM_MAGIC, JP2_MAGIC,
};

mod allocation;
mod compare;
#[cfg(test)]
mod contract_tests;
mod direct_api;
mod native;
mod output_api;
use self::allocation::retained_metadata_bytes;
pub(crate) use self::allocation::{retained_container_metadata_bytes, DecodeOwnerBudget};
use self::native::{try_clone_color_space, NativeOutputBudget};

/// Settings to apply during decoding.
#[derive(Debug, Copy, Clone)]
pub struct DecodeSettings {
    /// Whether palette indices should be resolved.
    ///
    /// JPEG2000 images can be stored in two different ways. First, by storing
    /// RGB values (depending on the color space) for each pixel. Secondly, by
    /// only storing a single index for each channel, and then resolving the
    /// actual color using the index.
    ///
    /// If you disable this option, in case you have an image with palette
    /// indices, they will not be resolved, but instead a grayscale image
    /// will be returned, with each pixel value corresponding to the palette
    /// index of the location.
    pub resolve_palette_indices: bool,
    /// Whether strict mode should be enabled when decoding.
    ///
    /// The default is lenient for compatibility with older releases. Lenient
    /// mode may tolerate malformed optional container metadata that strict mode
    /// rejects. Use [`DecodeSettings::strict`] for fail-closed validation of
    /// public or adversarial inputs.
    pub strict: bool,
    /// A hint for the target resolution that the image should be decoded at.
    pub target_resolution: Option<(u32, u32)>,
}

impl DecodeSettings {
    /// Compatibility decode settings.
    ///
    /// Lenient mode keeps the historical behavior of accepting recoverable
    /// optional metadata problems where possible.
    #[must_use]
    pub const fn lenient() -> Self {
        Self {
            resolve_palette_indices: true,
            strict: false,
            target_resolution: None,
        }
    }

    /// Strict decode settings for fail-closed validation.
    #[must_use]
    pub const fn strict() -> Self {
        Self {
            resolve_palette_indices: true,
            strict: true,
            target_resolution: None,
        }
    }

    /// Whether the settings permit lenient tolerance of malformed optional
    /// metadata.
    #[must_use]
    pub const fn lenient_tolerance_enabled(&self) -> bool {
        !self.strict
    }
}

impl Default for DecodeSettings {
    fn default() -> Self {
        Self::lenient()
    }
}

/// A JPEG2000 image or codestream.
pub struct Image<'a> {
    /// The tile-part payload used by the legacy JPEG 2000 decoder.
    pub(crate) codestream: &'a [u8],
    /// The header of the J2C codestream.
    pub(crate) header: Header<'a>,
    /// The JP2 boxes of the image. In the case of a raw codestream, we
    /// will synthesize the necessary boxes.
    pub(crate) boxes: ImageBoxes,
    /// Settings that should be applied during decoding.
    pub(crate) settings: DecodeSettings,
    /// Whether the image has an alpha channel.
    pub(crate) has_alpha: bool,
    /// The color space of the image.
    pub(crate) color_space: ColorSpace,
}

impl<'a> Image<'a> {
    pub(crate) fn from_parsed_parts(
        codestream: &'a [u8],
        header: Header<'a>,
        boxes: ImageBoxes,
        settings: DecodeSettings,
        color_space: ColorSpace,
        has_alpha: bool,
    ) -> Result<Self> {
        Self::from_parsed_parts_with_retained_baseline(
            codestream,
            header,
            boxes,
            settings,
            color_space,
            has_alpha,
            0,
        )
    }

    pub(crate) fn from_parsed_parts_with_retained_baseline(
        codestream: &'a [u8],
        header: Header<'a>,
        boxes: ImageBoxes,
        settings: DecodeSettings,
        color_space: ColorSpace,
        has_alpha: bool,
        retained_baseline_bytes: usize,
    ) -> Result<Self> {
        let metadata_bytes = retained_metadata_bytes(&header, &boxes, &color_space)?;
        allocation::combine_retained_bytes(retained_baseline_bytes, metadata_bytes)?;
        Ok(Self {
            codestream,
            header,
            boxes,
            settings,
            has_alpha,
            color_space,
        })
    }

    pub(crate) fn retained_metadata_bytes(&self) -> Result<usize> {
        retained_metadata_bytes(&self.header, &self.boxes, &self.color_space)
    }

    /// Return the allocator capacities retained by this parsed image.
    ///
    /// # Errors
    ///
    /// Returns an error if nested metadata capacity arithmetic overflows or
    /// exceeds the native decode cap.
    #[doc(hidden)]
    pub fn retained_allocation_bytes(&self) -> Result<usize> {
        self.retained_metadata_bytes()
    }

    /// Try to create a new JPEG2000 image from the given data.
    ///
    /// # Errors
    ///
    /// Returns an error when the input signature, container, or codestream is invalid.
    pub fn new(data: &'a [u8], settings: &DecodeSettings) -> Result<Self> {
        if data.starts_with(JP2_MAGIC) {
            jp2::parse(data, *settings)
        } else if data.starts_with(CODESTREAM_MAGIC) {
            j2c::parse(data, settings)
        } else {
            err!(FormatError::InvalidSignature)
        }
    }

    /// Parse an image while accounting already-live codec-owned allocations.
    ///
    /// This adapter is used when validation parses another image while an
    /// encoded output and earlier parsed metadata remain live.
    ///
    /// # Errors
    ///
    /// Returns an error when the input is invalid or aggregate parser-owned
    /// allocations exceed the native decode cap.
    #[doc(hidden)]
    pub fn new_with_retained_baseline(
        data: &'a [u8],
        settings: &DecodeSettings,
        retained_baseline_bytes: usize,
    ) -> Result<Self> {
        if retained_baseline_bytes == 0 {
            return Self::new(data, settings);
        }
        if data.starts_with(JP2_MAGIC) {
            jp2::parse_with_retained_baseline(data, *settings, retained_baseline_bytes)
        } else if data.starts_with(CODESTREAM_MAGIC) {
            j2c::parse_with_retained_baseline(data, settings, retained_baseline_bytes)
        } else {
            err!(FormatError::InvalidSignature)
        }
    }

    /// Whether the image has an alpha channel.
    #[must_use]
    pub fn has_alpha(&self) -> bool {
        self.has_alpha
    }

    /// The color space of the image.
    #[must_use]
    pub fn color_space(&self) -> &ColorSpace {
        &self.color_space
    }

    /// The width of the image.
    #[must_use]
    pub fn width(&self) -> u32 {
        self.header.size_data.image_width()
    }

    /// The height of the image.
    #[must_use]
    pub fn height(&self) -> u32 {
        self.header.size_data.image_height()
    }

    /// The original bit depth of the image. You usually don't need to do anything
    /// with this parameter, it just exists for informational purposes.
    #[must_use]
    pub fn original_bit_depth(&self) -> u8 {
        // Note that this only works if all components have the same precision.
        self.header.component_infos[0].size_info.precision
    }

    /// Whether decode finishes with additional host-side component mutation or reordering.
    #[doc(hidden)]
    #[must_use]
    pub fn supports_direct_device_plane_reuse(&self) -> bool {
        if self.settings.resolve_palette_indices && self.boxes.palette.is_some() {
            return false;
        }
        if self.boxes.channel_definition.is_some() {
            return false;
        }
        !matches!(
            self.boxes
                .primary_color_specification()
                .map(|spec| &spec.color_space),
            Some(jp2::colr::ColorSpace::Enumerated(
                EnumeratedColorspace::Sycc | EnumeratedColorspace::CieLab(_)
            ))
        )
    }

    /// Decode the image and return its decoded result as a `Vec<u8>`, with each
    /// channel interleaved.
    ///
    /// # Errors
    ///
    /// Returns an error when image validation, decoding, or output allocation fails.
    pub fn decode(&self) -> Result<Vec<u8>> {
        let bitmap = self.decode_with_context(&mut DecoderContext::default())?;
        Ok(bitmap.data)
    }

    /// Decode the image and return its decoded result using a caller-provided
    /// decoder context so allocations can be reused across repeated decodes.
    ///
    /// # Errors
    ///
    /// Returns an error when image validation, decoding, or output allocation fails.
    pub fn decode_with_context(&self, decoder_context: &mut DecoderContext<'a>) -> Result<Bitmap> {
        (|| {
            let retained_image_bytes = self.retained_metadata_bytes()?;
            let mut decoded_image = self.prepare_decoded_image(decoder_context)?;
            let component_owner_capacity = decoded_image.decoded_components.capacity();
            let buffer_size = checked_decode_byte_len3(
                self.width() as usize,
                self.height() as usize,
                decoded_image.decoded_components.len(),
            )?;
            let mut budget = NativeOutputBudget::for_component_pack(
                retained_image_bytes,
                decoded_image.decoded_components,
                component_owner_capacity,
            )?;
            budget.include_elements::<u8>(buffer_size)?;
            budget.include_color_space_clone(&self.color_space)?;

            let color_space = try_clone_color_space(&self.color_space)?;
            budget.include_color_space_clone_overage(&self.color_space, &color_space)?;
            let mut data = Vec::new();
            try_resize_decode_elements(&mut data, buffer_size, 0_u8)?;
            budget.include_capacity_overage::<u8>(buffer_size, data.capacity())?;
            validate_interleaved_output_buffer(&decoded_image, &data)?;
            interleave_and_convert(&mut decoded_image, &mut data)?;
            let bitmap = Bitmap {
                color_space,
                data,
                has_alpha: self.has_alpha,
                width: self.width(),
                height: self.height(),
                original_bit_depth: self.original_bit_depth(),
            };
            NativeOutputBudget::validate_bitmap_pack(
                retained_image_bytes,
                decoded_image.decoded_components,
                component_owner_capacity,
                &bitmap,
            )?;
            Ok(bitmap)
        })()
    }

    /// Decode the image into borrowed component planes using a caller-provided
    /// decoder context so allocations can be reused across repeated decodes.
    ///
    /// # Errors
    ///
    /// Returns an error when component precision is unsupported or decoding fails.
    pub fn decode_components_with_context<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
    ) -> Result<DecodedComponents<'ctx>> {
        self.validate_component_plane_precision()?;
        let decoded_image = self.prepare_decoded_image(decoder_context)?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        self.try_borrow_component_planes(
            decoded_components.as_slice(),
            decoded_components.capacity(),
            (self.width(), self.height()),
        )
    }

    /// Decode the image into owned native-bit-depth component planes.
    ///
    /// Unlike [`Self::decode_native`], this preserves per-component bit depth
    /// and signedness metadata and does not require all components to share a
    /// single packed interleaved representation.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, decoding, or native sample packing fails.
    pub fn decode_native_components(&self) -> Result<DecodedNativeComponents> {
        let mut decoder_context = DecoderContext::default();
        self.decode_native_components_with_context(&mut decoder_context)
    }

    /// Decode owned native component planes while accounting an already-live
    /// external allocation, such as the encoded `Vec` being validated.
    ///
    /// `retained_capacity` must be the allocator capacity of that external
    /// owner, not merely its logical length.
    ///
    /// # Errors
    ///
    /// Returns an error when aggregate retained allocation accounting,
    /// decoding, or native component packing fails.
    #[doc(hidden)]
    pub fn decode_native_components_with_retained_capacity(
        &self,
        retained_capacity: usize,
    ) -> Result<DecodedNativeComponents> {
        let retained_baseline_bytes =
            allocation::combine_retained_bytes(retained_capacity, self.retained_metadata_bytes()?)?;
        let mut decoder_context = DecoderContext::default();
        self.decode_native_components_with_context_and_retained_baseline(
            &mut decoder_context,
            retained_baseline_bytes,
        )
    }

    /// Decode the image into owned native-bit-depth component planes using a
    /// caller-provided decoder context.
    ///
    /// # Errors
    ///
    /// Returns an error when validation, decoding, or native sample packing fails.
    pub fn decode_native_components_with_context(
        &self,
        decoder_context: &mut DecoderContext<'a>,
    ) -> Result<DecodedNativeComponents> {
        let retained_baseline_bytes = self.retained_metadata_bytes()?;
        self.decode_native_components_with_context_and_retained_baseline(
            decoder_context,
            retained_baseline_bytes,
        )
    }

    fn decode_native_components_with_context_and_retained_baseline(
        &self,
        decoder_context: &mut DecoderContext<'a>,
        retained_baseline_bytes: usize,
    ) -> Result<DecodedNativeComponents> {
        let decoded_image = self.prepare_decoded_image_with_retained_baseline(
            decoder_context,
            retained_baseline_bytes,
        )?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        let component_owner_capacity = decoded_components.capacity();
        self.pack_native_component_planes(
            decoded_components,
            component_owner_capacity,
            (self.width(), self.height()),
            retained_baseline_bytes,
        )
    }

    /// Decode borrowed component planes while delegating HTJ2K code-block decode.
    #[doc(hidden)]
    pub fn decode_components_with_ht_decoder<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        ht_decoder: &mut dyn HtCodeBlockDecoder,
    ) -> Result<DecodedComponents<'ctx>> {
        self.validate_component_plane_precision()?;
        let decoded_image =
            self.prepare_decoded_image_with_ht_decoder(decoder_context, ht_decoder)?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        self.try_borrow_component_planes(
            decoded_components.as_slice(),
            decoded_components.capacity(),
            (self.width(), self.height()),
        )
    }

    /// Decode borrowed component planes for a requested region using a
    /// caller-provided decoder context.
    ///
    /// # Errors
    ///
    /// Returns an error when the region is invalid, precision is unsupported, or decoding fails.
    pub fn decode_region_components_with_context<'ctx>(
        &self,
        roi: (u32, u32, u32, u32),
        decoder_context: &'ctx mut DecoderContext<'a>,
    ) -> Result<DecodedComponents<'ctx>> {
        validate_roi((self.width(), self.height()), roi)?;
        self.validate_component_plane_precision()?;
        let (_x, _y, width, height) = roi;
        let decoded_image = self.prepare_decoded_image_with_region(decoder_context, Some(roi))?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        self.try_borrow_component_planes(
            decoded_components.as_slice(),
            decoded_components.capacity(),
            (width, height),
        )
    }

    /// Decode a source-coordinate region into owned native-bit-depth component
    /// planes using a caller-provided decoder context.
    ///
    /// # Errors
    ///
    /// Returns an error when the region is invalid or decoding and packing fail.
    pub fn decode_native_region_components_with_context(
        &self,
        roi: (u32, u32, u32, u32),
        decoder_context: &mut DecoderContext<'a>,
    ) -> Result<DecodedNativeComponents> {
        validate_roi((self.width(), self.height()), roi)?;
        if self.requires_exact_integer_decode() {
            return self.decode_native_region_components_via_full_decode(roi, decoder_context);
        }
        let (_x, _y, width, height) = roi;
        let decoded_image = self.prepare_decoded_image_with_region(decoder_context, Some(roi))?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        let component_owner_capacity = decoded_components.capacity();
        self.pack_native_component_planes(
            decoded_components,
            component_owner_capacity,
            (width, height),
            self.retained_metadata_bytes()?,
        )
    }

    /// Decode borrowed component planes for a requested region while
    /// delegating code-block/transform stages through the adapter backend hook.
    #[doc(hidden)]
    pub fn decode_region_components_with_ht_decoder<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        roi: (u32, u32, u32, u32),
        ht_decoder: &mut dyn HtCodeBlockDecoder,
    ) -> Result<DecodedComponents<'ctx>> {
        validate_roi((self.width(), self.height()), roi)?;
        self.validate_component_plane_precision()?;
        let (_x, _y, width, height) = roi;
        let decoded_image = self.prepare_decoded_image_with_region_and_ht_decoder(
            decoder_context,
            Some(roi),
            Some(ht_decoder),
        )?;
        let DecodedImage {
            decoded_components,
            boxes: _,
        } = decoded_image;
        self.try_borrow_component_planes(
            decoded_components.as_slice(),
            decoded_components.capacity(),
            (width, height),
        )
    }

    /// Decode a region of the image and return it as an 8-bit interleaved bitmap.
    ///
    /// # Errors
    ///
    /// Returns an error when the region is invalid or decoding fails.
    pub fn decode_region(&self, roi: (u32, u32, u32, u32)) -> Result<Bitmap> {
        self.decode_region_with_context(roi, &mut DecoderContext::default())
    }

    /// Decode a region of the image and return it as an 8-bit interleaved bitmap
    /// using a caller-provided decoder context.
    ///
    /// # Errors
    ///
    /// Returns an error when the region is invalid, decoding fails, or output sizing overflows.
    pub fn decode_region_with_context(
        &self,
        roi: (u32, u32, u32, u32),
        decoder_context: &mut DecoderContext<'a>,
    ) -> Result<Bitmap> {
        validate_roi((self.width(), self.height()), roi)?;
        (|| {
            let retained_image_bytes = self.retained_metadata_bytes()?;
            let mut decoded_image =
                self.prepare_decoded_image_with_region(decoder_context, Some(roi))?;
            let component_owner_capacity = decoded_image.decoded_components.capacity();
            let (_x, _y, width, height) = roi;
            let data_len = checked_decode_byte_len3(
                width as usize,
                height as usize,
                decoded_image.decoded_components.len(),
            )?;
            let mut budget = NativeOutputBudget::for_component_pack(
                retained_image_bytes,
                decoded_image.decoded_components,
                component_owner_capacity,
            )?;
            budget.include_elements::<u8>(data_len)?;
            budget.include_color_space_clone(&self.color_space)?;

            let color_space = try_clone_color_space(&self.color_space)?;
            budget.include_color_space_clone_overage(&self.color_space, &color_space)?;
            let mut data = Vec::new();
            try_resize_decode_elements(&mut data, data_len, 0_u8)?;
            budget.include_capacity_overage::<u8>(data_len, data.capacity())?;
            interleave_and_convert_region(
                &mut decoded_image,
                width as usize,
                (0, 0, width, height),
                &mut data,
            );
            let bitmap = Bitmap {
                color_space,
                data,
                has_alpha: self.has_alpha,
                width,
                height,
                original_bit_depth: self.original_bit_depth(),
            };
            NativeOutputBudget::validate_bitmap_pack(
                retained_image_bytes,
                decoded_image.decoded_components,
                component_owner_capacity,
                &bitmap,
            )?;
            Ok(bitmap)
        })()
    }

    /// Decode the image into the given buffer.
    ///
    /// This method does the same as [`Image::decode`], but you can provide
    /// a custom buffer for the output, as well as a decoder context. Doing
    /// so allows the internal decode engine to reuse memory allocations, so
    /// this is especially recommended if you plan on converting multiple
    /// images in the same session.
    ///
    /// The buffer must have the correct size.
    ///
    /// # Errors
    ///
    /// Returns an error when decoding fails or `buf` is too small for the image.
    pub fn decode_into(
        &self,
        buf: &mut [u8],
        decoder_context: &mut DecoderContext<'a>,
    ) -> Result<()> {
        let mut decoded_image = self.prepare_decoded_image(decoder_context)?;
        validate_interleaved_output_buffer(&decoded_image, buf)?;
        interleave_and_convert(&mut decoded_image, buf)?;

        Ok(())
    }

    fn prepare_decoded_image<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
    ) -> Result<DecodedImage<'ctx, '_>> {
        self.prepare_decoded_image_with_region(decoder_context, None)
    }

    fn prepare_decoded_image_with_retained_baseline<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        retained_baseline_bytes: usize,
    ) -> Result<DecodedImage<'ctx, '_>> {
        self.prepare_decoded_image_with_region_and_ht_decoder_with_retained_baseline(
            decoder_context,
            None,
            None,
            retained_baseline_bytes,
        )
    }

    fn prepare_decoded_image_with_ht_decoder<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        ht_decoder: &mut dyn HtCodeBlockDecoder,
    ) -> Result<DecodedImage<'ctx, '_>> {
        self.prepare_decoded_image_with_region_and_ht_decoder(
            decoder_context,
            None,
            Some(ht_decoder),
        )
    }

    fn prepare_decoded_image_with_region<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
    ) -> Result<DecodedImage<'ctx, '_>> {
        self.prepare_decoded_image_with_region_and_ht_decoder(decoder_context, output_region, None)
    }

    fn prepare_decoded_image_with_region_and_ht_decoder<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
        ht_decoder: Option<&mut dyn HtCodeBlockDecoder>,
    ) -> Result<DecodedImage<'ctx, '_>> {
        let retained_baseline_bytes = self.retained_metadata_bytes()?;
        self.prepare_decoded_image_with_region_and_ht_decoder_with_retained_baseline(
            decoder_context,
            output_region,
            ht_decoder,
            retained_baseline_bytes,
        )
    }

    fn prepare_decoded_image_with_region_and_ht_decoder_with_retained_baseline<'ctx>(
        &self,
        decoder_context: &'ctx mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
        ht_decoder: Option<&mut dyn HtCodeBlockDecoder>,
        retained_baseline_bytes: usize,
    ) -> Result<DecodedImage<'ctx, '_>> {
        let settings = &self.settings;
        self.decode_with_output_region_and_ht_decoder_with_retained_baseline(
            decoder_context,
            output_region,
            ht_decoder,
            retained_baseline_bytes,
        )?;
        let mut decoded_image = DecodedImage {
            decoded_components: &mut decoder_context.tile_decode_context.channel_data,
            boxes: &self.boxes,
        };

        if settings.resolve_palette_indices {
            let components = core::mem::take(decoded_image.decoded_components);
            *decoded_image.decoded_components =
                resolve_palette_indices(components, decoded_image.boxes, retained_baseline_bytes)?;
        }

        if let Some(cdef) = &decoded_image.boxes.channel_definition {
            validate_and_reorder_channels(
                cdef,
                decoded_image.decoded_components,
                retained_baseline_bytes,
            )?;
        }

        let bit_depth = decoded_image
            .decoded_components
            .first()
            .ok_or(DecodingError::CodeBlockDecodeFailure)?
            .bit_depth;
        convert_color_space(&mut decoded_image, bit_depth)?;
        Ok(decoded_image)
    }

    fn decode_with_output_region(
        &self,
        decoder_context: &mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
    ) -> Result<()> {
        self.decode_with_output_region_and_ht_decoder(decoder_context, output_region, None)
    }

    fn decode_with_output_region_and_ht_decoder(
        &self,
        decoder_context: &mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
        ht_decoder: Option<&mut dyn HtCodeBlockDecoder>,
    ) -> Result<()> {
        let retained_metadata_bytes = self.retained_metadata_bytes()?;
        self.decode_with_output_region_and_ht_decoder_with_retained_baseline(
            decoder_context,
            output_region,
            ht_decoder,
            retained_metadata_bytes,
        )
    }

    fn decode_with_output_region_and_ht_decoder_with_retained_baseline(
        &self,
        decoder_context: &mut DecoderContext<'a>,
        output_region: Option<(u32, u32, u32, u32)>,
        mut ht_decoder: Option<&mut dyn HtCodeBlockDecoder>,
        retained_baseline_bytes: usize,
    ) -> Result<()> {
        decoder_context.set_output_region(output_region);
        let decode_result = j2c::decode(
            self.codestream,
            &self.header,
            retained_baseline_bytes,
            decoder_context,
            &mut ht_decoder,
        );
        decoder_context.set_output_region(None);
        decode_result
    }
}