Coverage Report

Created: 2026-12-01 08:10

next uncovered line (L), next uncovered region (R), next uncovered branch (B)
/rust/registry/src/index.crates.io-1949cf8c6b5b557f/zune-jpeg-0.5.15/src/decoder.rs
Line
Count
Source
1
/*
2
 * Copyright (c) 2023.
3
 *
4
 * This software is free software;
5
 *
6
 * You can redistribute it or modify it under terms of the MIT, Apache License or Zlib license
7
 */
8
9
//! Main image logic.
10
#![allow(clippy::doc_markdown)]
11
12
use alloc::string::ToString;
13
use alloc::vec::Vec;
14
use alloc::{format, vec};
15
16
use zune_core::bytestream::{ZByteReaderTrait, ZReader};
17
use zune_core::colorspace::ColorSpace;
18
use zune_core::log::{error, trace, warn};
19
use zune_core::options::DecoderOptions;
20
21
use crate::color_convert::choose_ycbcr_to_rgb_convert_func;
22
use crate::components::{Components, SampleRatios};
23
use crate::errors::{DecodeErrors, UnsupportedSchemes};
24
use crate::headers::{
25
    parse_app1, parse_app13, parse_app14, parse_app2, parse_dqt, parse_huffman, parse_sos,
26
    parse_start_of_frame
27
};
28
use crate::huffman::HuffmanTable;
29
use crate::idct::{choose_idct_func, choose_idct_1x1_func, choose_idct_4x4_func};
30
use crate::marker::Marker;
31
use crate::misc::SOFMarkers;
32
use crate::upsampler::{
33
    choose_horizontal_samp_function, choose_hv_samp_function, choose_v_samp_function,
34
    generic_sampler, upsample_no_op
35
};
36
37
/// Maximum components
38
pub(crate) const MAX_COMPONENTS: usize = 4;
39
40
/// Maximum image dimensions supported.
41
pub(crate) const MAX_DIMENSIONS: usize = 1 << 27;
42
43
/// Color conversion function that can convert YCbCr colorspace to RGB(A/X) for
44
/// 16 values
45
///
46
/// The following are guarantees to the following functions
47
///
48
/// 1. The `&[i16]` slices passed contain 16 items
49
///
50
/// 2. The slices passed are in the following order
51
///     `y,cb,cr`
52
///
53
/// 3. `&mut [u8]` is zero initialized
54
///
55
/// 4. `&mut usize` points to the position in the array where new values should
56
/// be used
57
///
58
/// The pointer should
59
/// 1. Carry out color conversion
60
/// 2. Update `&mut usize` with the new position
61
62
pub type ColorConvert16Ptr = fn(&[i16; 16], &[i16; 16], &[i16; 16], &mut [u8], &mut usize);
63
64
/// IDCT  function prototype
65
///
66
/// This encapsulates a dequantize and IDCT function which will carry out the
67
/// following functions
68
///
69
/// Multiply each 64 element block of `&mut [i16]` with `&Aligned32<[i32;64]>`
70
/// Carry out IDCT (type 3 dct) on ach block of 64 i16's
71
pub type IDCTPtr = fn(&mut [i32; 64], &mut [i16], usize);
72
73
/// An encapsulation of an ICC chunk
74
pub(crate) struct ICCChunk {
75
    pub(crate) seq_no:      u8,
76
    pub(crate) num_markers: u8,
77
    pub(crate) data:        Vec<u8>
78
}
79
80
/// A JPEG Decoder Instance.
81
#[allow(clippy::upper_case_acronyms, clippy::struct_excessive_bools)]
82
pub struct JpegDecoder<T> {
83
    /// Struct to hold image information from SOI
84
    pub(crate) info:              ImageInfo,
85
    ///  Quantization tables, will be set to none and the tables will
86
    /// be moved to `components` field
87
    pub(crate) qt_tables:         [Option<[i32; 64]>; MAX_COMPONENTS],
88
    /// DC Huffman Tables with a maximum of 4 tables for each  component
89
    pub(crate) dc_huffman_tables: [Option<HuffmanTable>; MAX_COMPONENTS],
90
    /// AC Huffman Tables with a maximum of 4 tables for each component
91
    pub(crate) ac_huffman_tables: [Option<HuffmanTable>; MAX_COMPONENTS],
92
    /// Image components, holds information like DC prediction and quantization
93
    /// tables of a component
94
    pub(crate) components:        Vec<Components>,
95
    /// maximum horizontal component of all channels in the image
96
    pub(crate) h_max:             usize,
97
    // maximum vertical component of all channels in the image
98
    pub(crate) v_max:             usize,
99
    /// mcu's  width (interleaved scans)
100
    pub(crate) mcu_width:         usize,
101
    /// MCU height(interleaved scans
102
    pub(crate) mcu_height:        usize,
103
    /// Number of MCU's in the x plane
104
    pub(crate) mcu_x:             usize,
105
    /// Number of MCU's in the y plane
106
    pub(crate) mcu_y:             usize,
107
    /// Is the image interleaved?
108
    pub(crate) is_interleaved:    bool,
109
    /// Image input colorspace, should be YCbCr for a sane image, might be
110
    /// grayscale too
111
    pub(crate) input_colorspace:  ColorSpace,
112
    // Progressive image details
113
    /// Is the image progressive?
114
    pub(crate) is_progressive:    bool,
115
116
    /// Start of spectral scan
117
    pub(crate) spec_start:       u8,
118
    /// End of spectral scan
119
    pub(crate) spec_end:         u8,
120
    /// Successive approximation bit position high
121
    pub(crate) succ_high:        u8,
122
    /// Successive approximation bit position low
123
    pub(crate) succ_low:         u8,
124
    /// Number of components.
125
    pub(crate) num_scans:        u8,
126
    /// For a scan, check if any component has vertical/horizontal sampling.
127
    pub(crate) scan_subsampled:  bool,
128
    // Function pointers, for pointy stuff.
129
    /// Dequantize and idct function
130
    // This is determined at runtime which function to run, statically it's
131
    // initialized to a platform independent one and during initialization
132
    // of this struct, we check if we can switch to a faster one which
133
    // depend on certain CPU extensions.
134
    pub(crate) idct_func: IDCTPtr,
135
    /// Specialized IDCT when we can guarantee only few coefficients are non-zero.
136
    ///
137
    /// **The callee must uphold a contract**. See [`choose_idct_4x4_func`].
138
    pub(crate) idct_4x4_func: IDCTPtr,
139
    pub(crate) idct_1x1_func: IDCTPtr,
140
    // Color convert function which acts on 16 YCbCr values
141
    pub(crate) color_convert_16: ColorConvert16Ptr,
142
    pub(crate) z_order:          [usize; MAX_COMPONENTS],
143
    /// restart markers
144
    pub(crate) restart_interval: usize,
145
    pub(crate) todo:             usize,
146
    // decoder options
147
    pub(crate) options:          DecoderOptions,
148
    // byte-stream
149
    pub(crate) stream:           ZReader<T>,
150
    // Indicate whether headers have been decoded
151
    pub(crate) headers_decoded:  bool,
152
    pub(crate) seen_sof:         bool,
153
154
    // exif data, lifted from app2
155
    pub(crate) icc_data: Vec<ICCChunk>,
156
    pub(crate) is_mjpeg: bool,
157
    pub(crate) coeff:    usize, // Solves some weird bug :)
158
    /// Extended XMP segments
159
    pub(crate) extended_xmp_segments: Vec<ExtendedXmpSegment>,
160
}
161
162
impl<T> JpegDecoder<T>
163
where
164
    T: ZByteReaderTrait
165
{
166
    #[allow(clippy::redundant_field_names)]
167
23.1k
    fn default(options: DecoderOptions, buffer: T) -> Self {
168
23.1k
        let color_convert = choose_ycbcr_to_rgb_convert_func(ColorSpace::RGB, &options).unwrap();
169
23.1k
        JpegDecoder {
170
23.1k
            info:              ImageInfo::default(),
171
23.1k
            qt_tables:         [None, None, None, None],
172
23.1k
            dc_huffman_tables: [None, None, None, None],
173
23.1k
            ac_huffman_tables: [None, None, None, None],
174
23.1k
            components:        vec![],
175
23.1k
            // Interleaved information
176
23.1k
            h_max:             1,
177
23.1k
            v_max:             1,
178
23.1k
            mcu_height:        0,
179
23.1k
            mcu_width:         0,
180
23.1k
            mcu_x:             0,
181
23.1k
            mcu_y:             0,
182
23.1k
            is_interleaved:    false,
183
23.1k
            is_progressive:    false,
184
23.1k
            spec_start:        0,
185
23.1k
            spec_end:          0,
186
23.1k
            succ_high:         0,
187
23.1k
            succ_low:          0,
188
23.1k
            num_scans:         0,
189
23.1k
            scan_subsampled:   false, 
190
23.1k
            idct_func:         choose_idct_func(&options),
191
23.1k
            idct_4x4_func:     choose_idct_4x4_func(&options),
192
23.1k
            idct_1x1_func:     choose_idct_1x1_func(&options),
193
23.1k
            color_convert_16:  color_convert,
194
23.1k
            input_colorspace:  ColorSpace::YCbCr,
195
23.1k
            z_order:           [0; MAX_COMPONENTS],
196
23.1k
            restart_interval:  0,
197
23.1k
            todo:              0x7fff_ffff,
198
23.1k
            options:           options,
199
23.1k
            stream:            ZReader::new(buffer),
200
23.1k
            headers_decoded:   false,
201
23.1k
            seen_sof:          false,
202
23.1k
            icc_data:          vec![],
203
23.1k
            is_mjpeg:          false,
204
23.1k
            coeff:             1,
205
23.1k
            extended_xmp_segments: vec![],
206
23.1k
        }
207
23.1k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::default
Line
Count
Source
167
9.99k
    fn default(options: DecoderOptions, buffer: T) -> Self {
168
9.99k
        let color_convert = choose_ycbcr_to_rgb_convert_func(ColorSpace::RGB, &options).unwrap();
169
9.99k
        JpegDecoder {
170
9.99k
            info:              ImageInfo::default(),
171
9.99k
            qt_tables:         [None, None, None, None],
172
9.99k
            dc_huffman_tables: [None, None, None, None],
173
9.99k
            ac_huffman_tables: [None, None, None, None],
174
9.99k
            components:        vec![],
175
9.99k
            // Interleaved information
176
9.99k
            h_max:             1,
177
9.99k
            v_max:             1,
178
9.99k
            mcu_height:        0,
179
9.99k
            mcu_width:         0,
180
9.99k
            mcu_x:             0,
181
9.99k
            mcu_y:             0,
182
9.99k
            is_interleaved:    false,
183
9.99k
            is_progressive:    false,
184
9.99k
            spec_start:        0,
185
9.99k
            spec_end:          0,
186
9.99k
            succ_high:         0,
187
9.99k
            succ_low:          0,
188
9.99k
            num_scans:         0,
189
9.99k
            scan_subsampled:   false, 
190
9.99k
            idct_func:         choose_idct_func(&options),
191
9.99k
            idct_4x4_func:     choose_idct_4x4_func(&options),
192
9.99k
            idct_1x1_func:     choose_idct_1x1_func(&options),
193
9.99k
            color_convert_16:  color_convert,
194
9.99k
            input_colorspace:  ColorSpace::YCbCr,
195
9.99k
            z_order:           [0; MAX_COMPONENTS],
196
9.99k
            restart_interval:  0,
197
9.99k
            todo:              0x7fff_ffff,
198
9.99k
            options:           options,
199
9.99k
            stream:            ZReader::new(buffer),
200
9.99k
            headers_decoded:   false,
201
9.99k
            seen_sof:          false,
202
9.99k
            icc_data:          vec![],
203
9.99k
            is_mjpeg:          false,
204
9.99k
            coeff:             1,
205
9.99k
            extended_xmp_segments: vec![],
206
9.99k
        }
207
9.99k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::default
Line
Count
Source
167
13.1k
    fn default(options: DecoderOptions, buffer: T) -> Self {
168
13.1k
        let color_convert = choose_ycbcr_to_rgb_convert_func(ColorSpace::RGB, &options).unwrap();
169
13.1k
        JpegDecoder {
170
13.1k
            info:              ImageInfo::default(),
171
13.1k
            qt_tables:         [None, None, None, None],
172
13.1k
            dc_huffman_tables: [None, None, None, None],
173
13.1k
            ac_huffman_tables: [None, None, None, None],
174
13.1k
            components:        vec![],
175
13.1k
            // Interleaved information
176
13.1k
            h_max:             1,
177
13.1k
            v_max:             1,
178
13.1k
            mcu_height:        0,
179
13.1k
            mcu_width:         0,
180
13.1k
            mcu_x:             0,
181
13.1k
            mcu_y:             0,
182
13.1k
            is_interleaved:    false,
183
13.1k
            is_progressive:    false,
184
13.1k
            spec_start:        0,
185
13.1k
            spec_end:          0,
186
13.1k
            succ_high:         0,
187
13.1k
            succ_low:          0,
188
13.1k
            num_scans:         0,
189
13.1k
            scan_subsampled:   false, 
190
13.1k
            idct_func:         choose_idct_func(&options),
191
13.1k
            idct_4x4_func:     choose_idct_4x4_func(&options),
192
13.1k
            idct_1x1_func:     choose_idct_1x1_func(&options),
193
13.1k
            color_convert_16:  color_convert,
194
13.1k
            input_colorspace:  ColorSpace::YCbCr,
195
13.1k
            z_order:           [0; MAX_COMPONENTS],
196
13.1k
            restart_interval:  0,
197
13.1k
            todo:              0x7fff_ffff,
198
13.1k
            options:           options,
199
13.1k
            stream:            ZReader::new(buffer),
200
13.1k
            headers_decoded:   false,
201
13.1k
            seen_sof:          false,
202
13.1k
            icc_data:          vec![],
203
13.1k
            is_mjpeg:          false,
204
13.1k
            coeff:             1,
205
13.1k
            extended_xmp_segments: vec![],
206
13.1k
        }
207
13.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::default
208
    /// Decode a buffer already in memory
209
    ///
210
    /// The buffer should be a valid jpeg file, perhaps created by the command
211
    /// `std:::fs::read()` or a JPEG file downloaded from the internet.
212
    ///
213
    /// # Errors
214
    /// See DecodeErrors for an explanation
215
11.1k
    pub fn decode(&mut self) -> Result<Vec<u8>, DecodeErrors> {
216
11.1k
        self.decode_headers()?;
217
11.1k
        let size = self.output_buffer_size().unwrap();
218
11.1k
        let mut out = vec![0; size];
219
11.1k
        self.decode_into(&mut out)?;
220
10.1k
        Ok(out)
221
11.1k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::decode
Line
Count
Source
215
11.1k
    pub fn decode(&mut self) -> Result<Vec<u8>, DecodeErrors> {
216
11.1k
        self.decode_headers()?;
217
11.1k
        let size = self.output_buffer_size().unwrap();
218
11.1k
        let mut out = vec![0; size];
219
11.1k
        self.decode_into(&mut out)?;
220
10.1k
        Ok(out)
221
11.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::decode
222
223
    /// Create a new Decoder instance
224
    ///
225
    /// # Arguments
226
    ///  - `stream`: The raw bytes of a jpeg file.
227
    #[must_use]
228
    #[allow(clippy::new_without_default)]
229
13.1k
    pub fn new(stream: T) -> JpegDecoder<T> {
230
13.1k
        JpegDecoder::default(DecoderOptions::default(), stream)
231
13.1k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::new
Line
Count
Source
229
13.1k
    pub fn new(stream: T) -> JpegDecoder<T> {
230
13.1k
        JpegDecoder::default(DecoderOptions::default(), stream)
231
13.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::new
232
233
    /// Returns the image information
234
    ///
235
    /// This **must** be called after a subsequent call to [`decode`] or [`decode_headers`]
236
    /// it will return `None`
237
    ///
238
    /// # Returns
239
    /// - `Some(info)`: Image information,width, height, number of components
240
    /// - None: Indicates image headers haven't been decoded
241
    ///
242
    /// [`decode`]: JpegDecoder::decode
243
    /// [`decode_headers`]: JpegDecoder::decode_headers
244
    #[must_use]
245
0
    pub fn info(&self) -> Option<ImageInfo> {
246
        // we check for fails to that call by comparing what we have to the default, if
247
        // it's default we assume that the caller failed to uphold the
248
        // guarantees. We can be sure that an image cannot be the default since
249
        // its a hard panic in-case width or height are set to zero.
250
0
        if !self.headers_decoded {
251
0
            return None;
252
0
        }
253
254
0
        return Some(self.info.clone());
255
0
    }
256
257
    /// Return the number of bytes required to hold a decoded image frame
258
    /// decoded using the given input transformations
259
    ///
260
    /// # Returns
261
    ///  - `Some(usize)`: Minimum size for a buffer needed to decode the image
262
    ///  - `None`: Indicates the image was not decoded, or image dimensions would overflow a usize
263
    ///
264
    #[must_use]
265
30.9k
    pub fn output_buffer_size(&self) -> Option<usize> {
266
30.9k
        return if self.headers_decoded {
267
            Some(
268
30.9k
                usize::from(self.width())
269
30.9k
                    .checked_mul(usize::from(self.height()))?
270
30.9k
                    .checked_mul(self.options.jpeg_get_out_colorspace().num_components())?
271
            )
272
        } else {
273
0
            None
274
        };
275
30.9k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::output_buffer_size
Line
Count
Source
265
8.69k
    pub fn output_buffer_size(&self) -> Option<usize> {
266
8.69k
        return if self.headers_decoded {
267
            Some(
268
8.69k
                usize::from(self.width())
269
8.69k
                    .checked_mul(usize::from(self.height()))?
270
8.69k
                    .checked_mul(self.options.jpeg_get_out_colorspace().num_components())?
271
            )
272
        } else {
273
0
            None
274
        };
275
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::output_buffer_size
Line
Count
Source
265
22.2k
    pub fn output_buffer_size(&self) -> Option<usize> {
266
22.2k
        return if self.headers_decoded {
267
            Some(
268
22.2k
                usize::from(self.width())
269
22.2k
                    .checked_mul(usize::from(self.height()))?
270
22.2k
                    .checked_mul(self.options.jpeg_get_out_colorspace().num_components())?
271
            )
272
        } else {
273
0
            None
274
        };
275
22.2k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::output_buffer_size
276
277
    /// Get an immutable reference to the decoder options
278
    /// for the decoder instance
279
    ///
280
    /// This can be used to modify options before actual decoding
281
    /// but after initial creation
282
    ///
283
    /// # Example
284
    /// ```no_run
285
    /// use zune_core::bytestream::ZCursor;
286
    /// use zune_jpeg::JpegDecoder;
287
    ///
288
    /// let mut decoder = JpegDecoder::new(ZCursor::new(&[]));
289
    /// // get current options
290
    /// let mut options = decoder.options();
291
    /// // modify it
292
    ///  let new_options = options.set_max_width(10);
293
    /// // set it back
294
    /// decoder.set_options(new_options);
295
    ///
296
    /// ```
297
    #[must_use]
298
8.69k
    pub const fn options(&self) -> &DecoderOptions {
299
8.69k
        &self.options
300
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::options
Line
Count
Source
298
8.69k
    pub const fn options(&self) -> &DecoderOptions {
299
8.69k
        &self.options
300
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::options
301
    /// Return the input colorspace of the image
302
    ///
303
    /// This indicates the colorspace that is present in
304
    /// the image, but this may be different to the colorspace that
305
    /// the output will be transformed to
306
    ///
307
    /// # Returns
308
    /// -`Some(Colorspace)`: Input colorspace
309
    /// - None : Indicates the headers weren't decoded
310
    #[must_use]
311
19.8k
    pub fn input_colorspace(&self) -> Option<ColorSpace> {
312
19.8k
        return if self.headers_decoded { Some(self.input_colorspace) } else { None };
313
19.8k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::input_colorspace
Line
Count
Source
311
8.69k
    pub fn input_colorspace(&self) -> Option<ColorSpace> {
312
8.69k
        return if self.headers_decoded { Some(self.input_colorspace) } else { None };
313
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::input_colorspace
Line
Count
Source
311
11.1k
    pub fn input_colorspace(&self) -> Option<ColorSpace> {
312
11.1k
        return if self.headers_decoded { Some(self.input_colorspace) } else { None };
313
11.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::input_colorspace
314
    /// Set decoder options
315
    ///
316
    /// This can be used to set new options even after initialization
317
    /// but before decoding.
318
    ///
319
    /// This does not bear any significance after decoding an image
320
    ///
321
    /// # Arguments
322
    /// - `options`: New decoder options
323
    ///
324
    /// # Example
325
    /// Set maximum jpeg progressive passes to be 4
326
    ///
327
    /// ```no_run
328
    /// use zune_core::bytestream::ZCursor;
329
    /// use zune_jpeg::JpegDecoder;
330
    /// let mut decoder =JpegDecoder::new(ZCursor::new(&[]));
331
    /// // this works also because DecoderOptions implements `Copy`
332
    /// let options = decoder.options().jpeg_set_max_scans(4);
333
    /// // set the new options
334
    /// decoder.set_options(options);
335
    /// // now decode
336
    /// decoder.decode().unwrap();
337
    /// ```
338
19.8k
    pub fn set_options(&mut self, options: DecoderOptions) {
339
19.8k
        self.options = options;
340
19.8k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::set_options
Line
Count
Source
338
8.69k
    pub fn set_options(&mut self, options: DecoderOptions) {
339
8.69k
        self.options = options;
340
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::set_options
Line
Count
Source
338
11.1k
    pub fn set_options(&mut self, options: DecoderOptions) {
339
11.1k
        self.options = options;
340
11.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::set_options
341
294k
    fn reassemble_extended_xmp(&mut self) {
342
294k
        if self.extended_xmp_segments.is_empty() {
343
0
            return;
344
294k
        }
345
346
        // Sort by offset
347
445M
        self.extended_xmp_segments.sort_by(|a, b| a.offset.cmp(&b.offset));
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::reassemble_extended_xmp::{closure#0}
Line
Count
Source
347
248M
        self.extended_xmp_segments.sort_by(|a, b| a.offset.cmp(&b.offset));
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::reassemble_extended_xmp::{closure#0}
Line
Count
Source
347
197M
        self.extended_xmp_segments.sort_by(|a, b| a.offset.cmp(&b.offset));
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::reassemble_extended_xmp::{closure#0}
348
349
294k
        let guid = &self.extended_xmp_segments[0].guid;
350
294k
        let total_size = self.extended_xmp_segments[0].total_size;
351
352
        // Check for consistency
353
436M
        for segment in &self.extended_xmp_segments {
354
436M
            if &segment.guid != guid || segment.total_size != total_size {
355
3.62k
                error!("Inconsistent Extended XMP segments");
356
3.62k
                self.extended_xmp_segments.clear();
357
3.62k
                return;
358
436M
            }
359
        }
360
361
290k
        let mut rolling_offset = 0;
362
290k
        let mut complete = true;
363
364
443k
        for segment in &self.extended_xmp_segments {
365
439k
            if segment.offset != rolling_offset {
366
                // Gap or overlap
367
286k
                complete = false;
368
286k
                break;
369
152k
            }
370
152k
            rolling_offset += segment.data.len() as u32;
371
        }
372
373
290k
        if complete && rolling_offset == total_size {
374
2.06k
            let mut result = Vec::with_capacity(total_size as usize);
375
4.41k
            for segment in &self.extended_xmp_segments {
376
2.35k
                result.extend_from_slice(&segment.data);
377
2.35k
            }
378
2.06k
            self.info.extended_xmp = Some(result);
379
2.06k
            self.info.extended_xmp_guid = Some(guid.clone());
380
2.06k
            self.extended_xmp_segments.clear();
381
288k
        } else if rolling_offset > total_size {
382
584
            error!("Extended XMP overflow");
383
584
            self.extended_xmp_segments.clear();
384
287k
        }
385
        // Else: Incomplete, wait for more.
386
294k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::reassemble_extended_xmp
Line
Count
Source
341
161k
    fn reassemble_extended_xmp(&mut self) {
342
161k
        if self.extended_xmp_segments.is_empty() {
343
0
            return;
344
161k
        }
345
346
        // Sort by offset
347
161k
        self.extended_xmp_segments.sort_by(|a, b| a.offset.cmp(&b.offset));
348
349
161k
        let guid = &self.extended_xmp_segments[0].guid;
350
161k
        let total_size = self.extended_xmp_segments[0].total_size;
351
352
        // Check for consistency
353
248M
        for segment in &self.extended_xmp_segments {
354
247M
            if &segment.guid != guid || segment.total_size != total_size {
355
1.53k
                error!("Inconsistent Extended XMP segments");
356
1.53k
                self.extended_xmp_segments.clear();
357
1.53k
                return;
358
247M
            }
359
        }
360
361
160k
        let mut rolling_offset = 0;
362
160k
        let mut complete = true;
363
364
308k
        for segment in &self.extended_xmp_segments {
365
306k
            if segment.offset != rolling_offset {
366
                // Gap or overlap
367
157k
                complete = false;
368
157k
                break;
369
148k
            }
370
148k
            rolling_offset += segment.data.len() as u32;
371
        }
372
373
160k
        if complete && rolling_offset == total_size {
374
1.43k
            let mut result = Vec::with_capacity(total_size as usize);
375
3.09k
            for segment in &self.extended_xmp_segments {
376
1.66k
                result.extend_from_slice(&segment.data);
377
1.66k
            }
378
1.43k
            self.info.extended_xmp = Some(result);
379
1.43k
            self.info.extended_xmp_guid = Some(guid.clone());
380
1.43k
            self.extended_xmp_segments.clear();
381
158k
        } else if rolling_offset > total_size {
382
260
            error!("Extended XMP overflow");
383
260
            self.extended_xmp_segments.clear();
384
158k
        }
385
        // Else: Incomplete, wait for more.
386
161k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::reassemble_extended_xmp
Line
Count
Source
341
132k
    fn reassemble_extended_xmp(&mut self) {
342
132k
        if self.extended_xmp_segments.is_empty() {
343
0
            return;
344
132k
        }
345
346
        // Sort by offset
347
132k
        self.extended_xmp_segments.sort_by(|a, b| a.offset.cmp(&b.offset));
348
349
132k
        let guid = &self.extended_xmp_segments[0].guid;
350
132k
        let total_size = self.extended_xmp_segments[0].total_size;
351
352
        // Check for consistency
353
188M
        for segment in &self.extended_xmp_segments {
354
188M
            if &segment.guid != guid || segment.total_size != total_size {
355
2.09k
                error!("Inconsistent Extended XMP segments");
356
2.09k
                self.extended_xmp_segments.clear();
357
2.09k
                return;
358
188M
            }
359
        }
360
361
130k
        let mut rolling_offset = 0;
362
130k
        let mut complete = true;
363
364
134k
        for segment in &self.extended_xmp_segments {
365
132k
            if segment.offset != rolling_offset {
366
                // Gap or overlap
367
128k
                complete = false;
368
128k
                break;
369
4.10k
            }
370
4.10k
            rolling_offset += segment.data.len() as u32;
371
        }
372
373
130k
        if complete && rolling_offset == total_size {
374
626
            let mut result = Vec::with_capacity(total_size as usize);
375
1.32k
            for segment in &self.extended_xmp_segments {
376
694
                result.extend_from_slice(&segment.data);
377
694
            }
378
626
            self.info.extended_xmp = Some(result);
379
626
            self.info.extended_xmp_guid = Some(guid.clone());
380
626
            self.extended_xmp_segments.clear();
381
129k
        } else if rolling_offset > total_size {
382
324
            error!("Extended XMP overflow");
383
324
            self.extended_xmp_segments.clear();
384
129k
        }
385
        // Else: Incomplete, wait for more.
386
132k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::reassemble_extended_xmp
387
    /// Decode Decoder headers
388
    ///
389
    /// This routine takes care of parsing supported headers from a Decoder
390
    /// image
391
    ///
392
    /// # Supported Headers
393
    ///  - APP(0)
394
    ///  - SOF(O)
395
    ///  - DQT -> Quantization tables
396
    ///  - DHT -> Huffman tables
397
    ///  - SOS -> Start of Scan
398
    /// # Unsupported Headers
399
    ///  - SOF(n) -> Decoder images which are not baseline/progressive
400
    ///  - DAC -> Images using Arithmetic tables
401
    ///  - JPG(n)
402
54.1k
    fn decode_headers_internal(&mut self) -> Result<(), DecodeErrors> {
403
54.1k
        if self.headers_decoded {
404
30.9k
            trace!("Headers decoded!");
405
30.9k
            return Ok(());
406
23.1k
        }
407
408
        // match output colorspace here
409
        // we know this will only be called once per image
410
        // so makes sense
411
        // We only care for ycbcr to rgb/rgba here
412
        // in case one is using another colorspace.
413
        // May god help you
414
23.1k
        let out_colorspace = self.options.jpeg_get_out_colorspace();
415
416
0
        if matches!(
417
23.1k
            out_colorspace,
418
            ColorSpace::BGR | ColorSpace::BGRA | ColorSpace::RGB | ColorSpace::RGBA
419
23.1k
        ) {
420
23.1k
            self.color_convert_16 = choose_ycbcr_to_rgb_convert_func(
421
23.1k
                self.options.jpeg_get_out_colorspace(),
422
23.1k
                &self.options
423
23.1k
            )
424
23.1k
            .unwrap();
425
23.1k
        }
426
        // First two bytes should be jpeg soi marker
427
23.1k
        let magic_bytes = self.stream.get_u16_be_err()?;
428
429
23.1k
        let mut last_byte = 0;
430
23.1k
        let mut bytes_before_marker = 0;
431
432
23.1k
        if magic_bytes != 0xffd8 {
433
138
            return Err(DecodeErrors::IllegalMagicBytes(magic_bytes));
434
22.9k
        }
435
436
        loop {
437
            // read a byte
438
26.0M
            let mut m = self.stream.read_u8_err()?;
439
440
            // AND OF COURSE some images will have fill bytes in their marker
441
            // bitstreams because why not.
442
            //
443
            // I am disappointed as a man.
444
26.0M
            if (m == 0xFF || m == 0) && last_byte == 0xFF {
445
                // This handles the edge case where
446
                // images have markers with fill bytes(0xFF)
447
                // or byte stuffing (0)
448
                // I.e 0xFF 0xFF 0xDA
449
                // and
450
                // 0xFF 0 0xDA
451
                // It should ignore those fill bytes and take 0xDA
452
                // I don't know why such images exist
453
                // but they do.
454
                // so this is for you (with love)
455
1.19M
                while m == 0xFF || m == 0x0 {
456
1.04M
                    last_byte = m;
457
1.04M
                    m = self.stream.read_u8_err()?;
458
                }
459
25.8M
            }
460
            // Last byte should be 0xFF to confirm existence of a marker since markers look
461
            // like OxFF(some marker data)
462
26.0M
            if last_byte == 0xFF {
463
669k
                let marker = Marker::from_u8(m);
464
669k
                if let Some(n) = marker {
465
669k
                    if bytes_before_marker > 3 {
466
355k
                        if self.options.strict_mode()
467
                        /*No reason to use this*/
468
                        {
469
0
                            return Err(DecodeErrors::FormatStatic(
470
0
                                "[strict-mode]: Extra bytes between headers"
471
0
                            ));
472
355k
                        }
473
474
355k
                        error!(
475
355k
                            "Extra bytes {} before marker 0xFF{:X}",
476
355k
                            bytes_before_marker - 3,
477
                            m
478
                        );
479
313k
                    }
480
481
669k
                    bytes_before_marker = 0;
482
483
669k
                    self.parse_marker_inner(n)?;
484
485
667k
                    if !self.extended_xmp_segments.is_empty() {
486
294k
                        self.reassemble_extended_xmp();
487
373k
                    }
488
489
                    // break after reading the start of scan.
490
                    // what follows is the image data
491
667k
                    if n == Marker::SOS {
492
19.8k
                        self.headers_decoded = true;
493
19.8k
                        trace!("Input colorspace {:?}", self.input_colorspace);
494
495
                        // Check if image is RGB
496
                        // The check is weird, we need to check if ID
497
                        // represents R, G and B in ascii,
498
                        //
499
                        // I am not sure if this is even specified in any standard,
500
                        // but jpegli https://github.com/google/jpegli does encode
501
                        // its images that way, so this will check for that. and handle it appropriately
502
                        // It is spefified here so that on a successful header decode,we can at least
503
                        // try to attribute image colorspace  correctly.
504
                        //
505
                        // It was first the issue in https://github.com/etemesi254/zune-image/issues/291
506
                        // that brought it to light
507
                        //
508
19.8k
                        let mut is_rgb = self.components.len() == 3;
509
19.8k
                        let chars = ['R', 'G', 'B'];
510
33.4k
                        for (comp, single_char) in self.components.iter().zip(chars.iter()) {
511
33.4k
                            is_rgb &= comp.id == (*single_char) as u8
512
                        }
513
                        // Image is RGB, change colorspace
514
19.8k
                        if is_rgb {
515
257
                            self.input_colorspace = ColorSpace::RGB;
516
19.5k
                        }
517
518
19.8k
                        return Ok(());
519
647k
                    }
520
                } else {
521
0
                    bytes_before_marker = 0;
522
523
0
                    warn!("Marker 0xFF{:X} not known", m);
524
525
0
                    let length = self.stream.get_u16_be_err()?;
526
527
0
                    if length < 2 {
528
0
                        return Err(DecodeErrors::Format(format!(
529
0
                            "Found a marker with invalid length : {length}"
530
0
                        )));
531
0
                    }
532
533
0
                    warn!("Skipping {} bytes", length - 2);
534
0
                    self.stream.skip((length - 2) as usize)?;
535
                }
536
25.3M
            }
537
25.9M
            last_byte = m;
538
25.9M
            bytes_before_marker += 1;
539
        }
540
        // Check if image is RGB
541
54.1k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::decode_headers_internal
Line
Count
Source
402
18.6k
    fn decode_headers_internal(&mut self) -> Result<(), DecodeErrors> {
403
18.6k
        if self.headers_decoded {
404
8.69k
            trace!("Headers decoded!");
405
8.69k
            return Ok(());
406
9.99k
        }
407
408
        // match output colorspace here
409
        // we know this will only be called once per image
410
        // so makes sense
411
        // We only care for ycbcr to rgb/rgba here
412
        // in case one is using another colorspace.
413
        // May god help you
414
9.99k
        let out_colorspace = self.options.jpeg_get_out_colorspace();
415
416
0
        if matches!(
417
9.99k
            out_colorspace,
418
            ColorSpace::BGR | ColorSpace::BGRA | ColorSpace::RGB | ColorSpace::RGBA
419
9.99k
        ) {
420
9.99k
            self.color_convert_16 = choose_ycbcr_to_rgb_convert_func(
421
9.99k
                self.options.jpeg_get_out_colorspace(),
422
9.99k
                &self.options
423
9.99k
            )
424
9.99k
            .unwrap();
425
9.99k
        }
426
        // First two bytes should be jpeg soi marker
427
9.99k
        let magic_bytes = self.stream.get_u16_be_err()?;
428
429
9.99k
        let mut last_byte = 0;
430
9.99k
        let mut bytes_before_marker = 0;
431
432
9.99k
        if magic_bytes != 0xffd8 {
433
3
            return Err(DecodeErrors::IllegalMagicBytes(magic_bytes));
434
9.99k
        }
435
436
        loop {
437
            // read a byte
438
12.0M
            let mut m = self.stream.read_u8_err()?;
439
440
            // AND OF COURSE some images will have fill bytes in their marker
441
            // bitstreams because why not.
442
            //
443
            // I am disappointed as a man.
444
12.0M
            if (m == 0xFF || m == 0) && last_byte == 0xFF {
445
                // This handles the edge case where
446
                // images have markers with fill bytes(0xFF)
447
                // or byte stuffing (0)
448
                // I.e 0xFF 0xFF 0xDA
449
                // and
450
                // 0xFF 0 0xDA
451
                // It should ignore those fill bytes and take 0xDA
452
                // I don't know why such images exist
453
                // but they do.
454
                // so this is for you (with love)
455
765k
                while m == 0xFF || m == 0x0 {
456
666k
                    last_byte = m;
457
666k
                    m = self.stream.read_u8_err()?;
458
                }
459
11.9M
            }
460
            // Last byte should be 0xFF to confirm existence of a marker since markers look
461
            // like OxFF(some marker data)
462
12.0M
            if last_byte == 0xFF {
463
427k
                let marker = Marker::from_u8(m);
464
427k
                if let Some(n) = marker {
465
427k
                    if bytes_before_marker > 3 {
466
150k
                        if self.options.strict_mode()
467
                        /*No reason to use this*/
468
                        {
469
0
                            return Err(DecodeErrors::FormatStatic(
470
0
                                "[strict-mode]: Extra bytes between headers"
471
0
                            ));
472
150k
                        }
473
474
150k
                        error!(
475
150k
                            "Extra bytes {} before marker 0xFF{:X}",
476
150k
                            bytes_before_marker - 3,
477
                            m
478
                        );
479
277k
                    }
480
481
427k
                    bytes_before_marker = 0;
482
483
427k
                    self.parse_marker_inner(n)?;
484
485
426k
                    if !self.extended_xmp_segments.is_empty() {
486
161k
                        self.reassemble_extended_xmp();
487
264k
                    }
488
489
                    // break after reading the start of scan.
490
                    // what follows is the image data
491
426k
                    if n == Marker::SOS {
492
8.69k
                        self.headers_decoded = true;
493
8.69k
                        trace!("Input colorspace {:?}", self.input_colorspace);
494
495
                        // Check if image is RGB
496
                        // The check is weird, we need to check if ID
497
                        // represents R, G and B in ascii,
498
                        //
499
                        // I am not sure if this is even specified in any standard,
500
                        // but jpegli https://github.com/google/jpegli does encode
501
                        // its images that way, so this will check for that. and handle it appropriately
502
                        // It is spefified here so that on a successful header decode,we can at least
503
                        // try to attribute image colorspace  correctly.
504
                        //
505
                        // It was first the issue in https://github.com/etemesi254/zune-image/issues/291
506
                        // that brought it to light
507
                        //
508
8.69k
                        let mut is_rgb = self.components.len() == 3;
509
8.69k
                        let chars = ['R', 'G', 'B'];
510
14.8k
                        for (comp, single_char) in self.components.iter().zip(chars.iter()) {
511
14.8k
                            is_rgb &= comp.id == (*single_char) as u8
512
                        }
513
                        // Image is RGB, change colorspace
514
8.69k
                        if is_rgb {
515
65
                            self.input_colorspace = ColorSpace::RGB;
516
8.63k
                        }
517
518
8.69k
                        return Ok(());
519
417k
                    }
520
                } else {
521
0
                    bytes_before_marker = 0;
522
523
0
                    warn!("Marker 0xFF{:X} not known", m);
524
525
0
                    let length = self.stream.get_u16_be_err()?;
526
527
0
                    if length < 2 {
528
0
                        return Err(DecodeErrors::Format(format!(
529
0
                            "Found a marker with invalid length : {length}"
530
0
                        )));
531
0
                    }
532
533
0
                    warn!("Skipping {} bytes", length - 2);
534
0
                    self.stream.skip((length - 2) as usize)?;
535
                }
536
11.6M
            }
537
12.0M
            last_byte = m;
538
12.0M
            bytes_before_marker += 1;
539
        }
540
        // Check if image is RGB
541
18.6k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::decode_headers_internal
Line
Count
Source
402
35.4k
    fn decode_headers_internal(&mut self) -> Result<(), DecodeErrors> {
403
35.4k
        if self.headers_decoded {
404
22.2k
            trace!("Headers decoded!");
405
22.2k
            return Ok(());
406
13.1k
        }
407
408
        // match output colorspace here
409
        // we know this will only be called once per image
410
        // so makes sense
411
        // We only care for ycbcr to rgb/rgba here
412
        // in case one is using another colorspace.
413
        // May god help you
414
13.1k
        let out_colorspace = self.options.jpeg_get_out_colorspace();
415
416
0
        if matches!(
417
13.1k
            out_colorspace,
418
            ColorSpace::BGR | ColorSpace::BGRA | ColorSpace::RGB | ColorSpace::RGBA
419
13.1k
        ) {
420
13.1k
            self.color_convert_16 = choose_ycbcr_to_rgb_convert_func(
421
13.1k
                self.options.jpeg_get_out_colorspace(),
422
13.1k
                &self.options
423
13.1k
            )
424
13.1k
            .unwrap();
425
13.1k
        }
426
        // First two bytes should be jpeg soi marker
427
13.1k
        let magic_bytes = self.stream.get_u16_be_err()?;
428
429
13.1k
        let mut last_byte = 0;
430
13.1k
        let mut bytes_before_marker = 0;
431
432
13.1k
        if magic_bytes != 0xffd8 {
433
135
            return Err(DecodeErrors::IllegalMagicBytes(magic_bytes));
434
12.9k
        }
435
436
        loop {
437
            // read a byte
438
13.9M
            let mut m = self.stream.read_u8_err()?;
439
440
            // AND OF COURSE some images will have fill bytes in their marker
441
            // bitstreams because why not.
442
            //
443
            // I am disappointed as a man.
444
13.9M
            if (m == 0xFF || m == 0) && last_byte == 0xFF {
445
                // This handles the edge case where
446
                // images have markers with fill bytes(0xFF)
447
                // or byte stuffing (0)
448
                // I.e 0xFF 0xFF 0xDA
449
                // and
450
                // 0xFF 0 0xDA
451
                // It should ignore those fill bytes and take 0xDA
452
                // I don't know why such images exist
453
                // but they do.
454
                // so this is for you (with love)
455
425k
                while m == 0xFF || m == 0x0 {
456
380k
                    last_byte = m;
457
380k
                    m = self.stream.read_u8_err()?;
458
                }
459
13.9M
            }
460
            // Last byte should be 0xFF to confirm existence of a marker since markers look
461
            // like OxFF(some marker data)
462
13.9M
            if last_byte == 0xFF {
463
241k
                let marker = Marker::from_u8(m);
464
241k
                if let Some(n) = marker {
465
241k
                    if bytes_before_marker > 3 {
466
205k
                        if self.options.strict_mode()
467
                        /*No reason to use this*/
468
                        {
469
0
                            return Err(DecodeErrors::FormatStatic(
470
0
                                "[strict-mode]: Extra bytes between headers"
471
0
                            ));
472
205k
                        }
473
474
205k
                        error!(
475
205k
                            "Extra bytes {} before marker 0xFF{:X}",
476
205k
                            bytes_before_marker - 3,
477
                            m
478
                        );
479
36.2k
                    }
480
481
241k
                    bytes_before_marker = 0;
482
483
241k
                    self.parse_marker_inner(n)?;
484
485
240k
                    if !self.extended_xmp_segments.is_empty() {
486
132k
                        self.reassemble_extended_xmp();
487
132k
                    }
488
489
                    // break after reading the start of scan.
490
                    // what follows is the image data
491
240k
                    if n == Marker::SOS {
492
11.1k
                        self.headers_decoded = true;
493
11.1k
                        trace!("Input colorspace {:?}", self.input_colorspace);
494
495
                        // Check if image is RGB
496
                        // The check is weird, we need to check if ID
497
                        // represents R, G and B in ascii,
498
                        //
499
                        // I am not sure if this is even specified in any standard,
500
                        // but jpegli https://github.com/google/jpegli does encode
501
                        // its images that way, so this will check for that. and handle it appropriately
502
                        // It is spefified here so that on a successful header decode,we can at least
503
                        // try to attribute image colorspace  correctly.
504
                        //
505
                        // It was first the issue in https://github.com/etemesi254/zune-image/issues/291
506
                        // that brought it to light
507
                        //
508
11.1k
                        let mut is_rgb = self.components.len() == 3;
509
11.1k
                        let chars = ['R', 'G', 'B'];
510
18.5k
                        for (comp, single_char) in self.components.iter().zip(chars.iter()) {
511
18.5k
                            is_rgb &= comp.id == (*single_char) as u8
512
                        }
513
                        // Image is RGB, change colorspace
514
11.1k
                        if is_rgb {
515
192
                            self.input_colorspace = ColorSpace::RGB;
516
10.9k
                        }
517
518
11.1k
                        return Ok(());
519
229k
                    }
520
                } else {
521
0
                    bytes_before_marker = 0;
522
523
0
                    warn!("Marker 0xFF{:X} not known", m);
524
525
0
                    let length = self.stream.get_u16_be_err()?;
526
527
0
                    if length < 2 {
528
0
                        return Err(DecodeErrors::Format(format!(
529
0
                            "Found a marker with invalid length : {length}"
530
0
                        )));
531
0
                    }
532
533
0
                    warn!("Skipping {} bytes", length - 2);
534
0
                    self.stream.skip((length - 2) as usize)?;
535
                }
536
13.7M
            }
537
13.9M
            last_byte = m;
538
13.9M
            bytes_before_marker += 1;
539
        }
540
        // Check if image is RGB
541
35.4k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::decode_headers_internal
542
    #[allow(clippy::too_many_lines)]
543
1.28M
    pub(crate) fn parse_marker_inner(&mut self, m: Marker) -> Result<(), DecodeErrors> {
544
1.28M
        match m {
545
20.1k
            Marker::SOF(0..=2) => {
546
20.1k
                let marker = {
547
                    // choose marker
548
20.1k
                    if m == Marker::SOF(0) || m == Marker::SOF(1) {
549
5.68k
                        SOFMarkers::BaselineDct
550
                    } else {
551
14.5k
                        self.is_progressive = true;
552
14.5k
                        SOFMarkers::ProgressiveDctHuffman
553
                    }
554
                };
555
556
20.1k
                trace!("Image encoding scheme =`{:?}`", marker);
557
                // get components
558
20.1k
                parse_start_of_frame(marker, self)?;
559
            }
560
            // Start of Frame Segments not supported
561
0
            Marker::SOF(v) => {
562
0
                let feature = UnsupportedSchemes::from_int(v);
563
564
0
                if let Some(feature) = feature {
565
0
                    return Err(DecodeErrors::Unsupported(feature));
566
0
                }
567
568
0
                return Err(DecodeErrors::Format("Unsupported image format".to_string()));
569
            }
570
            //APP(0) segment
571
            Marker::APP(0) => {
572
158k
                let mut length = self.stream.get_u16_be_err()?;
573
574
158k
                if length < 2 {
575
12
                    return Err(DecodeErrors::Format(format!(
576
12
                        "Found a marker with invalid length:{length}\n"
577
12
                    )));
578
158k
                }
579
                // skip for now
580
158k
                if length > 5 {
581
79.7k
                    let mut buffer = [0u8; 5];
582
79.7k
                    self.stream.read_exact_bytes(&mut buffer)?;
583
79.7k
                    if &buffer == b"AVI1\0" {
584
43.8k
                        self.is_mjpeg = true;
585
43.8k
                    }
586
79.7k
                    length -= 5;
587
78.4k
                }
588
589
158k
                self.stream.skip(length.saturating_sub(2) as usize)?;
590
591
                //parse_app(buf, m, &mut self.info)?;
592
            }
593
            Marker::APP(1) => {
594
353k
                parse_app1(self)?;
595
            }
596
597
            Marker::APP(2) => {
598
279k
                parse_app2(self)?;
599
            }
600
            // Quantization tables
601
            Marker::DQT => {
602
108k
                parse_dqt(self)?;
603
            }
604
            // Huffman tables
605
            Marker::DHT => {
606
37.0k
                parse_huffman(self)?;
607
            }
608
            // Start of Scan Data
609
            Marker::SOS => {
610
61.2k
                parse_sos(self)?;
611
            }
612
11
            Marker::EOI => return Err(DecodeErrors::FormatStatic("Premature End of image")),
613
614
            Marker::DAC | Marker::DNL => {
615
75
                return Err(DecodeErrors::Format(format!(
616
75
                    "Parsing of the following header `{m:?}` is not supported,\
617
75
                                cannot continue"
618
75
                )));
619
            }
620
            Marker::DRI => {
621
15.5k
                if self.stream.get_u16_be_err()? != 4 {
622
39
                    return Err(DecodeErrors::Format(
623
39
                        "Bad DRI length, Corrupt JPEG".to_string()
624
39
                    ));
625
15.5k
                }
626
627
15.5k
                self.restart_interval = usize::from(self.stream.get_u16_be_err()?);
628
15.5k
                trace!("DRI marker present ({})", self.restart_interval);
629
630
15.5k
                self.todo = self.restart_interval;
631
            }
632
            Marker::APP(14) => {
633
70.8k
                parse_app14(self)?;
634
            }
635
            Marker::APP(13) => {
636
40.9k
                parse_app13(self)?;
637
            }
638
            _ => {
639
139k
                warn!(
640
139k
                    "Capabilities for processing marker \"{:?}\" not implemented",
641
                    m
642
                );
643
644
139k
                let length = self.stream.get_u16_be_err()?;
645
646
139k
                if length < 2 {
647
174
                    return Err(DecodeErrors::Format(format!(
648
174
                        "Found a marker with invalid length:{length}\n"
649
174
                    )));
650
139k
                }
651
139k
                warn!("Skipping {} bytes", length - 2);
652
139k
                self.stream.skip((length - 2) as usize)?;
653
            }
654
        }
655
1.28M
        Ok(())
656
1.28M
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::parse_marker_inner
Line
Count
Source
543
849k
    pub(crate) fn parse_marker_inner(&mut self, m: Marker) -> Result<(), DecodeErrors> {
544
849k
        match m {
545
8.84k
            Marker::SOF(0..=2) => {
546
8.84k
                let marker = {
547
                    // choose marker
548
8.84k
                    if m == Marker::SOF(0) || m == Marker::SOF(1) {
549
2.59k
                        SOFMarkers::BaselineDct
550
                    } else {
551
6.25k
                        self.is_progressive = true;
552
6.25k
                        SOFMarkers::ProgressiveDctHuffman
553
                    }
554
                };
555
556
8.84k
                trace!("Image encoding scheme =`{:?}`", marker);
557
                // get components
558
8.84k
                parse_start_of_frame(marker, self)?;
559
            }
560
            // Start of Frame Segments not supported
561
0
            Marker::SOF(v) => {
562
0
                let feature = UnsupportedSchemes::from_int(v);
563
564
0
                if let Some(feature) = feature {
565
0
                    return Err(DecodeErrors::Unsupported(feature));
566
0
                }
567
568
0
                return Err(DecodeErrors::Format("Unsupported image format".to_string()));
569
            }
570
            //APP(0) segment
571
            Marker::APP(0) => {
572
124k
                let mut length = self.stream.get_u16_be_err()?;
573
574
124k
                if length < 2 {
575
9
                    return Err(DecodeErrors::Format(format!(
576
9
                        "Found a marker with invalid length:{length}\n"
577
9
                    )));
578
124k
                }
579
                // skip for now
580
124k
                if length > 5 {
581
47.0k
                    let mut buffer = [0u8; 5];
582
47.0k
                    self.stream.read_exact_bytes(&mut buffer)?;
583
47.0k
                    if &buffer == b"AVI1\0" {
584
25.5k
                        self.is_mjpeg = true;
585
25.5k
                    }
586
47.0k
                    length -= 5;
587
77.5k
                }
588
589
124k
                self.stream.skip(length.saturating_sub(2) as usize)?;
590
591
                //parse_app(buf, m, &mut self.info)?;
592
            }
593
            Marker::APP(1) => {
594
211k
                parse_app1(self)?;
595
            }
596
597
            Marker::APP(2) => {
598
208k
                parse_app2(self)?;
599
            }
600
            // Quantization tables
601
            Marker::DQT => {
602
46.0k
                parse_dqt(self)?;
603
            }
604
            // Huffman tables
605
            Marker::DHT => {
606
14.7k
                parse_huffman(self)?;
607
            }
608
            // Start of Scan Data
609
            Marker::SOS => {
610
19.0k
                parse_sos(self)?;
611
            }
612
6
            Marker::EOI => return Err(DecodeErrors::FormatStatic("Premature End of image")),
613
614
            Marker::DAC | Marker::DNL => {
615
47
                return Err(DecodeErrors::Format(format!(
616
47
                    "Parsing of the following header `{m:?}` is not supported,\
617
47
                                cannot continue"
618
47
                )));
619
            }
620
            Marker::DRI => {
621
7.29k
                if self.stream.get_u16_be_err()? != 4 {
622
30
                    return Err(DecodeErrors::Format(
623
30
                        "Bad DRI length, Corrupt JPEG".to_string()
624
30
                    ));
625
7.25k
                }
626
627
7.25k
                self.restart_interval = usize::from(self.stream.get_u16_be_err()?);
628
7.25k
                trace!("DRI marker present ({})", self.restart_interval);
629
630
7.25k
                self.todo = self.restart_interval;
631
            }
632
            Marker::APP(14) => {
633
59.9k
                parse_app14(self)?;
634
            }
635
            Marker::APP(13) => {
636
32.8k
                parse_app13(self)?;
637
            }
638
            _ => {
639
116k
                warn!(
640
116k
                    "Capabilities for processing marker \"{:?}\" not implemented",
641
                    m
642
                );
643
644
116k
                let length = self.stream.get_u16_be_err()?;
645
646
116k
                if length < 2 {
647
75
                    return Err(DecodeErrors::Format(format!(
648
75
                        "Found a marker with invalid length:{length}\n"
649
75
                    )));
650
116k
                }
651
116k
                warn!("Skipping {} bytes", length - 2);
652
116k
                self.stream.skip((length - 2) as usize)?;
653
            }
654
        }
655
846k
        Ok(())
656
849k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::parse_marker_inner
Line
Count
Source
543
435k
    pub(crate) fn parse_marker_inner(&mut self, m: Marker) -> Result<(), DecodeErrors> {
544
435k
        match m {
545
11.3k
            Marker::SOF(0..=2) => {
546
11.3k
                let marker = {
547
                    // choose marker
548
11.3k
                    if m == Marker::SOF(0) || m == Marker::SOF(1) {
549
3.09k
                        SOFMarkers::BaselineDct
550
                    } else {
551
8.25k
                        self.is_progressive = true;
552
8.25k
                        SOFMarkers::ProgressiveDctHuffman
553
                    }
554
                };
555
556
11.3k
                trace!("Image encoding scheme =`{:?}`", marker);
557
                // get components
558
11.3k
                parse_start_of_frame(marker, self)?;
559
            }
560
            // Start of Frame Segments not supported
561
0
            Marker::SOF(v) => {
562
0
                let feature = UnsupportedSchemes::from_int(v);
563
564
0
                if let Some(feature) = feature {
565
0
                    return Err(DecodeErrors::Unsupported(feature));
566
0
                }
567
568
0
                return Err(DecodeErrors::Format("Unsupported image format".to_string()));
569
            }
570
            //APP(0) segment
571
            Marker::APP(0) => {
572
33.6k
                let mut length = self.stream.get_u16_be_err()?;
573
574
33.6k
                if length < 2 {
575
3
                    return Err(DecodeErrors::Format(format!(
576
3
                        "Found a marker with invalid length:{length}\n"
577
3
                    )));
578
33.6k
                }
579
                // skip for now
580
33.6k
                if length > 5 {
581
32.7k
                    let mut buffer = [0u8; 5];
582
32.7k
                    self.stream.read_exact_bytes(&mut buffer)?;
583
32.7k
                    if &buffer == b"AVI1\0" {
584
18.2k
                        self.is_mjpeg = true;
585
18.2k
                    }
586
32.7k
                    length -= 5;
587
887
                }
588
589
33.5k
                self.stream.skip(length.saturating_sub(2) as usize)?;
590
591
                //parse_app(buf, m, &mut self.info)?;
592
            }
593
            Marker::APP(1) => {
594
141k
                parse_app1(self)?;
595
            }
596
597
            Marker::APP(2) => {
598
71.1k
                parse_app2(self)?;
599
            }
600
            // Quantization tables
601
            Marker::DQT => {
602
62.1k
                parse_dqt(self)?;
603
            }
604
            // Huffman tables
605
            Marker::DHT => {
606
22.2k
                parse_huffman(self)?;
607
            }
608
            // Start of Scan Data
609
            Marker::SOS => {
610
42.2k
                parse_sos(self)?;
611
            }
612
5
            Marker::EOI => return Err(DecodeErrors::FormatStatic("Premature End of image")),
613
614
            Marker::DAC | Marker::DNL => {
615
28
                return Err(DecodeErrors::Format(format!(
616
28
                    "Parsing of the following header `{m:?}` is not supported,\
617
28
                                cannot continue"
618
28
                )));
619
            }
620
            Marker::DRI => {
621
8.28k
                if self.stream.get_u16_be_err()? != 4 {
622
9
                    return Err(DecodeErrors::Format(
623
9
                        "Bad DRI length, Corrupt JPEG".to_string()
624
9
                    ));
625
8.26k
                }
626
627
8.26k
                self.restart_interval = usize::from(self.stream.get_u16_be_err()?);
628
8.26k
                trace!("DRI marker present ({})", self.restart_interval);
629
630
8.26k
                self.todo = self.restart_interval;
631
            }
632
            Marker::APP(14) => {
633
10.8k
                parse_app14(self)?;
634
            }
635
            Marker::APP(13) => {
636
8.09k
                parse_app13(self)?;
637
            }
638
            _ => {
639
23.6k
                warn!(
640
23.6k
                    "Capabilities for processing marker \"{:?}\" not implemented",
641
                    m
642
                );
643
644
23.6k
                let length = self.stream.get_u16_be_err()?;
645
646
23.6k
                if length < 2 {
647
99
                    return Err(DecodeErrors::Format(format!(
648
99
                        "Found a marker with invalid length:{length}\n"
649
99
                    )));
650
23.5k
                }
651
23.5k
                warn!("Skipping {} bytes", length - 2);
652
23.5k
                self.stream.skip((length - 2) as usize)?;
653
            }
654
        }
655
433k
        Ok(())
656
435k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::parse_marker_inner
657
    /// Get the embedded ICC profile if it exists
658
    /// and is correct
659
    ///
660
    /// One needs not to decode the whole image to extract this,
661
    /// calling [`decode_headers`] for an image with an ICC profile
662
    /// allows you to decode this
663
    ///
664
    /// # Returns
665
    /// - `Some(Vec<u8>)`: The raw ICC profile of the image
666
    /// - `None`: May indicate an error  in the ICC profile , non-existence of
667
    /// an ICC profile, or that the headers weren't decoded.
668
    ///
669
    /// [`decode_headers`]:Self::decode_headers
670
    #[must_use]
671
8.69k
    pub fn icc_profile(&self) -> Option<Vec<u8>> {
672
8.69k
        let mut marker_present: [Option<&ICCChunk>; 256] = [None; 256];
673
674
8.69k
        if !self.headers_decoded {
675
0
            return None;
676
8.69k
        }
677
8.69k
        let num_markers = self.icc_data.len();
678
679
8.69k
        if num_markers == 0 || num_markers >= 255 {
680
6.79k
            return None;
681
1.90k
        }
682
        // check validity
683
3.67k
        for chunk in &self.icc_data {
684
1.90k
            if usize::from(chunk.num_markers) != num_markers {
685
                // all the lengths must match
686
133
                return None;
687
1.77k
            }
688
1.77k
            if chunk.seq_no == 0 {
689
0
                warn!("Zero sequence number in ICC, corrupt ICC chunk");
690
0
                return None;
691
1.77k
            }
692
1.77k
            if marker_present[usize::from(chunk.seq_no)].is_some() {
693
                // duplicate seq_no
694
2
                warn!("Duplicate sequence number in ICC, corrupt chunk");
695
2
                return None;
696
1.77k
            }
697
698
1.77k
            marker_present[usize::from(chunk.seq_no)] = Some(chunk);
699
        }
700
1.76k
        let mut data = Vec::with_capacity(1000);
701
        // assemble the data now
702
1.76k
        for chunk in marker_present.get(1..=num_markers).unwrap() {
703
1.76k
            if let Some(ch) = chunk {
704
1.76k
                data.extend_from_slice(&ch.data);
705
1.76k
            } else {
706
0
                warn!("Missing icc sequence number, corrupt ICC chunk ");
707
0
                return None;
708
            }
709
        }
710
711
1.76k
        Some(data)
712
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::icc_profile
Line
Count
Source
671
8.69k
    pub fn icc_profile(&self) -> Option<Vec<u8>> {
672
8.69k
        let mut marker_present: [Option<&ICCChunk>; 256] = [None; 256];
673
674
8.69k
        if !self.headers_decoded {
675
0
            return None;
676
8.69k
        }
677
8.69k
        let num_markers = self.icc_data.len();
678
679
8.69k
        if num_markers == 0 || num_markers >= 255 {
680
6.79k
            return None;
681
1.90k
        }
682
        // check validity
683
3.67k
        for chunk in &self.icc_data {
684
1.90k
            if usize::from(chunk.num_markers) != num_markers {
685
                // all the lengths must match
686
133
                return None;
687
1.77k
            }
688
1.77k
            if chunk.seq_no == 0 {
689
0
                warn!("Zero sequence number in ICC, corrupt ICC chunk");
690
0
                return None;
691
1.77k
            }
692
1.77k
            if marker_present[usize::from(chunk.seq_no)].is_some() {
693
                // duplicate seq_no
694
2
                warn!("Duplicate sequence number in ICC, corrupt chunk");
695
2
                return None;
696
1.77k
            }
697
698
1.77k
            marker_present[usize::from(chunk.seq_no)] = Some(chunk);
699
        }
700
1.76k
        let mut data = Vec::with_capacity(1000);
701
        // assemble the data now
702
1.76k
        for chunk in marker_present.get(1..=num_markers).unwrap() {
703
1.76k
            if let Some(ch) = chunk {
704
1.76k
                data.extend_from_slice(&ch.data);
705
1.76k
            } else {
706
0
                warn!("Missing icc sequence number, corrupt ICC chunk ");
707
0
                return None;
708
            }
709
        }
710
711
1.76k
        Some(data)
712
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::icc_profile
713
    /// Return the exif data for the file
714
    ///
715
    /// This returns the raw exif data starting at the
716
    /// TIFF header
717
    ///
718
    /// # Returns
719
    /// -`Some(data)`: The raw exif data, if present in the image
720
    /// - None: May indicate the following
721
    ///
722
    ///    1. The image doesn't have exif data
723
    ///    2. The image headers haven't been decoded
724
    #[must_use]
725
8.69k
    pub fn exif(&self) -> Option<&Vec<u8>> {
726
8.69k
        return self.info.exif_data.as_ref();
727
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::exif
Line
Count
Source
725
8.69k
    pub fn exif(&self) -> Option<&Vec<u8>> {
726
8.69k
        return self.info.exif_data.as_ref();
727
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::exif
728
    /// Return the XMP data for the file
729
    ///
730
    /// This returns raw XMP data starting at the XML header
731
    /// One needs an XML/XMP decoder to extract valuable metadata
732
    ///
733
    ///
734
    /// # Returns
735
    ///  - `Some(data)`: Raw xmp data
736
    ///  - `None`: May indicate the following
737
    ///     1. The image does not have xmp data
738
    ///     2. The image headers have not been decoded
739
    ///
740
    /// # Example
741
    ///
742
    /// ```no_run
743
    /// use zune_core::bytestream::ZCursor;
744
    /// use zune_jpeg::JpegDecoder;
745
    /// let mut decoder = JpegDecoder::new(ZCursor::new(&[]));
746
    /// // decode headers to extract xmp metadata if present
747
    /// decoder.decode_headers().unwrap();
748
    /// if let Some(data) = decoder.xmp(){
749
    ///     let stringified = String::from_utf8_lossy(data);
750
    ///     println!("XMP")
751
    /// } else{
752
    ///     println!("No XMP Found")
753
    /// }
754
    ///
755
    /// ```
756
8.69k
    pub fn xmp(&self) -> Option<&Vec<u8>> {
757
8.69k
        return self.info.xmp_data.as_ref();
758
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::xmp
Line
Count
Source
756
8.69k
    pub fn xmp(&self) -> Option<&Vec<u8>> {
757
8.69k
        return self.info.xmp_data.as_ref();
758
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::xmp
759
    /// Return the IPTC data for the file
760
    ///
761
    /// This returns the raw IPTC data.
762
    ///
763
    /// # Returns
764
    /// -`Some(data)`: The raw IPTC data, if present in the image
765
    /// - None: May indicate the following
766
    ///
767
    ///    1. The image doesn't have IPTC data
768
    ///    2. The image headers haven't been decoded
769
    #[must_use]
770
8.69k
    pub fn iptc(&self) -> Option<&Vec<u8>> {
771
8.69k
        return self.info.iptc_data.as_ref();
772
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::iptc
Line
Count
Source
770
8.69k
    pub fn iptc(&self) -> Option<&Vec<u8>> {
771
8.69k
        return self.info.iptc_data.as_ref();
772
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::iptc
773
    /// Get the output colorspace the image pixels will be decoded into
774
    ///
775
    ///
776
    /// # Note.
777
    /// This field can only be regarded after decoding headers,
778
    /// as markers such as Adobe APP14 may dictate different colorspaces
779
    /// than requested.
780
    ///
781
    /// Calling `decode_headers` is sufficient to know what colorspace the
782
    /// output is, if this is called after `decode` it indicates the colorspace
783
    /// the output is currently in
784
    ///
785
    /// Additionally not all input->output colorspace mappings are supported
786
    /// but all input colorspaces can map to RGB colorspace, so that's a safe bet
787
    /// if one is handling image formats
788
    ///
789
    ///# Returns
790
    /// - `Some(Colorspace)`: If headers have been decoded, the colorspace the
791
    ///output array will be in
792
    ///- `None
793
    #[must_use]
794
0
    pub fn output_colorspace(&self) -> Option<ColorSpace> {
795
0
        return if self.headers_decoded {
796
0
            Some(self.options.jpeg_get_out_colorspace())
797
        } else {
798
0
            None
799
        };
800
0
    }
801
802
    /// Decode into a pre-allocated buffer
803
    ///
804
    /// It is an error if the buffer size is smaller than
805
    /// [`output_buffer_size()`](Self::output_buffer_size)
806
    ///
807
    /// If the buffer is bigger than expected, we ignore the end padding bytes
808
    ///
809
    /// # Example
810
    ///
811
    /// - Read  headers and then alloc a buffer big enough to hold the image
812
    ///
813
    /// ```no_run
814
    /// use zune_core::bytestream::ZCursor;
815
    /// use zune_jpeg::JpegDecoder;
816
    /// let mut decoder = JpegDecoder::new(ZCursor::new(&[]));
817
    /// // before we get output, we must decode the headers to get width
818
    /// // height, and input colorspace
819
    /// decoder.decode_headers().unwrap();
820
    ///
821
    /// let mut out = vec![0;decoder.output_buffer_size().unwrap()];
822
    /// // write into out
823
    /// decoder.decode_into(&mut out).unwrap();
824
    /// ```
825
    ///
826
    ///
827
19.8k
    pub fn decode_into(&mut self, out: &mut [u8]) -> Result<(), DecodeErrors> {
828
19.8k
        self.decode_headers_internal()?;
829
830
19.8k
        let expected_size = self.output_buffer_size().unwrap();
831
832
19.8k
        if out.len() < expected_size {
833
            // too small of a size
834
0
            return Err(DecodeErrors::TooSmallOutput(expected_size, out.len()));
835
19.8k
        }
836
837
        // ensure we don't touch anyone else's scratch space
838
19.8k
        let out_len = core::cmp::min(out.len(), expected_size);
839
19.8k
        let out = &mut out[0..out_len];
840
841
19.8k
        if self.is_progressive {
842
14.2k
            self.decode_mcu_ycbcr_progressive(out)
843
        } else {
844
5.54k
            self.decode_mcu_ycbcr_baseline(out)
845
        }
846
19.8k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::decode_into
Line
Count
Source
827
8.69k
    pub fn decode_into(&mut self, out: &mut [u8]) -> Result<(), DecodeErrors> {
828
8.69k
        self.decode_headers_internal()?;
829
830
8.69k
        let expected_size = self.output_buffer_size().unwrap();
831
832
8.69k
        if out.len() < expected_size {
833
            // too small of a size
834
0
            return Err(DecodeErrors::TooSmallOutput(expected_size, out.len()));
835
8.69k
        }
836
837
        // ensure we don't touch anyone else's scratch space
838
8.69k
        let out_len = core::cmp::min(out.len(), expected_size);
839
8.69k
        let out = &mut out[0..out_len];
840
841
8.69k
        if self.is_progressive {
842
6.14k
            self.decode_mcu_ycbcr_progressive(out)
843
        } else {
844
2.54k
            self.decode_mcu_ycbcr_baseline(out)
845
        }
846
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::decode_into
Line
Count
Source
827
11.1k
    pub fn decode_into(&mut self, out: &mut [u8]) -> Result<(), DecodeErrors> {
828
11.1k
        self.decode_headers_internal()?;
829
830
11.1k
        let expected_size = self.output_buffer_size().unwrap();
831
832
11.1k
        if out.len() < expected_size {
833
            // too small of a size
834
0
            return Err(DecodeErrors::TooSmallOutput(expected_size, out.len()));
835
11.1k
        }
836
837
        // ensure we don't touch anyone else's scratch space
838
11.1k
        let out_len = core::cmp::min(out.len(), expected_size);
839
11.1k
        let out = &mut out[0..out_len];
840
841
11.1k
        if self.is_progressive {
842
8.13k
            self.decode_mcu_ycbcr_progressive(out)
843
        } else {
844
3.00k
            self.decode_mcu_ycbcr_baseline(out)
845
        }
846
11.1k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::decode_into
847
848
    /// Read only headers from a jpeg image buffer
849
    ///
850
    /// This allows you to extract important information like
851
    /// image width and height without decoding the full image
852
    ///
853
    /// # Examples
854
    /// ```no_run
855
    /// use zune_core::bytestream::ZCursor;
856
    /// use zune_jpeg::{JpegDecoder};
857
    ///
858
    /// let img_data = std::fs::read("a_valid.jpeg").unwrap();
859
    /// let mut decoder = JpegDecoder::new(ZCursor::new(&img_data));
860
    /// decoder.decode_headers().unwrap();
861
    ///
862
    /// println!("Total decoder dimensions are : {:?} pixels",decoder.dimensions());
863
    /// println!("Number of components in the image are {}", decoder.info().unwrap().components);
864
    /// ```
865
    /// # Errors
866
    /// See DecodeErrors enum for list of possible errors during decoding
867
34.2k
    pub fn decode_headers(&mut self) -> Result<(), DecodeErrors> {
868
34.2k
        self.decode_headers_internal()?;
869
30.9k
        Ok(())
870
34.2k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::decode_headers
Line
Count
Source
867
9.99k
    pub fn decode_headers(&mut self) -> Result<(), DecodeErrors> {
868
9.99k
        self.decode_headers_internal()?;
869
8.69k
        Ok(())
870
9.99k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::decode_headers
Line
Count
Source
867
24.2k
    pub fn decode_headers(&mut self) -> Result<(), DecodeErrors> {
868
24.2k
        self.decode_headers_internal()?;
869
22.2k
        Ok(())
870
24.2k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::decode_headers
871
    /// Create a new decoder with the specified options to be used for decoding
872
    /// an image
873
    ///
874
    /// # Arguments
875
    /// - `buf`: The input buffer from where we will pull in compressed jpeg bytes from
876
    /// - `options`: Options specific to this decoder instance
877
    #[must_use]
878
9.99k
    pub fn new_with_options(buf: T, options: DecoderOptions) -> JpegDecoder<T> {
879
9.99k
        JpegDecoder::default(options, buf)
880
9.99k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::new_with_options
Line
Count
Source
878
9.99k
    pub fn new_with_options(buf: T, options: DecoderOptions) -> JpegDecoder<T> {
879
9.99k
        JpegDecoder::default(options, buf)
880
9.99k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::new_with_options
881
882
    /// Set up-sampling routines in case an image is down sampled
883
7.36k
    pub(crate) fn set_upsampling(&mut self) -> Result<(), DecodeErrors> {
884
        // no sampling, return early
885
        // check if horizontal max ==1
886
7.36k
        if self.h_max == self.v_max && self.h_max == 1 {
887
0
            return Ok(());
888
7.36k
        }
889
890
31.0k
        for comp in &mut self.components {
891
23.6k
            let hs = self.h_max / comp.horizontal_sample;
892
23.6k
            let vs = self.v_max / comp.vertical_sample;
893
894
23.6k
            let samp_factor = match (hs, vs) {
895
8.56k
                (1, 1) => {
896
8.56k
                    comp.sample_ratio = SampleRatios::None;
897
8.56k
                    upsample_no_op
898
8.56k
                }
899
                (2, 1) => {
900
1.39k
                    comp.sample_ratio = SampleRatios::H;
901
1.39k
                    choose_horizontal_samp_function(&self.options)
902
                }
903
                (1, 2) => {
904
7.05k
                    comp.sample_ratio = SampleRatios::V;
905
7.05k
                    choose_v_samp_function(&self.options)
906
                }
907
                (2, 2) => {
908
1.80k
                    comp.sample_ratio = SampleRatios::HV;
909
1.80k
                    choose_hv_samp_function(&self.options)
910
                }
911
4.82k
                (hs, vs) => {
912
4.82k
                    comp.sample_ratio = SampleRatios::Generic(hs, vs);
913
4.82k
                    generic_sampler()
914
                }
915
            };
916
23.6k
            comp.setup_upsample_scanline();
917
23.6k
            comp.up_sampler = samp_factor;
918
        }
919
920
7.36k
        return Ok(());
921
7.36k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::set_upsampling
Line
Count
Source
883
3.94k
    pub(crate) fn set_upsampling(&mut self) -> Result<(), DecodeErrors> {
884
        // no sampling, return early
885
        // check if horizontal max ==1
886
3.94k
        if self.h_max == self.v_max && self.h_max == 1 {
887
0
            return Ok(());
888
3.94k
        }
889
890
14.1k
        for comp in &mut self.components {
891
10.2k
            let hs = self.h_max / comp.horizontal_sample;
892
10.2k
            let vs = self.v_max / comp.vertical_sample;
893
894
10.2k
            let samp_factor = match (hs, vs) {
895
5.50k
                (1, 1) => {
896
5.50k
                    comp.sample_ratio = SampleRatios::None;
897
5.50k
                    upsample_no_op
898
5.50k
                }
899
                (2, 1) => {
900
251
                    comp.sample_ratio = SampleRatios::H;
901
251
                    choose_horizontal_samp_function(&self.options)
902
                }
903
                (1, 2) => {
904
2.71k
                    comp.sample_ratio = SampleRatios::V;
905
2.71k
                    choose_v_samp_function(&self.options)
906
                }
907
                (2, 2) => {
908
1.38k
                    comp.sample_ratio = SampleRatios::HV;
909
1.38k
                    choose_hv_samp_function(&self.options)
910
                }
911
395
                (hs, vs) => {
912
395
                    comp.sample_ratio = SampleRatios::Generic(hs, vs);
913
395
                    generic_sampler()
914
                }
915
            };
916
10.2k
            comp.setup_upsample_scanline();
917
10.2k
            comp.up_sampler = samp_factor;
918
        }
919
920
3.94k
        return Ok(());
921
3.94k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::set_upsampling
Line
Count
Source
883
3.42k
    pub(crate) fn set_upsampling(&mut self) -> Result<(), DecodeErrors> {
884
        // no sampling, return early
885
        // check if horizontal max ==1
886
3.42k
        if self.h_max == self.v_max && self.h_max == 1 {
887
0
            return Ok(());
888
3.42k
        }
889
890
16.8k
        for comp in &mut self.components {
891
13.3k
            let hs = self.h_max / comp.horizontal_sample;
892
13.3k
            let vs = self.v_max / comp.vertical_sample;
893
894
13.3k
            let samp_factor = match (hs, vs) {
895
3.05k
                (1, 1) => {
896
3.05k
                    comp.sample_ratio = SampleRatios::None;
897
3.05k
                    upsample_no_op
898
3.05k
                }
899
                (2, 1) => {
900
1.14k
                    comp.sample_ratio = SampleRatios::H;
901
1.14k
                    choose_horizontal_samp_function(&self.options)
902
                }
903
                (1, 2) => {
904
4.34k
                    comp.sample_ratio = SampleRatios::V;
905
4.34k
                    choose_v_samp_function(&self.options)
906
                }
907
                (2, 2) => {
908
415
                    comp.sample_ratio = SampleRatios::HV;
909
415
                    choose_hv_samp_function(&self.options)
910
                }
911
4.43k
                (hs, vs) => {
912
4.43k
                    comp.sample_ratio = SampleRatios::Generic(hs, vs);
913
4.43k
                    generic_sampler()
914
                }
915
            };
916
13.3k
            comp.setup_upsample_scanline();
917
13.3k
            comp.up_sampler = samp_factor;
918
        }
919
920
3.42k
        return Ok(());
921
3.42k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::set_upsampling
922
    #[must_use]
923
    /// Get the width of the image as a u16
924
    ///
925
    /// The width lies between 1 and 65535
926
50.7k
    pub(crate) fn width(&self) -> u16 {
927
50.7k
        self.info.width
928
50.7k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::width
Line
Count
Source
926
17.3k
    pub(crate) fn width(&self) -> u16 {
927
17.3k
        self.info.width
928
17.3k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::width
Line
Count
Source
926
33.4k
    pub(crate) fn width(&self) -> u16 {
927
33.4k
        self.info.width
928
33.4k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::width
929
930
    /// Get the height of the image as a u16
931
    ///
932
    /// The height lies between 1 and 65535
933
    #[must_use]
934
50.7k
    pub(crate) fn height(&self) -> u16 {
935
50.7k
        self.info.height
936
50.7k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::height
Line
Count
Source
934
17.3k
    pub(crate) fn height(&self) -> u16 {
935
17.3k
        self.info.height
936
17.3k
    }
<zune_jpeg::decoder::JpegDecoder<zune_core::bytestream::reader::no_std_readers::ZCursor<alloc::vec::Vec<u8>>>>::height
Line
Count
Source
934
33.4k
    pub(crate) fn height(&self) -> u16 {
935
33.4k
        self.info.height
936
33.4k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::height
937
938
    /// Get image dimensions as a tuple of width and height
939
    /// or `None` if the image hasn't been decoded.
940
    ///
941
    /// # Returns
942
    /// - `Some(width,height)`: Image dimensions
943
    /// -  None : The image headers haven't been decoded
944
    #[must_use]
945
8.69k
    pub const fn dimensions(&self) -> Option<(usize, usize)> {
946
8.69k
        return if self.headers_decoded {
947
8.69k
            Some((self.info.width as usize, self.info.height as usize))
948
        } else {
949
0
            None
950
        };
951
8.69k
    }
<zune_jpeg::decoder::JpegDecoder<std::io::cursor::Cursor<&[u8]>>>::dimensions
Line
Count
Source
945
8.69k
    pub const fn dimensions(&self) -> Option<(usize, usize)> {
946
8.69k
        return if self.headers_decoded {
947
8.69k
            Some((self.info.width as usize, self.info.height as usize))
948
        } else {
949
0
            None
950
        };
951
8.69k
    }
Unexecuted instantiation: <zune_jpeg::decoder::JpegDecoder<_>>::dimensions
952
}
953
954
#[derive(Default, Clone, Eq, PartialEq, Debug)]
955
pub struct GainMapInfo {
956
    pub data: Vec<u8>
957
}
958
959
#[derive(Default, Clone, Eq, PartialEq, Debug)]
960
pub(crate) struct ExtendedXmpSegment {
961
    pub(crate) offset: u32,
962
    pub(crate) total_size: u32,
963
    pub(crate) guid: Vec<u8>,
964
    pub(crate) data: Vec<u8>,
965
}
966
967
/// A struct representing Image Information
968
#[derive(Default, Clone, Eq, PartialEq)]
969
#[allow(clippy::module_name_repetitions)]
970
pub struct ImageInfo {
971
    /// Width of the image
972
    pub width: u16,
973
    /// Height of image
974
    pub height: u16,
975
    /// PixelDensity
976
    pub pixel_density: u8,
977
    /// Start of frame markers
978
    pub sof: SOFMarkers,
979
    /// Horizontal sample
980
    pub x_density: u16,
981
    /// Vertical sample
982
    pub y_density: u16,
983
    /// Number of components
984
    pub components: u8,
985
    /// Gain Map information, useful for
986
    /// UHDR images
987
    pub gain_map_info: Vec<GainMapInfo>,
988
    /// Multi picture information, useful for
989
    /// UHDR images
990
    pub multi_picture_information: Option<Vec<u8>>,
991
    /// Exif Data
992
    pub exif_data: Option<Vec<u8>>,
993
    /// XMP Data
994
    pub xmp_data: Option<Vec<u8>>,
995
    /// IPTC Data
996
    pub iptc_data: Option<Vec<u8>>,
997
    /// Extended XMP Data
998
    pub extended_xmp: Option<Vec<u8>>,
999
    /// Extended XMP Guid
1000
    pub extended_xmp_guid: Option<Vec<u8>>,
1001
    /// Image sub-sampling ratio
1002
    pub sample_ratio: SampleRatios,
1003
    /// The offset at which Multi picture information was found
1004
    pub multi_picture_information_offset: Option<u64>,
1005
}
1006
1007
impl ImageInfo {
1008
    /// Set width of the image
1009
    ///
1010
    /// Found in the start of frame
1011
1012
20.0k
    pub(crate) fn set_width(&mut self, width: u16) {
1013
20.0k
        self.width = width;
1014
20.0k
    }
1015
1016
    /// Set height of the image
1017
    ///
1018
    /// Found in the start of frame
1019
1020
20.0k
    pub(crate) fn set_height(&mut self, height: u16) {
1021
20.0k
        self.height = height;
1022
20.0k
    }
1023
1024
    /// Set the image density
1025
    ///
1026
    /// Found in the start of frame
1027
1028
20.0k
    pub(crate) fn set_density(&mut self, density: u8) {
1029
20.0k
        self.pixel_density = density;
1030
20.0k
    }
1031
1032
    /// Set image Start of frame marker
1033
    ///
1034
    /// found in the Start of frame header
1035
1036
19.9k
    pub(crate) fn set_sof_marker(&mut self, marker: SOFMarkers) {
1037
19.9k
        self.sof = marker;
1038
19.9k
    }
1039
1040
    /// Set image x-density(dots per pixel)
1041
    ///
1042
    /// Found in the APP(0) marker
1043
    #[allow(dead_code)]
1044
0
    pub(crate) fn set_x(&mut self, sample: u16) {
1045
0
        self.x_density = sample;
1046
0
    }
1047
1048
    /// Set image y-density
1049
    ///
1050
    /// Found in the APP(0) marker
1051
    #[allow(dead_code)]
1052
0
    pub(crate) fn set_y(&mut self, sample: u16) {
1053
0
        self.y_density = sample;
1054
0
    }
1055
}