Merge pull request #2425 from dotCooCoo/fix/file-formats-jpeg-ls

file-formats: register JPEG-LS and tell it from JPEG
This commit is contained in:
Dylan M. Taylor
2026-11-19 17:46:57 -05:00
committed by GitHub
5 changed files with 161 additions and 8 deletions
Generated
+1
View File
@@ -2089,6 +2089,7 @@ dependencies = [
"craft-dxf",
"craft-eps",
"craft-file-formats",
"craft-image-codecs",
"craft-pdf 0.1.0",
"craft-raster-codecs",
"craft-svg",
+64 -5
View File
@@ -39,6 +39,8 @@ pub enum Format {
Cineon,
Dicom,
Iff,
/// JPEG-LS (ITU-T T.87). Its files start with the same `FF D8 FF` bytes as JPEG files.
JpegLs,
Ase,
Psd,
Affinity,
@@ -108,7 +110,7 @@ const fn availability(feature: bool, supported: bool) -> Availability {
impl Format {
/// Every known format, including formats whose reader or writer is not enabled in this build.
pub const ALL: [Format; 56] = [
pub const ALL: [Format; 57] = [
Self::Pdf,
Self::Eps,
Self::PostScript,
@@ -139,6 +141,7 @@ impl Format {
Self::Cineon,
Self::Dicom,
Self::Iff,
Self::JpegLs,
Self::Ase,
Self::Psd,
Self::Affinity,
@@ -200,6 +203,7 @@ impl Format {
Self::Cineon => &["cin"],
Self::Dicom => &["dcm", "dicom", "dc3"],
Self::Iff => &["iff", "lbm", "ilbm"],
Self::JpegLs => &["jls"],
Self::Ase => &["ase"],
Self::Psd => &["psd", "psb", "psdt"],
Self::Affinity => &["afdesign", "afphoto", "afpub", "af"],
@@ -270,6 +274,7 @@ impl Format {
Self::Cineon => "image/x-cineon",
Self::Dicom => "application/dicom",
Self::Iff => "image/ilbm",
Self::JpegLs => "image/jls",
Self::Ase => "application/x-adobe-swatch-exchange",
Self::Psd => "image/vnd.adobe.photoshop",
Self::Affinity => "application/x-affinity",
@@ -327,6 +332,7 @@ impl Format {
Self::Cineon => Codec::Cineon,
Self::Dicom => Codec::Dicom,
Self::Iff => Codec::Iff,
Self::JpegLs => Codec::JpegLs,
_ => return None,
})
}
@@ -381,7 +387,8 @@ impl Format {
| Self::Fits
| Self::Dpx
| Self::Cineon
| Self::Iff => capability(raster, true, true, false, false),
| Self::Iff
| Self::JpegLs => capability(raster, true, true, false, false),
Self::Pdf => capability(cfg!(feature = "pdf"), true, true, false, false),
Self::Eps | Self::PostScript | Self::Illustrator => capability(cfg!(feature = "pdf"), true, false, false, false),
Self::Svg | Self::Svgz => capability(cfg!(feature = "svg"), true, false, false, false),
@@ -483,7 +490,7 @@ pub fn detect(name: &str, bytes: &[u8]) -> Option<Format> {
if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("af")) {
return Some(Format::Affinity);
}
if let Some(raster) = raster_signature(bytes) {
if let Some(raster) = raster_signature(name, bytes) {
return Some(raster);
}
if bytes.starts_with(b"silhouette04;") || bytes.starts_with(b"silhouette05;") {
@@ -598,13 +605,18 @@ fn dxf_ascii_prefix(bytes: &[u8]) -> bool {
matches!((lines.next(), lines.next(), lines.next(), lines.next()), (Some("0"), Some("SECTION"), Some("2"), Some(section)) if matches!(section, "HEADER" | "CLASSES" | "TABLES" | "BLOCKS" | "ENTITIES" | "OBJECTS"))
}
fn raster_signature(bytes: &[u8]) -> Option<Format> {
fn raster_signature(name: &str, bytes: &[u8]) -> Option<Format> {
let head = bytes.get(..16).unwrap_or(bytes);
if head.starts_with(b"\x89PNG\r\n\x1a\n") {
return Some(Format::Png);
}
if head.starts_with(b"\xff\xd8\xff") {
return Some(Format::Jpeg);
return Some(match jpeg_frame(bytes) {
JpegFrame::Ls => Format::JpegLs,
JpegFrame::Other => Format::Jpeg,
JpegFrame::Unknown if extension(name).is_some_and(|ext| ext.eq_ignore_ascii_case("jls")) => Format::JpegLs,
JpegFrame::Unknown => Format::Jpeg,
});
}
if head.starts_with(b"BM") {
return Some(Format::Bmp);
@@ -620,3 +632,50 @@ fn raster_signature(bytes: &[u8]) -> Option<Format> {
}
None
}
/// What the marker segments after a JPEG start-of-image marker lead to.
#[derive(Debug, PartialEq, Eq)]
enum JpegFrame {
/// An SOF55 frame header (`FF F7`, ITU-T T.87): JPEG-LS.
Ls,
/// Another frame header, a scan header, an end-of-image marker, or a byte that is not a
/// marker where one should be.
Other,
/// The bytes, or the probe's first 1 MiB, end before a frame or scan header.
Unknown,
}
/// Walk the marker segments from the start-of-image marker to the first frame or scan header.
/// Only the first 1 MiB is read, and each step moves forward at least one byte. The walk follows
/// `jpeg_frame_from` in craft-image-codecs, which a build without the `raster-codecs` feature does
/// not link.
fn jpeg_frame(bytes: &[u8]) -> JpegFrame {
const LIMIT: usize = 1 << 20;
let bytes = bytes.get(..bytes.len().min(LIMIT)).unwrap_or(bytes);
let mut pos = 2;
loop {
let (Some(&prefix), Some(&marker)) = (bytes.get(pos), bytes.get(pos + 1)) else {
return if bytes.get(pos).is_none_or(|&prefix| prefix == 0xFF) { JpegFrame::Unknown } else { JpegFrame::Other };
};
if prefix != 0xFF {
return JpegFrame::Other;
}
match marker {
0xF7 => return JpegFrame::Ls,
// `FF 00` is a stuffed zero, not a marker.
0x00 | 0xDA | 0xD9 => return JpegFrame::Other,
// A DRI segment (`FF DD`) may come before an SOF55 frame header, so it is skipped
// by its length below.
0xC0..=0xCF | 0xDB | 0xDC | 0xDE | 0xDF => return JpegFrame::Other,
// A fill byte, or a marker without a length.
0xFF => pos += 1,
0x01 | 0xD0..=0xD7 => pos += 2,
_ => {
let Some(length) = bytes.get(pos + 2..pos + 4).map(|length| usize::from(u16::from_be_bytes([length[0], length[1]]))) else {
return JpegFrame::Unknown;
};
pos += 2 + length;
}
}
}
}
+66
View File
@@ -57,6 +57,72 @@ fn bounded_probes_prefer_signatures_and_resolve_extensions() {
assert_eq!(super::detect("unknown", b""), None);
}
#[test]
fn jpeg_ls_is_told_from_jpeg_and_resolves_its_extension() {
assert_eq!(super::from_extension("JLS"), Some(Format::JpegLs));
assert_eq!(Format::JpegLs.mime_type(), Some("image/jls"));
assert_eq!(super::detect("scan.jls", b""), Some(Format::JpegLs));
// SOI followed by an SOF55 frame header.
assert_eq!(super::detect("scan.jpg", b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0"), Some(Format::JpegLs));
assert_eq!(super::detect("photo.jls", b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0"), Some(Format::Jpeg));
// An APP0 segment, a fill byte and a DRI segment before the SOF55 frame header.
let with_segments = b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0";
assert_eq!(super::detect("scan.jpg", with_segments), Some(Format::JpegLs));
assert_eq!(super::detect("", with_segments), Some(Format::JpegLs));
// Bytes that end before any frame header: the name decides.
assert_eq!(super::detect("scan.jls", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::JpegLs));
assert_eq!(super::detect("photo.jpg", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
assert_eq!(super::detect("", b"\xff\xd8\xff\xe0\0\x10"), Some(Format::Jpeg));
}
#[test]
fn jpeg_marker_walk_reads_only_the_first_mebibyte() {
let mut bytes = vec![0xFF; (1 << 20) + 64];
bytes[1] = 0xD8;
let len = bytes.len();
bytes[len - 2] = 0xF7;
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::Jpeg));
assert_eq!(super::detect("scan.jls", &bytes), Some(Format::JpegLs));
bytes[1 << 19] = 0xF7;
assert_eq!(super::detect("scan.jpg", &bytes), Some(Format::JpegLs));
}
#[cfg(feature = "raster-codecs")]
#[test]
fn jpeg_marker_walk_matches_the_codec_detection() {
let cases: [&[u8]; 6] = [
b"\xff\xd8\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
b"\xff\xd8\xff\xe0\0\x04\0\0\xff\xff\xdd\0\x04\0\0\xff\xf7\0\x0b\x08\0\x01\0\x01\x01\x01\x11\0",
b"\xff\xd8\xff\xe0\0\x10JFIF\0\x01\x01\0\0\x01\0\x01\0\0\xff\xc0",
b"\xff\xd8\xff\xd0\xff\x01\xff\xf7\0\x0b",
b"\xff\xd8\xff\xe0\0\x04\0\0\x12\x34",
b"\xff\xd8\xff\xda\0\x08",
];
for bytes in cases {
let expected = match craft_image_codecs::detect(bytes) {
Some(craft_image_codecs::Format::JpegLs) => Format::JpegLs,
_ => Format::Jpeg,
};
assert_eq!(super::detect("", bytes), Some(expected), "{bytes:02x?}");
}
}
#[test]
fn jpeg_ls_capabilities_follow_the_codec() {
#[cfg(feature = "raster-codecs")]
{
assert_eq!(Format::JpegLs.raster_codec(), Some(craft_image_codecs::Format::JpegLs));
assert_eq!(Format::JpegLs.extensions(), craft_image_codecs::Format::JpegLs.extensions());
assert_eq!(Format::JpegLs.capabilities().read, Availability::Available);
assert_eq!(Format::JpegLs.capabilities().write, Availability::Available);
}
#[cfg(not(feature = "raster-codecs"))]
{
assert_eq!(Format::JpegLs.capabilities().read, Availability::BuildDisabled);
assert_eq!(Format::JpegLs.capabilities().write, Availability::BuildDisabled);
}
}
#[test]
fn registered_mime_and_preferred_extensions_remain_distinct() {
assert_eq!(Format::Svg.mime_type(), Format::Svgz.mime_type());
+3
View File
@@ -18,5 +18,8 @@ kurbo = { workspace = true }
thiserror = { workspace = true }
vectorcraft-geom = { workspace = true }
[dev-dependencies]
craft-image-codecs = { workspace = true }
[lints]
workspace = true
+27 -3
View File
@@ -89,14 +89,15 @@ pub const CAPABILITIES: &[Capability] = &[
detected_formats: &[
craft_file_formats::Format::Png,
craft_file_formats::Format::Jpeg,
craft_file_formats::Format::JpegLs,
craft_file_formats::Format::Bmp,
craft_file_formats::Format::Gif,
craft_file_formats::Format::Tiff,
craft_file_formats::Format::WebP,
],
extensions: &["png", "jpg", "jpeg", "bmp", "gif", "tif", "tiff", "webp"],
extensions: &["png", "jpg", "jpeg", "jls", "bmp", "gif", "tif", "tiff", "webp"],
write_extensions: &["png", "jpg", "jpeg"],
mime_types: &["image/png", "image/jpeg", "image/bmp", "image/gif", "image/tiff", "image/webp"],
mime_types: &["image/png", "image/jpeg", "image/jls", "image/bmp", "image/gif", "image/tiff", "image/webp"],
raster: true,
vector: false,
},
@@ -197,7 +198,7 @@ pub fn format_for(name: &str, bytes: &[u8]) -> Option<ImportFormat> {
F::Pdf => Some(ImportFormat::Pdf),
F::Illustrator if bytes.starts_with(b"%PDF-") => Some(ImportFormat::Pdf),
F::Eps | F::PostScript | F::Illustrator => Some(ImportFormat::Eps),
F::Png | F::Jpeg | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
F::Png | F::Jpeg | F::JpegLs | F::Bmp | F::Gif | F::Tiff | F::WebP => Some(ImportFormat::Raster),
_ => None,
}
}
@@ -402,4 +403,27 @@ mod format_tests {
let bytes = b"%PDF-1.7\n/AIPrivateData";
assert_eq!(format_for("illustration.ai", bytes), Some(ImportFormat::Pdf));
}
#[test]
fn jpeg_ls_is_routed_to_the_raster_reader() {
use craft_image_codecs::{ChannelLayout, EncodeOptions, Format, Image, encode};
let gray: Vec<u8> = (0..6).map(|value| value * 40).collect();
let Ok(image) = Image::from_u8(3, 2, ChannelLayout::Gray, gray.clone()) else {
panic!("a 3 by 2 gray image");
};
let Ok(bytes) = encode(&image, Format::JpegLs, &EncodeOptions::default()) else {
panic!("JPEG-LS encodes");
};
for name in ["scan.jls", "scan.jpg", "scan"] {
assert_eq!(format_for(name, &bytes), Some(ImportFormat::Raster), "{name}");
let Ok(Imported::Raster(raster)) = import(name, &bytes, Limits::default()) else {
panic!("{name} imports as a raster image");
};
assert_eq!((raster.width, raster.height), (3, 2));
let red: Vec<u8> = raster.rgba.as_chunks::<4>().0.iter().map(|pixel| pixel[0]).collect();
assert_eq!(red, gray, "{name}");
}
assert!(supported_formats(ImportFormat::Raster).contains(&craft_file_formats::Format::JpegLs));
assert!(supported_extensions().contains(&"jls"));
}
}