Skip to main content

euv_core/media/image/
impl.rs

1use super::*;
2
3/// Conversion helpers for `DecodedRgbaImage`.
4impl DecodedRgbaImage {
5    /// Converts this decoded RGBA8 image into an `ImageBuffer`.
6    ///
7    /// # Arguments
8    ///
9    /// - `Self` - Decoded RGBA8 image.
10    ///
11    /// # Returns
12    ///
13    /// - `ImageBuffer` - Ready RGBA8 image buffer.
14    #[must_use]
15    pub fn into_image_buffer(self) -> ImageBuffer {
16        let Self {
17            width,
18            height,
19            pixels,
20            ..
21        } = self;
22        ImageBuffer::new(width, height, pixels)
23    }
24}
25
26/// Tonemapping and pixel lookup helpers for `DecodedHdrImage`.
27impl DecodedHdrImage {
28    /// Converts this linear HDR RGBA32F image to 8-bit sRGB RGBA8 using simple Reinhard exposure tone mapping.
29    ///
30    /// # Arguments
31    ///
32    /// - `&Self` - Source linear HDR image.
33    /// - `f32` - Linear exposure multiplier (`1.0` for neutral exposure).
34    ///
35    /// # Returns
36    ///
37    /// - `DecodedRgbaImage` - Tone-mapped RGBA8 image.
38    #[must_use]
39    pub fn to_tonemapped_rgba8(&self, exposure: f32) -> DecodedRgbaImage {
40        let width: u32 = self.get_width();
41        let height: u32 = self.get_height();
42        let src: &[f32] = self.get_pixels().as_slice();
43        let pixel_count: usize = (width as usize).saturating_mul(height as usize);
44        let mut rgba: Vec<u8> = Vec::with_capacity(pixel_count.saturating_mul(4));
45        let gain: f32 = exposure.max(0.0);
46        for pixel_idx in 0..pixel_count {
47            let base: usize = pixel_idx * 4;
48            let red_lin: f32 = (src[base].max(0.0) * gain).min(1e6);
49            let green_lin: f32 = (src[base + 1].max(0.0) * gain).min(1e6);
50            let blue_lin: f32 = (src[base + 2].max(0.0) * gain).min(1e6);
51            let alpha_lin: f32 = src[base + 3].clamp(0.0, 1.0);
52            let red_tm: f32 = red_lin / (1.0 + red_lin);
53            let green_tm: f32 = green_lin / (1.0 + green_lin);
54            let blue_tm: f32 = blue_lin / (1.0 + blue_lin);
55            rgba.push((red_tm.powf(1.0 / 2.2).clamp(0.0, 1.0) * 255.0).round() as u8);
56            rgba.push((green_tm.powf(1.0 / 2.2).clamp(0.0, 1.0) * 255.0).round() as u8);
57            rgba.push((blue_tm.powf(1.0 / 2.2).clamp(0.0, 1.0) * 255.0).round() as u8);
58            rgba.push((alpha_lin * 255.0).round() as u8);
59        }
60        DecodedRgbaImage {
61            width,
62            height,
63            pixels: rgba,
64            format: self.get_format(),
65        }
66    }
67}
68
69/// Bitstream reading helpers for `DeflateBitReader`.
70impl<'a> DeflateBitReader<'a> {
71    /// Creates a new `DeflateBitReader` positioned at the start of `data`.
72    ///
73    /// # Arguments
74    ///
75    /// - `&'a [u8]` - Compressed RFC 1951 byte stream.
76    ///
77    /// # Returns
78    ///
79    /// - `Self` - Initialized bit reader.
80    #[must_use]
81    pub(crate) fn new(data: &'a [u8]) -> Self {
82        Self {
83            data,
84            byte_pos: 0,
85            bit_buf: 0,
86            bit_count: 0,
87        }
88    }
89
90    /// Ensures at least `needed` bits are buffered in `bit_buf`.
91    ///
92    /// # Arguments
93    ///
94    /// - `&Self` - Mutable bit reader.
95    /// - `u8` - Minimum required bit count (`<= 56`).
96    pub(crate) fn fill_bits(&mut self, needed: u8) {
97        let Self {
98            data,
99            byte_pos,
100            bit_buf,
101            bit_count,
102        } = self;
103        while *bit_count < needed && *byte_pos < data.len() {
104            let next_byte: u64 = u64::from(data[*byte_pos]);
105            *bit_buf |= next_byte << *bit_count;
106            *byte_pos += 1;
107            *bit_count += 8;
108        }
109    }
110
111    /// Reads `count` LSB-first bits as a `u32`.
112    ///
113    /// # Arguments
114    ///
115    /// - `&Self` - Mutable bit reader.
116    /// - `u8` - Number of bits to read (`0..=24`).
117    ///
118    /// # Returns
119    ///
120    /// - `Result<u32, String>` - Decoded bit field or truncation error.
121    pub(crate) fn read_bits(&mut self, count: u8) -> Result<u32, String> {
122        if count == 0 {
123            return Ok(0);
124        }
125        self.fill_bits(count);
126        let Self {
127            bit_buf, bit_count, ..
128        } = self;
129        if *bit_count < count {
130            return Err(ERR_DEFLATE_INVALID.to_string());
131        }
132        let mask: u64 = (1u64 << count) - 1;
133        let value: u32 = (*bit_buf & mask) as u32;
134        *bit_buf >>= count;
135        *bit_count -= count;
136        Ok(value)
137    }
138
139    /// Discards remaining partial bits in the current byte to align on a byte boundary.
140    ///
141    /// # Arguments
142    ///
143    /// - `&Self` - Mutable bit reader.
144    pub(crate) fn align_to_byte(&mut self) {
145        let Self {
146            bit_buf, bit_count, ..
147        } = self;
148        let discard: u8 = *bit_count & 7;
149        if discard > 0 {
150            *bit_buf >>= discard;
151            *bit_count -= discard;
152        }
153    }
154
155    /// Reads one full aligned byte, consuming buffered bytes before reading from `data`.
156    ///
157    /// # Arguments
158    ///
159    /// - `&Self` - Mutable bit reader.
160    ///
161    /// # Returns
162    ///
163    /// - `Result<u8, String>` - Next byte or truncation error.
164    pub(crate) fn read_aligned_byte(&mut self) -> Result<u8, String> {
165        let Self {
166            data,
167            byte_pos,
168            bit_buf,
169            bit_count,
170        } = self;
171        if *bit_count >= 8 {
172            let value: u8 = (*bit_buf & 0xFF) as u8;
173            *bit_buf >>= 8;
174            *bit_count -= 8;
175            return Ok(value);
176        }
177        if *byte_pos >= data.len() {
178            return Err(ERR_DEFLATE_INVALID.to_string());
179        }
180        let value: u8 = data[*byte_pos];
181        *byte_pos += 1;
182        Ok(value)
183    }
184
185    /// Returns the effective byte index after accounting for buffered whole unread bytes.
186    ///
187    /// # Arguments
188    ///
189    /// - `&Self` - Bit reader reference.
190    ///
191    /// # Returns
192    ///
193    /// - `usize` - Consumed byte position inside `data`.
194    #[must_use]
195    pub(crate) fn consumed_bytes(&self) -> usize {
196        let Self {
197            byte_pos,
198            bit_count,
199            ..
200        } = self;
201        let unread_whole: usize = (*bit_count as usize) / 8;
202        byte_pos.saturating_sub(unread_whole)
203    }
204}
205
206/// Canonical Huffman construction and symbol decoding for `DeflateHuffmanTable`.
207impl DeflateHuffmanTable {
208    /// Constructs a canonical DEFLATE Huffman table from symbol code lengths.
209    ///
210    /// # Arguments
211    ///
212    /// - `&[u8]` - Code length in bits for each symbol (`0` = unused, `1..=15` = active).
213    ///
214    /// # Returns
215    ///
216    /// - `Result<Self, String>` - Validated Huffman table or error.
217    pub(crate) fn from_code_lengths(lengths: &[u8]) -> Result<Self, String> {
218        let mut counts: [u16; 16] = [0u16; 16];
219        let mut max_bits: u8 = 0;
220        for &bit_len in lengths.iter() {
221            if bit_len > 15 {
222                return Err(ERR_DEFLATE_HUFFMAN.to_string());
223            }
224            if bit_len > 0 {
225                counts[bit_len as usize] = counts[bit_len as usize].saturating_add(1);
226                if bit_len > max_bits {
227                    max_bits = bit_len;
228                }
229            }
230        }
231        let mut total_symbols: usize = 0;
232        for &count_val in counts.iter().skip(1) {
233            total_symbols += count_val as usize;
234        }
235        if total_symbols == 0 {
236            return Ok(Self {
237                counts,
238                symbols: Vec::new(),
239                max_bits: 0,
240            });
241        }
242        let mut left: i32 = 1;
243        for &count_val in counts.iter().skip(1) {
244            left <<= 1;
245            left -= i32::from(count_val);
246            if left < 0 {
247                return Err(ERR_DEFLATE_HUFFMAN.to_string());
248            }
249        }
250        let mut offsets: [usize; 16] = [0usize; 16];
251        let mut running: usize = 0;
252        for bit_len in 1..=15usize {
253            offsets[bit_len] = running;
254            running += counts[bit_len] as usize;
255        }
256        let mut symbols: Vec<u16> = vec![0u16; total_symbols];
257        for (symbol_idx, &bit_len) in lengths.iter().enumerate() {
258            if bit_len > 0 {
259                let slot: usize = offsets[bit_len as usize];
260                symbols[slot] = symbol_idx as u16;
261                offsets[bit_len as usize] += 1;
262            }
263        }
264        Ok(Self {
265            counts,
266            symbols,
267            max_bits,
268        })
269    }
270
271    /// Decodes a single canonical Huffman symbol from `reader`.
272    ///
273    /// # Arguments
274    ///
275    /// - `&Self` - Huffman table reference.
276    /// - `&mut DeflateBitReader<'_>` - Active DEFLATE bitstream reader.
277    ///
278    /// # Returns
279    ///
280    /// - `Result<u16, String>` - Decoded symbol value or bitstream error.
281    pub(crate) fn decode(&self, reader: &mut DeflateBitReader<'_>) -> Result<u16, String> {
282        let Self {
283            counts,
284            symbols,
285            max_bits,
286        } = self;
287        if *max_bits == 0 {
288            return Err(ERR_DEFLATE_HUFFMAN.to_string());
289        }
290        let mut code: i32 = 0;
291        let mut first: i32 = 0;
292        let mut index: usize = 0;
293        for &raw_count in counts.iter().take((*max_bits as usize) + 1).skip(1) {
294            let bit: i32 = reader.read_bits(1)? as i32;
295            code |= bit;
296            let count: i32 = i32::from(raw_count);
297            if code - count < first {
298                let sym_idx: usize = index + (code - first) as usize;
299                return symbols
300                    .get(sym_idx)
301                    .copied()
302                    .ok_or_else(|| ERR_DEFLATE_HUFFMAN.to_string());
303            }
304            index += count as usize;
305            first = (first + count) << 1;
306            code <<= 1;
307        }
308        Err(ERR_DEFLATE_HUFFMAN.to_string())
309    }
310}
311
312/// Canonical MSB-first Huffman helpers for `JpegHuffmanTable`.
313impl JpegHuffmanTable {
314    /// Builds a JPEG Huffman decoding table from DHT `counts` and `values`.
315    ///
316    /// # Arguments
317    ///
318    /// - `[u8; 16]` - Code count for lengths `1..=16`.
319    /// - `Vec<u8>` - Ordered symbol bytes.
320    ///
321    /// # Returns
322    ///
323    /// - `Self` - Populated JPEG Huffman decoding table.
324    #[must_use]
325    pub(crate) fn from_dht(counts: [u8; 16], values: Vec<u8>) -> Self {
326        let mut max_code: [i32; 17] = [-1i32; 17];
327        let mut val_offset: [i32; 17] = [0i32; 17];
328        let mut code: i32 = 0;
329        let mut val_idx: i32 = 0;
330        for bit_len in 1..=16usize {
331            let count: i32 = i32::from(counts[bit_len - 1]);
332            if count > 0 {
333                val_offset[bit_len] = val_idx - code;
334                val_idx += count;
335                code += count;
336                max_code[bit_len] = code - 1;
337            }
338            code <<= 1;
339        }
340        Self {
341            max_code,
342            val_offset,
343            values,
344            valid: true,
345        }
346    }
347
348    /// Decodes a single JPEG Huffman symbol from `reader`.
349    ///
350    /// # Arguments
351    ///
352    /// - `&Self` - JPEG Huffman table reference.
353    /// - `&mut JpegBitReader<'_>` - Active JPEG entropy reader.
354    ///
355    /// # Returns
356    ///
357    /// - `Result<u8, String>` - Decoded symbol byte or bitstream error.
358    pub(crate) fn decode(&self, reader: &mut JpegBitReader<'_>) -> Result<u8, String> {
359        let Self {
360            max_code,
361            val_offset,
362            values,
363            valid,
364            ..
365        } = self;
366        if !*valid {
367            return Err(ERR_JPEG_INVALID.to_string());
368        }
369        let mut code: i32 = 0;
370        for bit_len in 1..=16usize {
371            let bit: i32 = reader.read_bit()? as i32;
372            code = (code << 1) | bit;
373            if max_code[bit_len] >= 0 && code <= max_code[bit_len] {
374                let idx: i32 = code + val_offset[bit_len];
375                if idx < 0 || (idx as usize) >= values.len() {
376                    return Err(ERR_JPEG_INVALID.to_string());
377                }
378                return Ok(values[idx as usize]);
379            }
380        }
381        Err(ERR_JPEG_INVALID.to_string())
382    }
383}
384
385/// Canonical JPEG Huffman encoder table construction for `JpegHuffmanEncodeTable`.
386impl JpegHuffmanEncodeTable {
387    /// Builds an encoding lookup table from Annex K `bits` counts and `values`.
388    ///
389    /// # Arguments
390    ///
391    /// - `&[u8; 16]` - Code counts for bit lengths `1..=16`.
392    /// - `&[u8]` - Canonical symbol sequence.
393    ///
394    /// # Returns
395    ///
396    /// - `Self` - Populated encoding lookup table.
397    #[must_use]
398    pub(crate) fn from_spec(bits: &[u8; 16], values: &[u8]) -> Self {
399        let mut codes: [u16; 256] = [0u16; 256];
400        let mut lengths: [u8; 256] = [0u8; 256];
401        let mut code: u32 = 0;
402        let mut val_cursor: usize = 0;
403        for bit_len in 1..=16usize {
404            let count: usize = bits[bit_len - 1] as usize;
405            for _ in 0..count {
406                if val_cursor < values.len() {
407                    let sym: usize = values[val_cursor] as usize;
408                    codes[sym] = code as u16;
409                    lengths[sym] = bit_len as u8;
410                    val_cursor += 1;
411                }
412                code += 1;
413            }
414            code <<= 1;
415        }
416        Self { codes, lengths }
417    }
418}
419
420/// MSB-first JPEG entropy bitstream reader methods for `JpegBitReader`.
421impl<'a> JpegBitReader<'a> {
422    /// Creates a new `JpegBitReader` starting at offset `start_pos` in `data`.
423    ///
424    /// # Arguments
425    ///
426    /// - `&'a [u8]` - Full JPEG byte slice.
427    /// - `usize` - Start of entropy-coded scan segment.
428    ///
429    /// # Returns
430    ///
431    /// - `Self` - Initialized JPEG entropy reader.
432    #[must_use]
433    pub(crate) fn new(data: &'a [u8], start_pos: usize) -> Self {
434        Self {
435            data,
436            pos: start_pos,
437            bit_buf: 0,
438            bit_count: 0,
439        }
440    }
441
442    /// Reads the next stuffed entropy byte, collapsing `0xFF 0x00` to `0xFF` and halting cleanly on markers.
443    ///
444    /// # Arguments
445    ///
446    /// - `&Self` - Mutable JPEG bit reader.
447    ///
448    /// # Returns
449    ///
450    /// - `Result<u8, String>` - Next entropy data byte.
451    fn next_entropy_byte(&mut self) -> Result<u8, String> {
452        let Self { data, pos, .. } = self;
453        if *pos >= data.len() {
454            return Ok(0);
455        }
456        let byte_val: u8 = data[*pos];
457        *pos += 1;
458        if byte_val == 0xFF {
459            if *pos < data.len() {
460                let next_val: u8 = data[*pos];
461                if next_val == 0x00 {
462                    *pos += 1;
463                    return Ok(0xFF);
464                }
465                *pos -= 1;
466                return Ok(0);
467            }
468            return Ok(0);
469        }
470        Ok(byte_val)
471    }
472
473    /// Reads a single MSB-first bit from the entropy stream.
474    ///
475    /// # Arguments
476    ///
477    /// - `&Self` - Mutable JPEG bit reader.
478    ///
479    /// # Returns
480    ///
481    /// - `Result<u32, String>` - Next bit (`0` or `1`).
482    pub(crate) fn read_bit(&mut self) -> Result<u32, String> {
483        let Self {
484            bit_buf, bit_count, ..
485        } = self;
486        if *bit_count == 0 {
487            let next_byte: u8 = self.next_entropy_byte()?;
488            let Self {
489                bit_buf: buf_ref,
490                bit_count: cnt_ref,
491                ..
492            } = self;
493            *buf_ref = u32::from(next_byte) << 24;
494            *cnt_ref = 8;
495            let bit: u32 = (*buf_ref >> 31) & 1;
496            *buf_ref <<= 1;
497            *cnt_ref -= 1;
498            return Ok(bit);
499        }
500        let bit: u32 = (*bit_buf >> 31) & 1;
501        *bit_buf <<= 1;
502        *bit_count -= 1;
503        Ok(bit)
504    }
505
506    /// Reads `count` MSB-first bits as an unsigned integer.
507    ///
508    /// # Arguments
509    ///
510    /// - `&Self` - Mutable JPEG bit reader.
511    /// - `u8` - Number of bits to read (`0..=16`).
512    ///
513    /// # Returns
514    ///
515    /// - `Result<u32, String>` - Decoded bit field.
516    pub(crate) fn read_bits(&mut self, count: u8) -> Result<u32, String> {
517        let mut value: u32 = 0;
518        for _ in 0..count {
519            let bit: u32 = self.read_bit()?;
520            value = (value << 1) | bit;
521        }
522        Ok(value)
523    }
524
525    /// Reads a signed JPEG magnitude-coded value of `bits` length.
526    ///
527    /// # Arguments
528    ///
529    /// - `&Self` - Mutable JPEG bit reader.
530    /// - `u8` - Category bit count (`0..=15`).
531    ///
532    /// # Returns
533    ///
534    /// - `Result<i32, String>` - Sign-extended coefficient value.
535    pub(crate) fn receive_extend(&mut self, bits: u8) -> Result<i32, String> {
536        if bits == 0 {
537            return Ok(0);
538        }
539        let raw: i32 = self.read_bits(bits)? as i32;
540        let threshold: i32 = 1 << (bits - 1);
541        if raw < threshold {
542            Ok(raw + ((-1i32) << bits) + 1)
543        } else {
544            Ok(raw)
545        }
546    }
547
548    /// Resets the bit buffer and skips an optional JPEG restart marker (`0xFF 0xD0..=0xD7`).
549    ///
550    /// # Arguments
551    ///
552    /// - `&Self` - Mutable JPEG bit reader.
553    pub(crate) fn consume_restart_marker(&mut self) {
554        let Self {
555            data,
556            pos,
557            bit_buf,
558            bit_count,
559        } = self;
560        *bit_buf = 0;
561        *bit_count = 0;
562        while *pos < data.len() && data[*pos] == 0xFF {
563            if *pos + 1 < data.len() && (0xD0..=0xD7).contains(&data[*pos + 1]) {
564                *pos += 2;
565                break;
566            }
567            if *pos + 1 < data.len() && data[*pos + 1] == 0xFF {
568                *pos += 1;
569            } else {
570                break;
571            }
572        }
573    }
574}
575
576/// MSB-first JPEG entropy writer helpers for `JpegBitWriter`.
577impl JpegBitWriter {
578    /// Writes the lowest `bit_len` bits of `bits` in MSB-first order with `0xFF 0x00` stuffing.
579    ///
580    /// # Arguments
581    ///
582    /// - `&Self` - Mutable JPEG bit writer.
583    /// - `u32` - Source bit pattern.
584    /// - `u8` - Number of bits to write (`0..=16`).
585    pub(crate) fn write_bits(&mut self, bits: u32, bit_len: u8) {
586        if bit_len == 0 {
587            return;
588        }
589        let Self {
590            out,
591            bit_buf,
592            bit_count,
593        } = self;
594        let mask: u32 = (1u32 << bit_len) - 1;
595        *bit_buf = (*bit_buf << bit_len) | (bits & mask);
596        *bit_count += bit_len;
597        while *bit_count >= 8 {
598            *bit_count -= 8;
599            let byte_val: u8 = ((*bit_buf >> *bit_count) & 0xFF) as u8;
600            out.push(byte_val);
601            if byte_val == 0xFF {
602                out.push(0x00);
603            }
604        }
605    }
606
607    /// Pads any trailing partial byte with 1-bits and flushes it to `out`.
608    ///
609    /// # Arguments
610    ///
611    /// - `&Self` - Mutable JPEG bit writer.
612    pub(crate) fn flush_ones(&mut self) {
613        let Self { bit_count, .. } = self;
614        let rem: u8 = *bit_count;
615        if rem > 0 {
616            let pad: u8 = 8 - rem;
617            self.write_bits((1u32 << pad) - 1, pad);
618        }
619    }
620}