refactor(image-codecs): move format sniffers into format.rs

The DICOM, Cineon and IFF signature checks and the JPEG-LS marker walk
are what detect() and PrefixDetector use, so they now live beside them.
The codec modules call them from there. No behaviour change.

This lets a later change compile those codecs out while detection stays.
This commit is contained in:
hikari committed 2026-11-24 09:41:42 +01:00
1 parent 249a41bd93
commit 3e3a40993c
5 files changed
+88 -85

No files matched your search

+1 -6
View File
@@ -9,7 +9,7 @@
use std::collections::HashMap;
use crate::error::CodecError;
use crate::format::Format;
use crate::format::{Format, is_dicom};
use crate::image::{ChannelLayout, Image, SampleType};
use crate::options::Limits;
@@ -21,11 +21,6 @@ fn bad(msg: impl std::fmt::Display) -> CodecError {
CodecError::malformed(F, msg)
}
/// A DICOM file begins with a 128-byte preamble and the `DICM` magic.
pub(crate) fn is_dicom(b: &[u8]) -> bool {
b.get(128..132) == Some(b"DICM")
}
#[derive(Clone, Copy)]
struct Endian {
big: bool,
+1 -5
View File
@@ -27,6 +27,7 @@
use crate::Format;
use crate::error::CodecError;
use crate::fidelity::Plan;
use crate::format::is_cineon;
use crate::image::{ChannelLayout, DecodeWarning, Image, SampleType};
use crate::options::{DpxBits, EncodeOptions, Limits};
@@ -357,11 +358,6 @@ pub(crate) fn decode(bytes: &[u8], limits: &Limits) -> Result<Image, CodecError>
// 10-bit samples packed into each 32-bit word, lines on a word boundary — the same layout as
// DPX's 10-bit packing method A, so the unpacking and packing are shared.
/// The Cineon magic number (`802A5FD7` hex), big-endian.
pub(crate) fn is_cineon(b: &[u8]) -> bool {
b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7])
}
/// The EXIF orientation (1–8) for a Cineon header's orientation code (the same 0–7 order as DPX).
pub(crate) fn cineon_orientation(b: &[u8]) -> u16 {
let Some(code) = b.get(192).copied() else { return 1 };
+1 -6
View File
@@ -13,7 +13,7 @@
use crate::error::CodecError;
use crate::fidelity::Plan;
use crate::format::Format;
use crate::format::{Format, looks_like_iff};
use crate::image::{ChannelLayout, Image, SampleType};
use crate::options::Limits;
@@ -37,11 +37,6 @@ fn be16(b: &[u8], at: usize) -> Option<u16> {
Some(u16::from_be_bytes(s))
}
/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8.
pub(crate) fn looks_like_iff(b: &[u8]) -> bool {
b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM "))
}
/// Bitplanes of a "deep" ILBM: red, green and blue, 8 each, least significant bit first.
const DEEP_PLANES: u8 = 24;
+2 -63
View File
@@ -11,12 +11,11 @@
use crate::error::CodecError;
use crate::fidelity::Plan;
use crate::format::Format;
use crate::format::{Format, SOF55, looks_like_jpegls};
use crate::image::{ChannelLayout, Image, SampleType};
use crate::options::Limits;
const F: Format = Format::JpegLs;
const SOF55: u8 = 0xF7;
const LSE: u8 = 0xF8;
const RESET_DEFAULT: i32 = 64;
const MIN_C: i32 = -128;
@@ -32,67 +31,6 @@ fn bad(reason: impl std::fmt::Display) -> CodecError {
CodecError::malformed(F, reason)
}
/// 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<JpegFrame> {
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<JpegFrame> {
if *pos == 0 {
if !b.starts_with(&[0xFF, 0xD8]) {
return None;
}
*pos = 2;
}
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 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 Some(JpegFrame::Short(*pos + 4));
};
*pos += 2 + len;
}
}
}
}
/// 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.
#[derive(Clone, Copy)]
struct Params {
@@ -813,6 +751,7 @@ fn finish(frame: Option<Frame>, planes: Vec<Vec<u16>>, scans: usize) -> Result<I
#[cfg(test)]
mod tests {
use super::*;
use crate::format::{JpegFrame, jpeg_frame, jpeg_frame_from};
fn noise_u16(n: usize, seed: &mut u32, mask: u32) -> Vec<u16> {
(0..n)
+83 -5
View File
@@ -396,7 +396,6 @@ impl PrefixDetector {
/// 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),
@@ -418,7 +417,7 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
if b.starts_with(b"\x89PNG\r\n\x1a\n") {
return Some(Format::Png);
}
if crate::codecs::jpegls::looks_like_jpegls(b) {
if looks_like_jpegls(b) {
return Some(Format::JpegLs);
}
if b.starts_with(&[0xFF, 0xD8, 0xFF]) {
@@ -474,13 +473,13 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
if b.starts_with(b"SDPX") || b.starts_with(b"XPDS") {
return Some(Format::Dpx);
}
if crate::codecs::dpx::is_cineon(b) {
if is_cineon(b) {
return Some(Format::Cineon);
}
if crate::codecs::dicom::is_dicom(b) {
if is_dicom(b) {
return Some(Format::Dicom);
}
if crate::codecs::iff::looks_like_iff(b) {
if looks_like_iff(b) {
return Some(Format::Iff);
}
if b.starts_with(b"SIMPLE =") {
@@ -506,6 +505,85 @@ pub fn detect(bytes: &[u8]) -> Option<Format> {
None
}
/// The JPEG-LS frame marker.
pub(crate) const SOF55: u8 = 0xF7;
/// 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<JpegFrame> {
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<JpegFrame> {
if *pos == 0 {
if !b.starts_with(&[0xFF, 0xD8]) {
return None;
}
*pos = 2;
}
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 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 Some(JpegFrame::Short(*pos + 4));
};
*pos += 2 + len;
}
}
}
}
/// 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)
}
/// A DICOM file begins with a 128-byte preamble and the `DICM` magic.
pub(crate) fn is_dicom(b: &[u8]) -> bool {
b.get(128..132) == Some(b"DICM")
}
/// The Cineon magic number (`802A5FD7` hex), big-endian.
pub(crate) fn is_cineon(b: &[u8]) -> bool {
b.get(..4) == Some(&[0x80, 0x2A, 0x5F, 0xD7])
}
/// `FORM` + a bitmap type (`ILBM` interleaved, `PBM ` chunky) at offset 8.
pub(crate) fn looks_like_iff(b: &[u8]) -> bool {
b.get(0..4) == Some(b"FORM") && matches!(b.get(8..12), Some(b"ILBM" | b"PBM "))
}
/// The major brand and complete compatible brands in a leading ISO-BMFF `ftyp` box.
///
/// Pass at most the bytes the caller wants to inspect. A missing box or incomplete major