diff --git a/codex-rs/tui/src/sidebar_image.rs b/codex-rs/tui/src/sidebar_image.rs index 0c40400cc0..4fa83fc615 100644 --- a/codex-rs/tui/src/sidebar_image.rs +++ b/codex-rs/tui/src/sidebar_image.rs @@ -6,7 +6,9 @@ use std::sync::Arc; use color_eyre::eyre::OptionExt; use color_eyre::eyre::Result; use image::DynamicImage; +use image::ImageError; use image::ImageFormat; +use image::error::LimitErrorKind; use ratatui::buffer::Buffer; use ratatui::layout::Rect; use ratatui::style::Stylize; @@ -18,6 +20,14 @@ use crate::transcript_image::ImagePlacement; use crate::transcript_image::TranscriptImage; use crate::transcript_image::terminal_cell_size; +mod jpeg; + +#[cfg(test)] +#[path = "sidebar_image_tests.rs"] +mod tests; + +const MAX_PREVIEW_EDGE: u32 = 768; + #[derive(Debug)] pub(crate) enum DocumentContent { Text(String), @@ -61,16 +71,28 @@ impl SidebarImage { .ok_or_eyre("Unsupported image format")?; let mut limits = image::Limits::default(); limits.max_alloc = Some(32 * 1024 * 1024); - let image = crate::image_decode::decode_oriented(reader, limits)?; - let (width, height) = (image.width(), image.height()); + let (image, (width, height)) = + match crate::image_decode::decode_oriented(reader, limits.clone()) { + Ok(image) => { + let size = (image.width(), image.height()); + (image, size) + } + Err(ImageError::Limits(error)) + if format == ImageFormat::Jpeg + && error.kind() == LimitErrorKind::InsufficientMemory => + { + jpeg::decode_scaled(bytes, limits).ok_or(ImageError::Limits(error))? + } + Err(error) => return Err(error.into()), + }; Ok(Self { label: format!( "{} · {width} × {height}", format.extensions_str()[0].to_ascii_uppercase() ), source_size: (width, height), - raster: if width > 768 || height > 768 { - image.thumbnail(768, 768) + raster: if image.width() > MAX_PREVIEW_EDGE || image.height() > MAX_PREVIEW_EDGE { + image.thumbnail(MAX_PREVIEW_EDGE, MAX_PREVIEW_EDGE) } else { image }, diff --git a/codex-rs/tui/src/sidebar_image/jpeg.rs b/codex-rs/tui/src/sidebar_image/jpeg.rs new file mode 100644 index 0000000000..e4da203714 --- /dev/null +++ b/codex-rs/tui/src/sidebar_image/jpeg.rs @@ -0,0 +1,301 @@ +//! One-eighth-scale fallback for sidebar JPEGs above the pixel budget. +//! Each DC coefficient gives the average of an 8×8 block (T.81 F.2). +//! Keep only these coefficients, including progressive refinements, +//! and let the image crate resize their color samples to fit the sidebar. + +mod entropy; + +use entropy::Bits; +use entropy::Huffman; +use entropy::marker; +use image::DynamicImage; +use image::GenericImageView; +use image::Limits; +use image::Rgb; +use image::metadata::Orientation; + +use super::MAX_PREVIEW_EDGE; + +fn word(bytes: &mut &[u8]) -> Option { + Some(u16::from_be_bytes(bytes.split_off(..2)?.try_into().ok()?)) +} + +/// Return None to retain the original allocation error when a preview is unavailable. +pub(super) fn decode_scaled( + mut bytes: &[u8], + mut limits: Limits, +) -> Option<(DynamicImage, (u32, u32))> { + bytes = bytes.strip_prefix(&[0xff, 0xd8])?; + let mut decoder = Decoder::default(); + let mut orientation = None; + let mut adobe_transform = None; + let mut in_headers = true; + loop { + let tag = marker(&mut bytes)?; + if tag == 0xd9 { + break; + } + let len = usize::from(word(&mut bytes)?.checked_sub(2)?); + let mut body = bytes.split_off(..len)?; + match tag { + 0xc0..=0xc2 if decoder.planes.is_empty() => { + decoder.read_frame(body, tag, &mut limits)? + } + 0xdb => { + while let Some(&id) = body.split_off_first() { + // Read only the DC divisor of each quantization table. + let q = match id >> 4 { + 0 => u16::from(body.split_off(..64)?[0]), + 1 => word(&mut body.split_off(..128)?)?, + _ => return None, + }; + *decoder.divisors.get_mut(usize::from(id & 15))? = q; + } + } + 0xc4 => { + while let Some(&id) = body.split_off_first() { + let slots = decoder.huffman.get_mut(usize::from(id >> 4))?; + *slots.get_mut(usize::from(id & 15))? = Huffman::parse(&mut body)?; + } + } + 0xdd => decoder.restart_interval = usize::from(word(&mut body)?), + 0xe1 if in_headers && body.starts_with(b"Exif\0\0") => { + orientation = Orientation::from_exif_chunk(&body[6..]); + } + 0xee if in_headers && body.starts_with(b"Adobe") => { + adobe_transform = Some(*body.get(11)?) + } + 0xe0..=0xef | 0xfe => {} + 0xda => { + in_headers = false; + bytes = decoder.read_scan(body, bytes)?; + if decoder.planes.iter().all(|p| p.low_bit == Some(0)) { + break; + } + } + _ => return None, + } + } + if decoder.planes.is_empty() || decoder.planes.iter().any(|p| p.low_bit.is_none()) { + return None; + } + decoder.direct_rgb = match adobe_transform { + Some(0) => true, + Some(1) => false, + None => decoder.planes.iter().map(|p| p.id).eq(*b"RGB"), + _ => return None, + }; + let (w, h) = decoder.preview; + let mut size = decoder.size; + let mut image = DynamicImage::ImageRgb8(image::imageops::thumbnail(&decoder, w, h)); + drop(decoder); + let orientation = orientation.unwrap_or(Orientation::NoTransforms); + image.apply_orientation(orientation); + // EXIF orientations 5–8 exchange the axes. + if orientation.to_exif() >= 5 { + size = (size.1, size.0); + } + Some((image, size)) +} + +#[derive(Default)] +struct Decoder<'a> { + divisors: [u16; 4], + huffman: [[Huffman<'a>; 4]; 2], // DC and AC tables + restart_interval: usize, + size: (u32, u32), + preview: (u32, u32), + progressive: bool, + direct_rgb: bool, + max_h: usize, + max_v: usize, + planes: Vec, +} + +#[derive(Default)] +struct Plane { + id: u8, + // Horizontal and vertical sampling factors in the frame. + h: usize, + v: usize, + divisor_slot: usize, + divisor: u16, + low_bit: Option, // Lowest received DC bit, or None before the first scan. + stride: usize, + dc: Vec, +} + +impl Decoder<'_> { + fn read_frame(&mut self, bytes: &[u8], tag: u8, limits: &mut Limits) -> Option<()> { + let mut fields = bytes.strip_prefix(&[8])?; + let height = u32::from(word(&mut fields)?); + let width = u32::from(word(&mut fields)?); + let [count @ (1 | 3), components @ ..] = fields else { + return None; + }; + if width == 0 || height == 0 || components.len() != 3 * usize::from(*count) { + return None; + } + let longest = width.max(height); + let fit = |n: u32| { + n.div_ceil(8) + .min(((n * MAX_PREVIEW_EDGE + longest / 2) / longest).max(1)) + }; + self.size = (width, height); + self.preview = (fit(width), fit(height)); + self.progressive = tag == 0xc2; + for &[id, sampling, slot] in components.as_chunks::<3>().0 { + let h = usize::from(sampling >> 4); + let v = usize::from(sampling & 15); + if !(1..=4).contains(&h) || !(1..=4).contains(&v) || slot >= 4 { + return None; + } + self.max_h = self.max_h.max(h); + self.max_v = self.max_v.max(v); + self.planes.push(Plane { + id, + h, + v, + divisor_slot: usize::from(slot), + ..Default::default() + }); + } + // The thumbnail coexists first with the padded planes, then with + // its rotated copy. Source dimensions are bounded by u16. + let (cols, rows) = self.grid(/*h*/ 1, /*v*/ 1); + let blocks: usize = self.planes.iter().map(|p| p.h * p.v).sum(); + let storage = (cols * rows * blocks * size_of::()) as u64; + let pixels = u64::from(self.preview.0 * self.preview.1 * 3); + limits.reserve(pixels + storage.max(pixels)).ok()?; + for p in &mut self.planes { + p.stride = cols * p.h; + let n = p.stride * rows * p.v; + p.dc.try_reserve_exact(n).ok()?; + p.dc.resize(n, 0); + } + Some(()) + } + + // Interleaved scans have one minimum coded unit (MCU) per group of + // max_h × max_v blocks. Single-component scans use unpadded blocks. + fn grid(&self, h: usize, v: usize) -> (usize, usize) { + ( + (self.size.0 as usize * h).div_ceil(self.max_h * 8), + (self.size.1 as usize * v).div_ceil(self.max_v * 8), + ) + } + + fn read_scan<'a>(&mut self, mut header: &[u8], bytes: &'a [u8]) -> Option<&'a [u8]> { + let count = usize::from(*header.split_off_first()?); + let selectors = header.split_off(..2 * count)?; + let [start, end, approximation] = *header else { + return None; + }; + if self.progressive && count == 1 && start > 0 && start <= end && end <= 63 { + // Skip AC data up to the next marker, ignoring stuffing and restarts. + let next = bytes + .windows(2) + .position(|w| w[0] == 0xff && !matches!(w[1], 0 | 0xd0..=0xd7 | 0xff))?; + return Some(&bytes[next..]); + } + let high = approximation >> 4; + let low = approximation & 15; + if start != 0 + || (self.progressive && (end != 0 || low > 13)) + || (!self.progressive && (end != 63 || approximation != 0)) + || count == 0 + || count > self.planes.len() + { + return None; + } + let mut order = Vec::new(); + let mut blocks_per_mcu = 0; + let mut grid_factors = (1, 1); + for &[id, slots] in selectors.as_chunks::<2>().0 { + let i = self.planes.iter().position(|p| p.id == id)?; + let plane = &mut self.planes[i]; + // Bind the divisor on the first scan of this component. + if high == 0 && plane.low_bit.is_none() { + plane.divisor = self.divisors[plane.divisor_slot]; + if plane.divisor == 0 { + return None; + } + } else if high != low + 1 || plane.low_bit != Some(high) { + return None; + } + plane.low_bit = Some(low); + let dc = self.huffman[0].get(usize::from(slots >> 4))?; + let ac = self.huffman[1].get(usize::from(slots & 15))?; + let mut sampling = (plane.h, plane.v); + if count == 1 { + // One block per MCU. The sampling factors instead scale the grid. + grid_factors = sampling; + sampling = (1, 1); + } + blocks_per_mcu += sampling.0 * sampling.1; + order.push((i, sampling, dc, ac)); + } + if blocks_per_mcu > 10 { + return None; + } + let (cols, rows) = self.grid(grid_factors.0, grid_factors.1); + let mut predictors = [0_i16; 3]; + let mut bits = Bits::new(bytes); + for mcu in 0..rows * cols { + let (x, y) = (mcu % cols, mcu / cols); + if self.restart_interval > 0 && mcu > 0 && mcu.is_multiple_of(self.restart_interval) { + bits.restart(mcu / self.restart_interval - 1)?; + predictors.fill(0); + } + for &(i, (h, v), dc, ac) in &order { + let plane = &mut self.planes[i]; + for row in y * v..(y + 1) * v { + let pos = row * plane.stride + x * h; + for value in plane.dc.get_mut(pos..pos + h)? { + if high == 0 { + predictors[i] = predictors[i].checked_add(dc.difference(&mut bits)?)?; + *value = i16::try_from(i32::from(predictors[i]) << low).ok()?; + } else { + *value |= bits.read(/*count*/ 1)? << low; + } + if !self.progressive { + ac.skip_ac(&mut bits)?; + } + } + } + } + } + Some(bits.bytes) + } +} + +impl GenericImageView for Decoder<'_> { + type Pixel = Rgb; + + fn dimensions(&self) -> (u32, u32) { + (self.size.0.div_ceil(8), self.size.1.div_ceil(8)) + } + + fn get_pixel(&self, x: u32, y: u32) -> Rgb { + let sample = |p: &Plane| { + let index = (y as usize * p.v / self.max_v) * p.stride + x as usize * p.h / self.max_h; + let dc = i32::from(p.dc[index]) * i32::from(p.divisor); + (((dc + 4) >> 3) + 128).clamp(0, 255) as u8 + }; + let [p1, p2, p3] = &self.planes[..] else { + return Rgb([sample(&self.planes[0]); 3]); + }; + let color = [sample(p1), sample(p2), sample(p3)]; + if self.direct_rgb { + return Rgb(color); + } + // JFIF full-range YCbCr to RGB. + let [luma, cb, cr] = color.map(f32::from); + let (cb, cr) = (cb - 128., cr - 128.); + Rgb([ + (luma + 1.402 * cr).round() as u8, + (luma - 0.344_136 * cb - 0.714_136 * cr).round() as u8, + (luma + 1.772 * cb).round() as u8, + ]) + } +} diff --git a/codex-rs/tui/src/sidebar_image/jpeg/entropy.rs b/codex-rs/tui/src/sidebar_image/jpeg/entropy.rs new file mode 100644 index 0000000000..07637bf3d9 --- /dev/null +++ b/codex-rs/tui/src/sidebar_image/jpeg/entropy.rs @@ -0,0 +1,117 @@ +//! Entropy data for JPEG block averages (T.81, Annexes C, F and G). +//! Huffman tables borrow the input. Reading only the bytes a code needs +//! keeps the stream at the marker when a restart interval ends. + +pub(super) fn marker(bytes: &mut &[u8]) -> Option { + *bytes = bytes.strip_prefix(&[0xff])?; + while let Some(rest) = bytes.strip_prefix(&[0xff]) { + *bytes = rest; + } + bytes.split_off_first().copied() +} + +#[derive(Default)] +pub(super) struct Bits<'a> { + pub(super) bytes: &'a [u8], + pending: u32, + left: u8, +} + +impl<'a> Bits<'a> { + pub(super) fn new(bytes: &'a [u8]) -> Self { + Self { + bytes, + ..Default::default() + } + } + + pub(super) fn restart(&mut self, index: usize) -> Option<()> { + self.left = 0; + (marker(&mut self.bytes)? == 0xd0 + (index % 8) as u8).then_some(()) + } + + // At most eleven bits for an 8-bit DC difference. + pub(super) fn read(&mut self, count: u8) -> Option { + while self.left < count { + let byte = *self.bytes.split_off_first()?; + if byte == 0xff { + self.bytes = self.bytes.strip_prefix(&[0])?; + } + self.pending = (self.pending << 8) | u32::from(byte); + self.left += 8; + } + self.left -= count; + Some((self.pending >> self.left) as i16 & ((1 << count) - 1)) + } +} + +#[derive(Clone, Copy, Default)] +pub(super) struct Huffman<'a> { + counts: &'a [u8], + symbols: &'a [u8], +} + +impl<'a> Huffman<'a> { + pub(super) fn parse(bytes: &mut &'a [u8]) -> Option { + let counts = bytes.split_off(..16)?; + let mut total = 0; + let mut free = 1; + for &count in counts { + total += usize::from(count); + free = free * 2 - i32::from(count); + // The all-ones code must remain free for padding. + if free <= 0 || total > 256 { + return None; + } + } + let symbols = bytes.split_off(..total)?; + Some(Self { counts, symbols }) + } + + fn symbol(&self, bits: &mut Bits<'_>) -> Option { + let mut code = 0; + let mut offset = 0; + for &count in self.counts { + let count = usize::from(count); + code = 2 * code + bits.read(/*count*/ 1)? as usize; + if code < count { + return self.symbols.get(offset + code).copied(); + } + // Longer codes start after those assigned at this length. + code -= count; + offset += count; + } + None + } + + pub(super) fn difference(&self, bits: &mut Bits<'_>) -> Option { + let size = self.symbol(bits)?; + if size > 11 { + return None; + } + let value = bits.read(size)?; + let range = 1 << size; + Some(if value < range / 2 { + value + 1 - range + } else { + value + }) + } + + pub(super) fn skip_ac(&self, bits: &mut Bits<'_>) -> Option<()> { + let mut remaining = 63_u8; + while remaining != 0 { + let symbol = self.symbol(bits)?; + if symbol == 0 { + break; + } + let size = symbol & 15; + if size > 10 || (size == 0 && symbol != 0xf0) { + return None; + } + remaining = remaining.checked_sub((symbol >> 4) + 1)?; + bits.read(size)?; + } + Some(()) + } +} diff --git a/codex-rs/tui/src/sidebar_image_tests.rs b/codex-rs/tui/src/sidebar_image_tests.rs new file mode 100644 index 0000000000..15c38964cc --- /dev/null +++ b/codex-rs/tui/src/sidebar_image_tests.rs @@ -0,0 +1,51 @@ +#![cfg(test)] + +use super::SidebarImage; +use image::Rgb; +use image::RgbImage; +use image::codecs::jpeg::JpegEncoder; +use pretty_assertions::assert_eq; + +#[test] +fn sequential_jpeg_above_raster_limit_opens_at_sidebar_size() { + // Alternating columns exercise AC decoding. Each block averages 64. + let source = RgbImage::from_fn(6544, 1721, |x, _| { + Rgb([if x.is_multiple_of(2) { 48 } else { 80 }; 3]) + }); + let mut bytes = Vec::new(); + JpegEncoder::new(&mut bytes).encode_image(&source).unwrap(); + drop(source); + let preview = SidebarImage::decode(&bytes).unwrap(); + insta::assert_snapshot!(preview.label, @"JPG · 6544 × 1721"); + assert_eq!(preview.source_size, (6544, 1721)); + let expected = RgbImage::from_pixel(768, 202, Rgb([64; 3])); + assert_eq!(preview.raster.into_rgb8(), expected); +} + +#[test] +fn split_progressive_preview_requires_intact_scans_and_enough_memory() { + // A 33×49 fixture with Cr, Y, Cb DC scans, AC scans, then a DC refinement. + // Restarts every two MCUs. Its four solid regions align with 16×16 MCUs. + let path = + codex_utils_cargo_bin::find_resource!("tests/fixtures/progressive-squares.jpg").unwrap(); + let mut bytes = std::fs::read(path).unwrap(); + let decode = |input: &[u8], budget| { + let mut limits = image::Limits::default(); + limits.max_alloc = Some(budget); + super::jpeg::decode_scaled(input, limits) + }; + let required = 3 * 4 * 6 * 2 + 5 * 7 * 3; // padded 4:2:0 DC blocks + RGB pixels + assert!(decode(&bytes, required - 1).is_none()); + let top = [[79, 83, 208], [184, 53, 87]]; + let bottom = [[232, 160, 50], [49, 173, 89]]; + let expected = RgbImage::from_fn(7, 5, |x, y| { + let [left, right] = if y < 2 { top } else { bottom }; + Rgb(if x < 3 { left } else { right }) + }); + assert_eq!(decode(&bytes, required), Some((expected.into(), (49, 33)))); + + let rst0 = bytes.windows(2).position(|w| w == [0xff, 0xd0]).unwrap(); + assert!(decode(&bytes[..rst0 - 1], required).is_none()); + bytes[rst0 + 1] = 0xd1; + assert!(decode(&bytes, required).is_none()); +} diff --git a/codex-rs/tui/tests/fixtures/progressive-squares.jpg b/codex-rs/tui/tests/fixtures/progressive-squares.jpg new file mode 100644 index 0000000000..d292f250be Binary files /dev/null and b/codex-rs/tui/tests/fixtures/progressive-squares.jpg differ