mirror of
https://github.com/storytold/lightcraft.git
synced 2026-11-28 17:29:31 +01:00
Merge pull request #4307 from storytold/codex/shared-jpeg-inspection-consumer
Use shared JPEG marker and MPF handling
This commit is contained in:
3 files changed
+46
-235
No files matched your search
@@ -2,12 +2,14 @@
|
||||
//! thumbnail, colour-space hint). Full EXIF parsing lives in `lightcraft-meta`.
|
||||
|
||||
/// Byte-order aware reader over a TIFF-structured blob.
|
||||
#[cfg(test)]
|
||||
#[derive(Clone, Copy)]
|
||||
pub(crate) struct Tiff<'a> {
|
||||
pub data: &'a [u8],
|
||||
le: bool,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
#[derive(Clone, Copy, Debug)]
|
||||
pub(crate) struct Entry {
|
||||
pub tag: u16,
|
||||
@@ -17,6 +19,7 @@ pub(crate) struct Entry {
|
||||
pub value_pos: usize,
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
impl<'a> Tiff<'a> {
|
||||
pub fn new(data: &'a [u8]) -> Option<Tiff<'a>> {
|
||||
let le = match data.get(0..2)? {
|
||||
|
||||
@@ -16,33 +16,6 @@ pub use craft_gainmap::{GainImage, GainMapMeta, GainMapOptions, ISO_URN, apply,
|
||||
use crate::encode::{EncodeImage, EncodeMeta, Samples, jpeg_app_segments, xmp_segment};
|
||||
use crate::{ChromaSubsampling, Error, Format, Result, jpeg};
|
||||
|
||||
/// Offsets within the MPF payload (from "MPF\0"): the endian field, then the index IFD (3 tags).
|
||||
const MPF_ENTRIES_FROM_ENDIAN: usize = 8 + 2 + 3 * 12 + 4;
|
||||
|
||||
/// The primary image's MPF payload, entry sizes and offset to be patched once the file exists.
|
||||
fn mpf_placeholder() -> Vec<u8> {
|
||||
let mut p = b"MPF\0MM".to_vec();
|
||||
p.extend_from_slice(&42u16.to_be_bytes());
|
||||
p.extend_from_slice(&8u32.to_be_bytes()); // first IFD
|
||||
p.extend_from_slice(&3u16.to_be_bytes());
|
||||
let tag = |p: &mut Vec<u8>, tag: u16, ty: u16, count: u32, value: [u8; 4]| {
|
||||
p.extend_from_slice(&tag.to_be_bytes());
|
||||
p.extend_from_slice(&ty.to_be_bytes());
|
||||
p.extend_from_slice(&count.to_be_bytes());
|
||||
p.extend_from_slice(&value);
|
||||
};
|
||||
tag(&mut p, 0xB000, 7, 4, *b"0100"); // MPFVersion
|
||||
tag(&mut p, 0xB001, 4, 1, 2u32.to_be_bytes()); // NumberOfImages
|
||||
tag(&mut p, 0xB002, 7, 32, (MPF_ENTRIES_FROM_ENDIAN as u32).to_be_bytes()); // MPEntry
|
||||
p.extend_from_slice(&0u32.to_be_bytes()); // no next IFD
|
||||
// entry 0: baseline primary (0x030000) flagged as the representative image (bit 29)
|
||||
for attr in [0x2003_0000u32, jpeg::MPF_GAIN_MAP] {
|
||||
p.extend_from_slice(&attr.to_be_bytes());
|
||||
p.extend_from_slice(&[0; 12]); // size, offset, two dependent-image entries
|
||||
}
|
||||
p
|
||||
}
|
||||
|
||||
/// Encode a gain map JPEG: `base` (8-bit SDR, 3 or 4 channels, colour-managed by `meta.icc`) and
|
||||
/// its gain map, both at `quality`. `meta.xmp` is kept, with the gain map container added.
|
||||
pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, quality: u8, sub: ChromaSubsampling, meta: &EncodeMeta) -> Result<Vec<u8>> {
|
||||
@@ -87,28 +60,13 @@ pub fn encode_jpeg(base: &EncodeImage, gain: &GainImage, m: &GainMapMeta, qualit
|
||||
let xmp = craft_gainmap::primary_xmp(meta.xmp, gain_jpeg.len());
|
||||
let mut segs = jpeg_app_segments(&EncodeMeta { xmp: Some(&xmp), ..*meta })?;
|
||||
segs.push((0xE2, craft_gainmap::primary_iso_marker()));
|
||||
segs.push((0xE2, mpf_placeholder()));
|
||||
let sub = match sub {
|
||||
ChromaSubsampling::S444 => craft_jpeg::ChromaSubsampling::S444,
|
||||
ChromaSubsampling::S422 => craft_jpeg::ChromaSubsampling::S420,
|
||||
ChromaSubsampling::S420 => craft_jpeg::ChromaSubsampling::S420,
|
||||
};
|
||||
let mut primary =
|
||||
craft_jpeg::encode_baseline(data, w, h, base.channels as usize, quality, sub, &segs).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
|
||||
// patch the MPF index: sizes, and the gain map's offset from the MPF endian field
|
||||
let markers = jpeg::parse_markers(&primary).ok_or_else(|| Error::Encode("gain map JPEG: primary image unreadable".into()))?;
|
||||
let endian = markers.mpf.as_ref().map(|m| m.0).ok_or_else(|| Error::Encode("gain map JPEG: MPF segment missing".into()))?;
|
||||
let entries = endian + MPF_ENTRIES_FROM_ENDIAN;
|
||||
let (plen, glen) = (primary.len(), gain_jpeg.len());
|
||||
let fields = [(entries + 4, plen), (entries + 8, 0), (entries + 20, glen), (entries + 24, plen - endian)];
|
||||
for (at, v) in fields {
|
||||
let v = u32::try_from(v).map_err(|_| Error::Encode("gain map JPEG larger than 4 GiB".into()))?;
|
||||
let slot = primary.get_mut(at..at + 4).ok_or_else(|| Error::Encode("gain map JPEG: truncated MPF segment".into()))?;
|
||||
slot.copy_from_slice(&v.to_be_bytes());
|
||||
}
|
||||
primary.extend_from_slice(&gain_jpeg);
|
||||
Ok(primary)
|
||||
let primary = craft_jpeg::encode_baseline(data, w, h, base.channels as usize, quality, sub, &segs).map_err(|e| Error::Encode(e.to_string()))?;
|
||||
craft_metadata::mpf::write(&primary, &[(jpeg::MPF_GAIN_MAP, &gain_jpeg)]).map_err(|error| Error::Encode(format!("gain map JPEG: {error}")))
|
||||
}
|
||||
|
||||
/// The gain map of a gain map JPEG.
|
||||
|
||||
+41
-191
@@ -6,166 +6,10 @@ use crate::{DecodeOptions, Decoded, Error, Format, Result, Thumbnail, ThumbnailS
|
||||
|
||||
const F: Format = Format::Jpeg;
|
||||
|
||||
/// What we learn from walking the marker segments before the first scan.
|
||||
#[derive(Default, Debug)]
|
||||
pub(crate) struct Markers {
|
||||
pub width: u32,
|
||||
pub height: u32,
|
||||
pub components: u8,
|
||||
pub precision: u8,
|
||||
/// SOFn marker byte (0xC0 baseline, 0xC1 extended, 0xC2 progressive, …).
|
||||
pub sof: u8,
|
||||
/// Number of components in the first scan (< `components` for non-interleaved sequential files).
|
||||
pub first_scan_components: u8,
|
||||
/// Number of APP1 segments: capped before the allocating decoders walk them again.
|
||||
pub app1: u32,
|
||||
pub exif: Option<Vec<u8>>,
|
||||
/// Offset of the EXIF TIFF header within the file.
|
||||
pub exif_offset: usize,
|
||||
pub xmp: Option<String>,
|
||||
pub icc: Option<Vec<u8>>,
|
||||
/// An ICC_PROFILE APP2 segment was present but its sequence was invalid.
|
||||
pub icc_invalid: bool,
|
||||
pub adobe_transform: Option<u8>,
|
||||
/// Offset of the MPF TIFF header within the file and its bytes.
|
||||
pub mpf: Option<(usize, Vec<u8>)>,
|
||||
/// The ISO 21496-1 APP2 payload after its URN: 4 bytes (versions only) on a primary image
|
||||
/// that has a gain map, the full metadata on the gain map image itself.
|
||||
pub iso_gainmap: Option<Vec<u8>>,
|
||||
}
|
||||
pub(crate) type Markers = craft_metadata::JpegInspection;
|
||||
|
||||
impl Markers {
|
||||
/// This image is a gain map (ISO 21496-1 metadata or Adobe `hdrgm` gain parameters), not a
|
||||
/// picture: never a preview, never the image to show.
|
||||
pub fn is_gain_map(&self) -> bool {
|
||||
self.iso_gainmap.as_ref().is_some_and(|p| p.len() > 4) || self.xmp.as_deref().is_some_and(|x| x.contains("hdrgm:GainMapMax"))
|
||||
}
|
||||
}
|
||||
|
||||
pub(crate) fn parse_markers(b: &[u8]) -> Option<Markers> {
|
||||
if !b.starts_with(&[0xFF, 0xD8]) {
|
||||
return None;
|
||||
}
|
||||
let mut m = Markers::default();
|
||||
let mut icc_chunks: [Option<&[u8]>; 255] = [None; 255];
|
||||
let mut icc_total = None;
|
||||
let mut p = 2;
|
||||
while p + 4 <= b.len() {
|
||||
if b[p] != 0xFF {
|
||||
// Tolerate garbage between segments: resync on the next 0xFF.
|
||||
p += 1;
|
||||
continue;
|
||||
}
|
||||
let marker = b[p + 1];
|
||||
if marker == 0xFF {
|
||||
p += 1;
|
||||
continue;
|
||||
}
|
||||
if marker == 0xD8 || (0xD0..=0xD7).contains(&marker) || marker == 0x01 {
|
||||
p += 2;
|
||||
continue;
|
||||
}
|
||||
if marker == 0xD9 {
|
||||
break;
|
||||
}
|
||||
if marker == 0xDA {
|
||||
m.first_scan_components = b.get(p + 4).copied().unwrap_or(0);
|
||||
break;
|
||||
}
|
||||
let len = u16::from_be_bytes([b[p + 2], b[p + 3]]) as usize;
|
||||
if len < 2 {
|
||||
return None;
|
||||
}
|
||||
let start = p.checked_add(4)?;
|
||||
let declared_end = p.checked_add(2)?.checked_add(len)?;
|
||||
let complete = declared_end <= b.len();
|
||||
let end = declared_end.min(b.len());
|
||||
let seg = b.get(start..end)?;
|
||||
match marker {
|
||||
0xC0..=0xCF if marker != 0xC4 && marker != 0xC8 && marker != 0xCC && seg.len() >= 6 && m.components == 0 => {
|
||||
m.precision = seg[0];
|
||||
m.sof = marker;
|
||||
m.height = u16::from_be_bytes([seg[1], seg[2]]) as u32;
|
||||
m.width = u16::from_be_bytes([seg[3], seg[4]]) as u32;
|
||||
m.components = seg[5];
|
||||
}
|
||||
0xE1 => {
|
||||
m.app1 = m.app1.saturating_add(1);
|
||||
if seg.starts_with(b"Exif\0\0") && m.exif.is_none() {
|
||||
m.exif = Some(seg[6..].to_vec());
|
||||
m.exif_offset = start + 6;
|
||||
} else if let Some(x) = seg.strip_prefix(b"http://ns.adobe.com/xap/1.0/\0")
|
||||
&& m.xmp.is_none()
|
||||
{
|
||||
m.xmp = Some(String::from_utf8_lossy(x).trim_end_matches('\0').to_string());
|
||||
}
|
||||
}
|
||||
0xE2 => {
|
||||
if seg.starts_with(b"ICC_PROFILE\0") {
|
||||
if !complete || seg.len() < 14 {
|
||||
m.icc_invalid = true;
|
||||
} else if let (Some(&sequence), Some(&total)) = (seg.get(12), seg.get(13)) {
|
||||
if sequence == 0 || total == 0 || sequence > total || icc_total.is_some_and(|expected| expected != total) {
|
||||
m.icc_invalid = true;
|
||||
} else {
|
||||
icc_total = Some(total);
|
||||
let Some(slot) = icc_chunks.get_mut(usize::from(sequence - 1)) else {
|
||||
m.icc_invalid = true;
|
||||
p = declared_end;
|
||||
continue;
|
||||
};
|
||||
if slot.is_some() {
|
||||
m.icc_invalid = true;
|
||||
} else if let Some(data) = seg.get(14..) {
|
||||
*slot = Some(data);
|
||||
} else {
|
||||
m.icc_invalid = true;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
m.icc_invalid = true;
|
||||
}
|
||||
} else if seg.starts_with(b"MPF\0") && m.mpf.is_none() {
|
||||
m.mpf = Some((start + 4, seg[4..].to_vec()));
|
||||
} else if let Some(p) = seg.strip_prefix(crate::gainmap::ISO_URN)
|
||||
&& m.iso_gainmap.is_none()
|
||||
{
|
||||
m.iso_gainmap = Some(p.to_vec());
|
||||
}
|
||||
}
|
||||
0xEE if seg.starts_with(b"Adobe") && seg.len() >= 12 => {
|
||||
m.adobe_transform = Some(seg[11]);
|
||||
}
|
||||
_ => {}
|
||||
}
|
||||
p = declared_end;
|
||||
}
|
||||
if let Some(total) = icc_total {
|
||||
let mut profile_len = 0usize;
|
||||
for chunk in icc_chunks.iter().take(usize::from(total)) {
|
||||
let Some(bytes) = chunk else {
|
||||
m.icc_invalid = true;
|
||||
break;
|
||||
};
|
||||
let Some(next_len) = profile_len.checked_add(bytes.len()) else {
|
||||
m.icc_invalid = true;
|
||||
break;
|
||||
};
|
||||
profile_len = next_len;
|
||||
}
|
||||
let maximum_len = usize::from(total).checked_mul(65_519);
|
||||
if maximum_len.is_none_or(|maximum| profile_len > maximum) {
|
||||
m.icc_invalid = true;
|
||||
}
|
||||
if !m.icc_invalid {
|
||||
let mut profile = Vec::with_capacity(profile_len);
|
||||
for bytes in icc_chunks.iter().take(usize::from(total)).flatten() {
|
||||
profile.extend_from_slice(bytes);
|
||||
}
|
||||
m.icc = Some(profile);
|
||||
}
|
||||
}
|
||||
Some(m)
|
||||
pub(crate) fn parse_markers(bytes: &[u8]) -> Option<Markers> {
|
||||
craft_metadata::inspect_jpeg(bytes)
|
||||
}
|
||||
|
||||
pub(crate) fn decode(bytes: &[u8], opts: &DecodeOptions) -> Result<Decoded> {
|
||||
@@ -400,39 +244,9 @@ pub(crate) fn embedded_thumbnail(bytes: &[u8], max_edge: u32, min_edge: u32) ->
|
||||
/// MP type code of a gain map image (CIPA DC-007 entry attribute, low 24 bits).
|
||||
pub(crate) const MPF_GAIN_MAP: u32 = 0x05_0000;
|
||||
|
||||
/// An MPF-listed image other than the primary.
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub(crate) struct MpfEntry {
|
||||
/// File offset and length of the image.
|
||||
pub offset: usize,
|
||||
pub len: usize,
|
||||
/// MP type code (attribute low 24 bits).
|
||||
pub kind: u32,
|
||||
}
|
||||
|
||||
/// The MPF-listed images other than the primary.
|
||||
pub(crate) fn mpf_images(m: &Markers) -> Vec<MpfEntry> {
|
||||
let Some((base, data)) = &m.mpf else { return vec![] };
|
||||
let Some(t) = exif::Tiff::new(data) else { return vec![] };
|
||||
let Some(ifd) = t.first_ifd() else { return vec![] };
|
||||
let Some((entries, _)) = t.ifd(ifd) else { return vec![] };
|
||||
let Some(e) = entries.iter().find(|e| e.tag == 0xB002) else { return vec![] };
|
||||
let Some(list) = t.bytes(e) else { return vec![] };
|
||||
let mut out = Vec::new();
|
||||
for (i, rec) in list.as_chunks::<16>().0.iter().enumerate().take(16) {
|
||||
if i == 0 {
|
||||
continue;
|
||||
}
|
||||
let rd = |o: usize| {
|
||||
let a = [rec[o], rec[o + 1], rec[o + 2], rec[o + 3]];
|
||||
if data.starts_with(b"II") { u32::from_le_bytes(a) } else { u32::from_be_bytes(a) }
|
||||
};
|
||||
let (attr, size, off) = (rd(0), rd(4) as usize, rd(8) as usize);
|
||||
if size > 0 && off > 0 {
|
||||
out.push(MpfEntry { offset: base.saturating_add(off), len: size, kind: attr & 0x00FF_FFFF });
|
||||
}
|
||||
}
|
||||
out
|
||||
pub(crate) fn mpf_images(m: &Markers) -> Vec<craft_metadata::mpf::MpfImage> {
|
||||
m.mpf.as_ref().map_or_else(Vec::new, |(base, data)| craft_metadata::mpf::images_from_index(data, *base))
|
||||
}
|
||||
|
||||
/// Decode to the file's 8-bit samples as stored (no colour management): 1 channel for greyscale
|
||||
@@ -461,6 +275,42 @@ pub(crate) fn decode_codes8(bytes: &[u8]) -> Result<(usize, usize, usize, Vec<u8
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn mpf_shared_matches_previous_reader_on_mutated_indices() {
|
||||
fn previous(base: usize, data: &[u8]) -> Vec<craft_metadata::mpf::MpfImage> {
|
||||
let Some(t) = exif::Tiff::new(data) else { return vec![] };
|
||||
let Some(ifd) = t.first_ifd() else { return vec![] };
|
||||
let Some((entries, _)) = t.ifd(ifd) else { return vec![] };
|
||||
let Some(e) = entries.iter().find(|e| e.tag == 0xb002) else { return vec![] };
|
||||
let Some(list) = t.bytes(e) else { return vec![] };
|
||||
list.as_chunks::<16>()
|
||||
.0
|
||||
.iter()
|
||||
.enumerate()
|
||||
.take(16)
|
||||
.skip(1)
|
||||
.filter_map(|(_, rec)| {
|
||||
let rd = |i| {
|
||||
let b = [rec[i], rec[i + 1], rec[i + 2], rec[i + 3]];
|
||||
if data.starts_with(b"II") { u32::from_le_bytes(b) } else { u32::from_be_bytes(b) }
|
||||
};
|
||||
let (attr, len, off) = (rd(0), rd(4) as usize, rd(8) as usize);
|
||||
(len > 0 && off > 0).then_some(craft_metadata::mpf::MpfImage { offset: base.saturating_add(off), len, kind: attr & 0x00ff_ffff })
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
let file = craft_metadata::mpf::write(&[0xff, 0xd8, 0xff, 0xd9], &[(0x050000, &[0xff, 0xd8, 0xff, 0xd9])]).unwrap();
|
||||
let m = parse_markers(&file).unwrap();
|
||||
let (base, data) = m.mpf.unwrap();
|
||||
for at in 0..data.len() {
|
||||
for value in [0u8, 0xff] {
|
||||
let mut altered = data.clone();
|
||||
altered[at] = value;
|
||||
assert_eq!(craft_metadata::mpf::images_from_index(&altered, base), previous(base, &altered), "mutation at {at}, value {value}");
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn container_fallback_matches_tagged_jpeg_before_resizing_and_keeps_own_metadata() {
|
||||
use crate::{ChromaSubsampling, EncodeImage, EncodeMeta, NamedSpace, Samples, SpaceOrigin, encode_jpeg};
|
||||
|
||||
Reference in new issue
Block a user