diff --git a/crates/image-codecs/src/codecs/jpegls.rs b/crates/image-codecs/src/codecs/jpegls.rs index a5dff1015..aa6579349 100644 --- a/crates/image-codecs/src/codecs/jpegls.rs +++ b/crates/image-codecs/src/codecs/jpegls.rs @@ -32,26 +32,65 @@ fn bad(reason: impl std::fmt::Display) -> CodecError { CodecError::malformed(F, reason) } -/// Whether `b` is a JPEG-LS file: an SOI followed by marker segments up to an SOF55 frame header. -pub(crate) fn looks_like_jpegls(b: &[u8]) -> bool { - if !b.starts_with(&[0xFF, 0xD8]) { - return false; +/// What the marker segments after a JPEG SOI lead to. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) enum JpegFrame { + /// An SOF55 frame header: JPEG-LS. + Ls, + /// Another frame header, a scan header, an EOI, or a byte that is not a marker where one + /// should be. + Other, + /// The bytes end before a frame or scan header. The next step reads the bytes up to this + /// length. + Short(usize), +} + +/// Walks the marker segments of `b` from its SOI up to the first frame or scan header. `None` +/// when `b` does not start with an SOI. Each step moves forward at least one byte, so the walk +/// takes at most `b.len()` steps and reaches the frame header after any number of segments. +pub(crate) fn jpeg_frame(b: &[u8]) -> Option { + jpeg_frame_from(b, &mut 0) +} + +/// [`jpeg_frame`], started at `*pos`. A `*pos` of 0 starts at the SOI. Any other value is the +/// offset of the marker where an earlier walk of a shorter prefix of the same file stopped, and the +/// walk does not read the bytes before it. The walk leaves `*pos` at the marker it stopped at, so +/// walking longer and longer prefixes of one file this way reads each marker segment once. +pub(crate) fn jpeg_frame_from(b: &[u8], pos: &mut usize) -> Option { + if *pos == 0 { + if !b.starts_with(&[0xFF, 0xD8]) { + return None; + } + *pos = 2; } - let mut pos = 2; - for _ in 0..64 { - let (Some(&0xFF), Some(&marker)) = (b.get(pos), b.get(pos + 1)) else { return false }; + loop { + let (Some(&prefix), Some(&marker)) = (b.get(*pos), b.get(*pos + 1)) else { + return Some(if b.get(*pos).is_none_or(|&p| p == 0xFF) { JpegFrame::Short(*pos + 2) } else { JpegFrame::Other }); + }; + if prefix != 0xFF { + return Some(JpegFrame::Other); + } match marker { - SOF55 => return true, - 0xDA | 0xD9 => return false, - 0xC0..=0xCF | 0xDB..=0xDF => return false, - 0x01 | 0xD0..=0xD7 | 0xFF => pos += if marker == 0xFF { 1 } else { 2 }, + SOF55 => return Some(JpegFrame::Ls), + // `FF 00` is a stuffed zero, not a marker. + 0x00 | 0xDA | 0xD9 => return Some(JpegFrame::Other), + // A DRI segment (`0xDD`) may precede an SOF55 frame header, so it takes the + // length-prefixed path below. + 0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return Some(JpegFrame::Other), + 0x01 | 0xD0..=0xD7 | 0xFF => *pos += if marker == 0xFF { 1 } else { 2 }, _ => { - let Some(len) = b.get(pos + 2..pos + 4).map(|l| usize::from(u16::from_be_bytes([l[0], l[1]]))) else { return false }; - pos += 2 + len; + let Some(len) = b.get(*pos + 2..*pos + 4).map(|l| usize::from(u16::from_be_bytes([l[0], l[1]]))) else { + return Some(JpegFrame::Short(*pos + 4)); + }; + *pos += 2 + len; } } } - false +} + +/// Whether `b` is a JPEG-LS file: an SOI followed by marker segments up to an SOF55 frame header. +pub(crate) fn looks_like_jpegls(b: &[u8]) -> bool { + jpeg_frame(b) == Some(JpegFrame::Ls) } /// The coding parameters of one scan, derived as T.87 section C.2 specifies. @@ -618,6 +657,7 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { let mut preset = [0i32; 5]; let mut planes: Vec> = Vec::new(); let mut scans_done = 0; + let mut restart_interval = 0usize; loop { // Find the next marker. while b.get(pos) != Some(&0xFF) { @@ -668,8 +708,21 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { return Err(CodecError::unsupported(F, "mapping tables and colour transforms (LSE)")); } } + // DRI: a 2-, 3- or 4-byte interval in lines (T.87 C.2.5). An interval of 0 turns + // restart markers off. The interval in effect at each scan header applies to that scan. + 0xDD => { + if !(2..=4).contains(&seg.len()) { + return Err(bad("bad restart interval segment")); + } + restart_interval = seg.iter().fold(0, |ri, &v| (ri << 8) | usize::from(v)); + } 0xDA => { let f = frame.as_ref().ok_or_else(|| bad("a scan before the frame header"))?; + // A scan of one component has restart markers only when the interval is shorter + // than the frame's height. + if restart_interval != 0 && restart_interval < f.height { + return Err(CodecError::unsupported(F, "a restart interval")); + } let ns = usize::from(*seg.first().ok_or_else(|| bad("empty scan header"))?); if seg.len() < 1 + 2 * ns + 3 || ns != 1 { return Err(CodecError::unsupported(F, "interleaved scans (ILV 1 and 2)")); @@ -705,6 +758,11 @@ pub(crate) fn decode(b: &[u8], limits: &Limits) -> Result { samples.try_reserve_exact(f.width * f.height).map_err(|_| bad("pixel buffer is too large"))?; samples.resize(f.width * f.height, 0u16); decode_scan(&b[start..end], f.width, f.height, ¶ms, &mut samples)?; + // A restart marker comes only between two intervals, so none follows a scan that + // fits in one. Fill bytes (`0xFF`) may come before the marker. + if restart_interval != 0 && b[end..].iter().find(|&&v| v != 0xFF).is_some_and(|m| (0xD0..=0xD7).contains(m)) { + return Err(bad("a restart marker after the last restart interval")); + } planes[idx] = samples; scans_done += 1; pos = end; @@ -847,6 +905,25 @@ mod tests { assert!(!looks_like_jpegls(&[0xFF, 0xD8])); } + #[test] + fn a_resumed_walk_starts_at_the_marker_it_stopped_at() { + // SOI, a comment with two bytes of text, then an SOF55 frame header. + let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xF7, 0, 11]; + let mut pos = 0; + assert_eq!(jpeg_frame_from(&file[..5], &mut pos), Some(JpegFrame::Short(6))); + assert_eq!(pos, 2); + assert_eq!(jpeg_frame_from(&file[..9], &mut pos), Some(JpegFrame::Short(10))); + assert_eq!(pos, 8); + // The resumed walk does not read the bytes before `pos` again: with them cleared, it still + // reaches the frame header, while a walk from the start finds no SOI. + let mut cleared = file; + cleared[..8].fill(0); + assert_eq!(jpeg_frame_from(&cleared, &mut pos), Some(JpegFrame::Ls)); + assert_eq!(pos, 8); + assert_eq!(jpeg_frame(&cleared), None); + assert_eq!(jpeg_frame(&file), Some(JpegFrame::Ls)); + } + #[test] fn interleaved_scans_and_tables_are_unsupported() { let img = image(8, 4, ChannelLayout::Rgb, false, 2); diff --git a/crates/image-codecs/src/format.rs b/crates/image-codecs/src/format.rs index b3ec649e3..f43dae32c 100644 --- a/crates/image-codecs/src/format.rs +++ b/crates/image-codecs/src/format.rs @@ -354,8 +354,65 @@ pub fn caps(format: Format) -> FormatCaps { } } +/// What [`detect_prefix`] makes of the first bytes of a file. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum Detection { + /// The bytes identify this format, as [`detect`] reports it. + Format(Format), + /// The bytes start with a JPEG SOI and end before the frame header that tells JPEG from + /// JPEG-LS. Read the file up to at least this many bytes and call [`detect_prefix`] or + /// [`PrefixDetector::detect`] again. + NeedBytes(usize), + /// The bytes match no format. + Unknown, +} + +/// Identify a format from the first bytes of a file, which may be all of it or only its start. +/// A JPEG and a JPEG-LS file both start with an SOI, and only the frame header after their marker +/// segments tells them apart. When `bytes` ends before that header, the answer is +/// [`Detection::NeedBytes`]; every other answer is the one [`detect`] gives. +/// +/// Each call walks the marker segments from the SOI. To read more of a file after each +/// [`Detection::NeedBytes`], use a [`PrefixDetector`], which starts each walk where the previous +/// one stopped. +pub fn detect_prefix(bytes: &[u8]) -> Detection { + PrefixDetector::new().detect(bytes) +} + +/// [`detect_prefix`] for a file read in steps. The detector keeps the offset of the JPEG marker +/// where its last walk stopped, so it reads each marker segment once, however many steps the file +/// is read in. +#[derive(Debug, Clone, Default)] +pub struct PrefixDetector { + jpeg_pos: usize, +} + +impl PrefixDetector { + /// A detector that has seen no bytes. + pub fn new() -> Self { + Self::default() + } + + /// The answer [`detect_prefix`] gives for `bytes`. The `bytes` of each call must start with + /// the `bytes` of the previous call on this detector. + pub fn detect(&mut self, bytes: &[u8]) -> Detection { + use crate::codecs::jpegls::{JpegFrame, jpeg_frame_from}; + match jpeg_frame_from(bytes, &mut self.jpeg_pos) { + Some(JpegFrame::Short(len)) => Detection::NeedBytes(len), + Some(JpegFrame::Ls) => Detection::Format(Format::JpegLs), + // The walk found no SOF55 frame header, so `detect` answers JPEG for these bytes. + Some(JpegFrame::Other) if bytes.starts_with(&[0xFF, 0xD8, 0xFF]) => Detection::Format(Format::Jpeg), + Some(JpegFrame::Other) | None => detect(bytes).map_or(Detection::Unknown, Detection::Format), + } + } +} + /// Identify a format from its leading bytes (magic numbers). TGA has no /// magic and is recognized last, by header plausibility. +/// +/// JPEG-LS is told from JPEG by the frame header that follows the marker segments, so `bytes` +/// must reach that header; a buffer that ends before it is reported as [`Format::Jpeg`]. Use +/// [`detect_prefix`] on a buffer that may hold only the start of a file. pub fn detect(bytes: &[u8]) -> Option { let b = bytes; if b.starts_with(b"\x89PNG\r\n\x1a\n") { diff --git a/crates/image-codecs/src/lib.rs b/crates/image-codecs/src/lib.rs index a68ce52fe..fb7f64de1 100644 --- a/crates/image-codecs/src/lib.rs +++ b/crates/image-codecs/src/lib.rs @@ -57,7 +57,7 @@ pub use crate::codecs::tiff_ifd::{ExtraSampleKind, InkSet, TiffInfo, TiffPage, T pub use crate::error::CodecError; pub use crate::exif_color::{EXIF_COLOR_SPACE_SRGB, exif_color_space}; pub use crate::fidelity::{FidelityWarning, fidelity_warnings, fidelity_warnings_with}; -pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Format, FormatCaps, caps, detect, from_extension}; +pub use crate::format::{ASYMMETRIC_EXCEPTIONS, Detection, Format, FormatCaps, PrefixDetector, caps, detect, detect_prefix, from_extension}; pub use crate::image::{ ChannelLayout, CryptomatteBuffer, CryptomatteLayer, DecodeWarning, DeepChannel, DeepImage, ExrChannelInfo, ExrPartInfo, ExtraSample, Image, MAX_EXTRA_SAMPLES, Metadata, SampleType, convert_samples, diff --git a/crates/image-codecs/tests/it/detect_caps.rs b/crates/image-codecs/tests/it/detect_caps.rs index bbe518df6..76e8bc584 100644 --- a/crates/image-codecs/tests/it/detect_caps.rs +++ b/crates/image-codecs/tests/it/detect_caps.rs @@ -260,6 +260,196 @@ fn detect_magic_jpeg_ls() { assert!(decode_as(Format::JpegLs, &[0xFF, 0xD8, 0xFF, 0xF7]).is_err()); } +/// `file` with `count` marker segments of `body` bytes each inserted right after its SOI. +fn with_segments(file: &[u8], marker: u8, count: usize, body: usize) -> Vec { + let mut out = file[..2].to_vec(); + for i in 0..count { + out.extend_from_slice(&[0xFF, marker]); + out.extend_from_slice(&u16::try_from(body + 2).unwrap().to_be_bytes()); + out.extend((0..body).map(|j| (i + j) as u8)); + } + out.extend_from_slice(&file[2..]); + out +} + +fn jpeg_ls_file() -> (Image, Vec) { + let img = Image::from_u8(5, 3, ChannelLayout::Gray, (0..15).collect()).unwrap(); + let bytes = encode(&img, Format::JpegLs, &EncodeOptions::default()).unwrap(); + (img, bytes) +} + +/// Grows a prefix of `bytes` as a [`PrefixDetector`] asks, starting from `first` bytes, and checks +/// each answer against [`detect_prefix`]. +fn detect_by_prefix(bytes: &[u8], first: usize) -> Detection { + let mut detector = PrefixDetector::new(); + let mut len = first.min(bytes.len()); + loop { + let answer = detector.detect(&bytes[..len]); + assert_eq!(answer, detect_prefix(&bytes[..len]), "after {len} bytes"); + match answer { + Detection::NeedBytes(more) if len < bytes.len() => { + assert!(more > len, "{more} bytes asked for after {len}"); + len = more.min(bytes.len()); + } + answer => return answer, + } + } +} + +#[test] +fn jpeg_ls_after_a_long_comment_needs_the_frame_header() { + let (img, plain) = jpeg_ls_file(); + let bytes = with_segments(&plain, 0xFE, 1, 100); + assert_eq!(detect(&bytes), Some(Format::JpegLs)); + assert_eq!(decode(&bytes).unwrap().data(), img.data()); + // The first 64 bytes end inside the comment: `detect` says JPEG, `detect_prefix` asks for + // the bytes up to the next marker. + assert_eq!(detect(&bytes[..64]), Some(Format::Jpeg)); + assert_eq!(detect_prefix(&bytes[..64]), Detection::NeedBytes(2 + 2 + 102 + 2)); + assert_eq!(detect_by_prefix(&bytes, 64), Detection::Format(Format::JpegLs)); + assert_eq!(detect_prefix(&bytes), Detection::Format(Format::JpegLs)); +} + +#[test] +fn jpeg_ls_after_many_segments_is_still_jpeg_ls() { + // An ICC profile can span 255 APP2 segments. + let (img, plain) = jpeg_ls_file(); + let bytes = with_segments(&plain, 0xE2, 255, 14); + assert_eq!(detect(&bytes), Some(Format::JpegLs)); + assert_eq!(decode(&bytes).unwrap().data(), img.data()); + assert_eq!(detect_by_prefix(&bytes, 64), Detection::Format(Format::JpegLs)); + // A plain JPEG with as many segments before its baseline frame header stays JPEG. + let jpeg = with_segments(&[0xFF, 0xD8, 0xFF, 0xC0, 0, 11, 8, 0, 1, 0, 1, 1, 1, 0x11, 0], 0xE2, 255, 14); + assert_eq!(detect(&jpeg), Some(Format::Jpeg)); + assert_eq!(detect_by_prefix(&jpeg, 64), Detection::Format(Format::Jpeg)); +} + +#[test] +fn a_cut_off_jpeg_asks_for_more_bytes() { + let (_, plain) = jpeg_ls_file(); + let bytes = with_segments(&plain, 0xFE, 1, 100); + // Cut inside the comment, inside its length field, and right after the SOI. + assert_eq!(detect_prefix(&bytes[..50]), Detection::NeedBytes(108)); + assert_eq!(detect_prefix(&bytes[..5]), Detection::NeedBytes(6)); + assert_eq!(detect_prefix(&bytes[..3]), Detection::NeedBytes(4)); + assert_eq!(detect_prefix(&[0xFF, 0xD8]), Detection::NeedBytes(4)); + assert_eq!(detect(&bytes[..50]), Some(Format::Jpeg)); + assert!(decode_as(Format::JpegLs, &bytes[..50]).is_err()); + // A byte that is not a marker where one should be ends the walk: no frame header follows. + assert_eq!(detect_prefix(&[0xFF, 0xD8, 0xFF, 0xFE, 0, 2, 0x12, 0x34]), Detection::Format(Format::Jpeg)); + // Formats other than JPEG answer as `detect` does. + assert_eq!(detect_prefix(b"\x89PNG\r\n\x1a\n\0\0"), Detection::Format(Format::Png)); + assert_eq!(detect_prefix(&[0u8; 64]), Detection::Unknown); + assert_eq!(detect_prefix(&[]), Detection::Unknown); +} + +#[test] +fn a_restart_interval_before_the_frame_header_is_jpeg_ls() { + // A DRI segment may come before the frame header. An interval of 0 turns restarts off. + let (img, plain) = jpeg_ls_file(); + let mut bytes = plain[..2].to_vec(); + bytes.extend_from_slice(&[0xFF, 0xDD, 0, 4, 0, 0]); + bytes.extend_from_slice(&plain[2..]); + assert_eq!(detect(&bytes), Some(Format::JpegLs)); + assert_eq!(detect_by_prefix(&bytes, 4), Detection::Format(Format::JpegLs)); + assert_eq!(decode(&bytes).unwrap().data(), img.data()); + assert_eq!(decode_as(Format::JpegLs, &bytes).unwrap().data(), img.data()); + // A file that sets a restart interval is JPEG-LS, and its restart markers are not read. + bytes[7] = 1; + assert_eq!(detect(&bytes), Some(Format::JpegLs)); + assert!(matches!(decode(&bytes), Err(CodecError::Unsupported { .. }))); + // A 3- or 4-byte interval of 0 also turns restarts off. A segment with fewer than 2 interval + // bytes or more than 4 is malformed. + for (size, ok) in [(0, false), (1, false), (2, true), (3, true), (4, true), (5, false)] { + let mut bytes = plain[..2].to_vec(); + bytes.extend_from_slice(&[0xFF, 0xDD, 0, 2 + size as u8]); + bytes.extend(std::iter::repeat_n(0, size)); + bytes.extend_from_slice(&plain[2..]); + assert_eq!(detect(&bytes), Some(Format::JpegLs)); + assert_eq!(decode(&bytes).is_ok(), ok, "{size} interval bytes"); + } +} + +#[test] +fn the_restart_interval_in_effect_at_the_scan_decides_decoding() { + // The 5x3 file's frame header ends at byte 15, where its scan header starts. + let (img, plain) = jpeg_ls_file(); + assert_eq!(plain[2..4], [0xFF, 0xF7]); + assert_eq!(plain[15..17], [0xFF, 0xDA]); + let with_dri = |intervals: &[u16]| { + let mut bytes = plain[..15].to_vec(); + for interval in intervals { + bytes.extend_from_slice(&[0xFF, 0xDD, 0, 4]); + bytes.extend_from_slice(&interval.to_be_bytes()); + } + bytes.extend_from_slice(&plain[15..]); + bytes + }; + // A later interval of 0 turns restarts off again. + assert_eq!(decode(&with_dri(&[1, 0])).unwrap().data(), img.data()); + // An interval of at least the scan's 3 lines puts the whole scan in one interval, so the scan + // has no restart marker. + assert_eq!(decode(&with_dri(&[3])).unwrap().data(), img.data()); + assert_eq!(decode(&with_dri(&[u16::MAX])).unwrap().data(), img.data()); + // A shorter interval needs restart markers in the scan. + assert!(matches!(decode(&with_dri(&[2])), Err(CodecError::Unsupported { .. }))); + assert!(matches!(decode(&with_dri(&[0, 2])), Err(CodecError::Unsupported { .. }))); +} + +#[test] +fn a_restart_marker_after_a_scan_of_one_interval_is_an_error() { + // With an interval of 3 lines the 5x3 scan is one interval, which no restart marker follows. + let (img, plain) = jpeg_ls_file(); + assert_eq!(plain[plain.len() - 2..], [0xFF, 0xD9]); + let mut bytes = plain[..15].to_vec(); + bytes.extend_from_slice(&[0xFF, 0xDD, 0, 4, 0, 3]); + bytes.extend_from_slice(&plain[15..]); + assert_eq!(decode(&bytes).unwrap().data(), img.data()); + let eoi = bytes.len() - 2; + let mut marked = bytes.clone(); + marked.splice(eoi..eoi, [0xFF, 0xD0]); + assert!(decode(&marked).is_err()); + // Fill bytes before the restart marker do not hide it. + bytes.splice(eoi..eoi, [0xFF, 0xFF, 0xFF, 0xD3]); + assert!(decode(&bytes).is_err()); +} + +#[test] +fn a_stuffed_zero_where_a_marker_should_be_is_jpeg() { + // `FF 00` is not a marker, so the walk ends there without asking for a length field. + assert_eq!(detect_prefix(&[0xFF, 0xD8, 0xFF, 0x00]), Detection::Format(Format::Jpeg)); + assert_eq!(detect_prefix(&[0xFF, 0xD8, 0xFF, 0xFE, 0, 2, 0xFF, 0x00]), Detection::Format(Format::Jpeg)); +} + +#[test] +fn a_detector_that_found_a_jpeg_frame_does_not_walk_again() { + // SOI, a comment with two bytes of text, then a baseline frame header. + let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xC0, 0, 11]; + let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file), Detection::Format(Format::Jpeg)); + // With an SOF55 marker where the comment marker was, a walk from the SOI finds JPEG-LS. The + // detector starts at the baseline frame header it stopped at and still answers JPEG. + let mut changed = file; + changed[3] = 0xF7; + assert_eq!(detect_prefix(&changed), Detection::Format(Format::JpegLs)); + assert_eq!(detector.detect(&changed), Detection::Format(Format::Jpeg)); +} + +#[test] +fn a_detector_keeps_its_place_between_calls() { + // SOI, a comment with two bytes of text, then an SOF55 frame header. + let file = [0xFF, 0xD8, 0xFF, 0xFE, 0, 4, 1, 2, 0xFF, 0xF7, 0, 11]; + let mut detector = PrefixDetector::new(); + assert_eq!(detector.detect(&file[..9]), Detection::NeedBytes(10)); + // The next call starts at the frame header's marker and does not read the bytes before it + // again: with them cleared, the detector still finds JPEG-LS, while a walk from the start + // finds no SOI. + let mut cleared = file; + cleared[..8].fill(0); + assert_ne!(detect_prefix(&cleared), Detection::Format(Format::JpegLs)); + assert_eq!(detector.detect(&cleared), Detection::Format(Format::JpegLs)); +} + #[cfg(feature = "sunraster")] #[test] fn detect_magic_sun_raster() {