diff --git a/crates/gif/src/frames.rs b/crates/gif/src/frames.rs index 12ae37dda..5d9d1326a 100644 --- a/crates/gif/src/frames.rs +++ b/crates/gif/src/frames.rs @@ -7,7 +7,7 @@ //! decoding then stops at [`FrameLimits::max_frames`] frames or [`FrameLimits::max_bytes`] of kept //! pictures, or at the first damaged frame after the first, and [`Animation::stop`] says which. -use std::io::Cursor; +use std::io::{self, BufReader, Cursor, Read, Seek, SeekFrom}; use image::codecs::gif::GifDecoder; use image::{AnimationDecoder, ImageDecoder}; @@ -96,7 +96,9 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result limits.max_frames { Some(true) } else if info.complete { @@ -118,7 +120,8 @@ pub fn read_frames(bytes: &[u8], limits: &FrameLimits) -> Result Result { + bytes: Cursor<&'a [u8]>, + text_controls: Vec, +} + +impl Read for DecoderInput<'_> { + fn read(&mut self, output: &mut [u8]) -> io::Result { + let start = usize::try_from(self.bytes.position()).unwrap_or(usize::MAX); + let count = self.bytes.read(output)?; + if count == 0 { + return Ok(0); + } + let end = start + count; + let first = self.text_controls.partition_point(|&offset| offset + 4 <= start); + for &offset in self.text_controls[first..].iter().take_while(|&&offset| offset < end) { + output[offset.saturating_sub(start)..(offset + 4).min(end) - start].fill(0); + } + Ok(count) + } +} + +impl Seek for DecoderInput<'_> { + fn seek(&mut self, position: SeekFrom) -> io::Result { + self.bytes.seek(position) + } +} + /// Reads the optional ICC application extension without decoding frame pixels. As in the image /// decoder, a malformed optional profile is ignored and returned as `None`. pub fn icc_profile(bytes: &[u8]) -> Option> { @@ -218,6 +250,52 @@ mod tests { a.frames.iter().map(|f| (f.rgba[0], f.delay_ms)).collect() } + #[test] + fn plain_text_control_does_not_change_the_decoded_images() { + let mut bytes = Vec::new(); + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &[255, 0, 0, 0, 0, 255]).unwrap(); + for (index, delay, transparent) in [(0, 23, Some(0)), (1, 7, None)] { + let frame = gif::Frame { + width: 2, + height: 2, + delay, + transparent, + dispose: gif::DisposalMethod::Previous, + buffer: vec![index; 4].into(), + ..gif::Frame::default() + }; + encoder.write_frame(&frame).unwrap(); + } + } + let first_image = crate::scan(&bytes, 1).unwrap().frames[0].offset; + let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0]; + bytes.splice(first_image..first_image, text); + + let animation = read_frames(&bytes, &FrameLimits::default()).unwrap(); + assert_eq!(animation.frames.len(), 2); + let first = &animation.frames[0]; + assert_eq!((&first.rgba[..4], first.delay_ms), (&[255, 0, 0, 255][..], 0)); + let second = &animation.frames[1]; + assert_eq!((&second.rgba[..4], second.delay_ms), (&[0, 0, 255, 255][..], 70)); + } + + #[test] + fn text_control_can_span_decoder_reads() { + let bytes: Vec = (1..=16).collect(); + let mut input = DecoderInput { bytes: Cursor::new(&bytes), text_controls: vec![3, 10] }; + let mut prefix = [0; 5]; + input.read_exact(&mut prefix).unwrap(); + assert_eq!(prefix, [1, 2, 3, 0, 0]); + let mut tail = Vec::new(); + input.read_to_end(&mut tail).unwrap(); + assert_eq!(tail, [0, 0, 8, 9, 10, 0, 0, 0, 0, 15, 16]); + input.seek(SeekFrom::Start(6)).unwrap(); + let mut around = [0; 4]; + input.read_exact(&mut around).unwrap(); + assert_eq!(around, [0, 8, 9, 10]); + } + #[test] fn every_frame_with_its_delay() { let a = read_frames(&gif(&[(10, 5), (200, 10), (10, 0)]), &FrameLimits::default()).unwrap(); diff --git a/crates/gif/src/lib.rs b/crates/gif/src/lib.rs index db9e830ab..6d42f9c36 100644 --- a/crates/gif/src/lib.rs +++ b/crates/gif/src/lib.rs @@ -107,6 +107,12 @@ fn skip_sub_blocks(b: &[u8], mut at: usize) -> Option { /// `None` when `bytes` is not a GIF or ends inside its Logical Screen Descriptor. A file that /// breaks off later gives what was read, with [`Info::complete`] false. pub fn scan(bytes: &[u8], max_frames: usize) -> Option { + scan_with_text_controls(bytes, max_frames, |_| {}) +} + +// Report the control payloads that the image decoder would carry past a text block +// to an image without a control of its own. +fn scan_with_text_controls(bytes: &[u8], max_frames: usize, mut text_control: impl FnMut(usize)) -> Option { let b = bytes; if !sniff(b) { return None; @@ -116,8 +122,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { b.get(12)?; let mut info = Info { width, height, global_table: packed & 0x80 != 0, frames: Vec::new(), complete: false, loop_count: None }; let mut at = 13 + table_len(packed); - // What the last Graphic Control Extension said, for the next image. + // What the last Graphic Control Extension said, for the next rendering block. let (mut delay_cs, mut transparent, mut disposal) = (0u16, None, 0u8); + let mut control_offset = None; + let mut text_control_offset = None; // Each step either finishes the walk or moves `at` forward, so this ends with the file. let mut step = || -> Option { match *b.get(at)? { @@ -132,6 +140,8 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { delay_cs = u16_at(b, body + 2)?; transparent = (flags & 0x01 != 0).then_some(*b.get(body + 4)?); disposal = (flags >> 2) & 7; + control_offset = Some(body + 1); + text_control_offset = None; } // Application Extension NETSCAPE2.0 (or ANIMEXTS1.0): sub-block 3, 1, loop count. if label == 0xFF @@ -141,6 +151,13 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { info.loop_count = u16_at(b, body + 14); } at = skip_sub_blocks(b, body)?; + // GIF89a §12: a Plain Text Extension consumes the pending graphic control. + if label == 0x01 { + (delay_cs, transparent, disposal) = (0, None, 0); + if let Some(offset) = control_offset.take() { + text_control_offset = Some(offset); + } + } Some(true) } // Image Descriptor: separator, left, top, width, height, packed fields, then the @@ -162,6 +179,10 @@ pub fn scan(bytes: &[u8], max_frames: usize) -> Option { local_table: packed & 0x80 != 0, }); (delay_cs, transparent, disposal) = (0, None, 0); + control_offset = None; + if let Some(offset) = text_control_offset.take() { + text_control(offset); + } at = skip_sub_blocks(b, (at + 10).checked_add(table_len(packed))?.checked_add(1)?)?; Some(true) } diff --git a/crates/gif/src/tests.rs b/crates/gif/src/tests.rs index 6a776eb50..b2d5eaf2f 100644 --- a/crates/gif/src/tests.rs +++ b/crates/gif/src/tests.rs @@ -75,6 +75,42 @@ fn the_first_frames_table_and_transparent_entry() { assert_eq!(palette(&gif(&l, Some(9), None)), Some((l.to_vec(), None))); } +#[test] +fn graphic_control_ends_at_plain_text() { + let mut bytes = Vec::new(); + let colors = [0, 0, 0, 255, 0, 0]; + { + let mut encoder = gif::Encoder::new(&mut bytes, 2, 2, &colors).unwrap(); + let frame = gif::Frame { + width: 2, + height: 2, + delay: 23, + transparent: Some(1), + dispose: gif::DisposalMethod::Previous, + buffer: std::borrow::Cow::Borrowed(&[0; 4]), + ..gif::Frame::default() + }; + encoder.write_frame(&frame).unwrap(); + } + let image_start = scan(&bytes, 1).unwrap().frames[0].offset; + // A comment does not consume the control that precedes it. + let comment = [0x21, 0xfe, 1, b'x', 0]; + bytes.splice(image_start..image_start, comment); + let before = scan(&bytes, 1).unwrap(); + let first = before.frames[0]; + assert_eq!((first.delay_cs, first.transparent, first.disposal), (23, Some(1), 3)); + assert_eq!(palette(&bytes).unwrap().1, Some(1)); + + // A 2×2 plain text grid with 1×1 cells and one character consumes it. + let text = [0x21, 0x01, 12, 0, 0, 0, 0, 2, 0, 2, 0, 1, 1, 1, 0, 1, b'X', 0]; + bytes.splice(first.offset..first.offset, text); + let after = scan(&bytes, 1).unwrap(); + assert!(after.complete); + let first = after.frames[0]; + assert_eq!((first.delay_cs, first.transparent, first.disposal), (0, None, 0)); + assert_eq!(palette(&bytes).unwrap(), (vec![[0, 0, 0], [255, 0, 0]], None)); +} + #[test] fn no_table_or_not_a_gif_is_none() { assert_eq!(palette(&gif(&[], None, None)), None, "no table at all");