Debian Codegraph @

.cargo/vendor/zune-jpeg/src/decoder.rs

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