Skip to content

PhotoCraft: An open-source, photo editor written by scratch in pure Rust

Codecs: warn when DPX or Cineon saves drop bits (#8793)

Przemyslaw Majdak612c4a3c7fec
diff --git a/crates/codecs/README.md b/crates/codecs/README.md
index 46a33e89b..c191cc40b 100644
--- a/crates/codecs/README.md
+++ b/crates/codecs/README.md
@@ -106,6 +106,9 @@ embedded table (and a PNG's transparent entry) so `photocraft-io` can open them
give `DecodeWarning::MoreElements`; the image orientation is applied on import. Writing is
big-endian, one unencoded element, at `EncodeOptions::dpx_bits` (8/10/12/16; by default 8 for
U8 and 16 otherwise), packing 1 for 10 and 12 bits; gray with alpha is written as luma.
+ `FidelityWarning::BitsReduced` reports a 10- or 12-bit save (and every Cineon save) that drops
+ precision: always for float samples, for U16 ones unless they are already code values at that
+ depth.
Other descriptors, signed or run-length-encoded data and other bit depths return
`CodecError::Unsupported` naming the field.
diff --git a/crates/codecs/src/codecs/dpx.rs b/crates/codecs/src/codecs/dpx.rs
index f93c79c92..aa71f9465 100644
--- a/crates/codecs/src/codecs/dpx.rs
+++ b/crates/codecs/src/codecs/dpx.rs
@@ -537,6 +537,26 @@ pub(crate) fn bits_for(opt: Option<DpxBits>, sample: SampleType) -> u8 {
}
}
+/// The bits `format` stores below its U16 plan: DPX at 10 or 12 bits, Cineon's 10. `None` when
+/// the stored depth is the plan's sample type.
+pub(crate) fn packed_bits(format: Format, opts: &EncodeOptions) -> Option<u8> {
+ match format {
+ Format::Dpx => opts.dpx_bits.filter(|b| matches!(b, DpxBits::Bits10 | DpxBits::Bits12)).map(DpxBits::bits),
+ Format::Cineon => Some(10),
+ _ => None,
+ }
+}
+
+/// `true` when every sample of a U16 image is already a `bits`-bit code value, so writing it at
+/// `bits` and reading it back gives the same samples (a frame opened from such a file).
+pub(crate) fn keeps_u16_samples(img: &Image, bits: u8) -> bool {
+ if img.sample_type() != SampleType::U16 || !(1..16).contains(&bits) {
+ return false;
+ }
+ let max = (1u64 << bits) - 1;
+ img.data().as_chunks::<2>().0.iter().map(|c| u16::from_ne_bytes(*c)).all(|v| widen(narrow(v, max), max) == v)
+}
+
/// The plan's sample type for the chosen bits: U8 for 8 bits, U16 for 10, 12 and 16.
pub(crate) fn plan_sample(opt: Option<DpxBits>, src: SampleType) -> SampleType {
match opt {
diff --git a/crates/codecs/src/fidelity.rs b/crates/codecs/src/fidelity.rs
index a6937b571..d80bb9ef7 100644
--- a/crates/codecs/src/fidelity.rs
+++ b/crates/codecs/src/fidelity.rs
@@ -4,6 +4,7 @@
use std::fmt;
+use crate::codecs::dpx;
use crate::format::{Format, caps};
use crate::image::{ChannelLayout, Image, SampleType};
use crate::options::{DdsCompression, EncodeOptions};
@@ -20,6 +21,12 @@ pub enum FidelityWarning {
from: SampleType,
to: SampleType,
},
+ /// Samples will be stored with fewer bits than their sample type holds: DPX at 10 or 12
+ /// bits, Cineon at 10.
+ BitsReduced {
+ from: SampleType,
+ bits: u8,
+ },
/// Float samples outside `[0, 1]` will be clipped by integer storage.
RangeClipped,
/// Non-opaque alpha will be discarded.
@@ -82,6 +89,7 @@ impl fmt::Display for FidelityWarning {
write!(f, "{} cannot be written in this build", format.name())
}
DepthReduced { from, to } => write!(f, "{} will be reduced to {}", depth_name(*from), depth_name(*to)),
+ BitsReduced { from, bits } => write!(f, "{} will be reduced to {bits}-bit", depth_name(*from)),
RangeClipped => write!(f, "HDR values outside 0..1 will be clipped"),
AlphaDiscarded => write!(f, "alpha will be discarded"),
AlphaBinarized => write!(f, "alpha will be reduced to on/off transparency"),
@@ -161,7 +169,7 @@ pub(crate) fn plan(image: &Image, format: Format, opts: &EncodeOptions) -> Plan
// The sample type follows the chosen bits (U8 for 8, U16 for 10, 12 and 16).
Format::Dpx => Plan {
layout: if layout == ChannelLayout::GrayA { ChannelLayout::Gray } else { pick_layout(layout, c.layouts, c.alpha) },
- sample: crate::codecs::dpx::plan_sample(opts.dpx_bits, sample),
+ sample: dpx::plan_sample(opts.dpx_bits, sample),
},
// CIELab has no float form: float Lab is written with 16 bits.
Format::Tiff if layout.is_lab() && sample.is_float() => Plan { layout: pick_layout(layout, c.layouts, c.alpha), sample: SampleType::U16 },
@@ -201,7 +209,13 @@ pub fn fidelity_warnings_with(image: &Image, format: Format, opts: &EncodeOption
(SampleType::F16, SampleType::F32) => false,
_ => true,
};
- if lossy_depth {
+ // DPX at 10 or 12 bits and Cineon keep fewer bits than their U16 plan: float samples always
+ // lose precision there, 16-bit ones unless they are already code values at that depth.
+ if let Some(bits) = dpx::packed_bits(format, opts).filter(|_| ss != SampleType::U8) {
+ if ss.is_float() || !dpx::keeps_u16_samples(&image.converted(p.layout, SampleType::U16), bits) {
+ w.push(W::BitsReduced { from: ss, bits });
+ }
+ } else if lossy_depth {
w.push(W::DepthReduced { from: ss, to: p.sample });
}
// FITS stores floats as 0..1 (see `codecs::fits`), so out-of-range values are clipped too.
diff --git a/crates/codecs/tests/it/dpx.rs b/crates/codecs/tests/it/dpx.rs
index 6fbfb2db7..3ec897824 100644
--- a/crates/codecs/tests/it/dpx.rs
+++ b/crates/codecs/tests/it/dpx.rs
@@ -323,6 +323,49 @@ fn chosen_bit_depth_sets_the_header_and_packing() {
assert!(fidelity_warnings(&float, Format::Dpx).contains(&FidelityWarning::DepthReduced { from: SampleType::F32, to: SampleType::U16 }));
}
+/// The depth warnings of `img` written as `format` with `o`.
+fn depth_warnings(img: &Image, format: Format, o: &EncodeOptions) -> Vec<FidelityWarning> {
+ fidelity_warnings_with(img, format, o)
+ .into_iter()
+ .filter(|w| matches!(w, FidelityWarning::DepthReduced { .. } | FidelityWarning::BitsReduced { .. }))
+ .collect()
+}
+
+#[test]
+fn saving_sixteen_bits_at_ten_or_twelve_warns_with_the_stored_bits() {
+ let img = Image::from_u16(5, 2, ChannelLayout::Rgb, &(0..30u16).map(|i| i * 2000 + 1).collect::<Vec<_>>()).unwrap();
+ for (choice, bits) in [(DpxBits::Bits10, 10), (DpxBits::Bits12, 12)] {
+ assert_eq!(depth_warnings(&img, Format::Dpx, &opts(Some(choice))), [FidelityWarning::BitsReduced { from: SampleType::U16, bits }]);
+ assert_eq!(FidelityWarning::BitsReduced { from: SampleType::U16, bits }.to_string(), format!("16-bit will be reduced to {bits}-bit"));
+ // Float samples name the stored bits too, not the 16-bit words they are packed in.
+ let float = img.convert(ChannelLayout::Rgb, SampleType::F32);
+ assert_eq!(depth_warnings(&float, Format::Dpx, &opts(Some(choice))), [FidelityWarning::BitsReduced { from: SampleType::F32, bits }]);
+ // 8-bit samples widen into 10 and 12 bits without loss.
+ let eight = img.convert(ChannelLayout::Rgb, SampleType::U8);
+ assert_eq!(depth_warnings(&eight, Format::Dpx, &opts(Some(choice))), []);
+ }
+ assert_eq!(depth_warnings(&img, Format::Dpx, &opts(Some(DpxBits::Bits16))), []);
+ assert_eq!(depth_warnings(&img, Format::Dpx, &opts(None)), []);
+ assert_eq!(depth_warnings(&img, Format::Dpx, &opts(Some(DpxBits::Bits8))), [FidelityWarning::DepthReduced { from: SampleType::U16, to: SampleType::U8 }]);
+ assert_eq!(depth_warnings(&img, Format::Cineon, &EncodeOptions::default()), [FidelityWarning::BitsReduced { from: SampleType::U16, bits: 10 }]);
+}
+
+#[test]
+fn a_frame_opened_at_ten_or_twelve_bits_saves_back_without_a_warning() {
+ let img = Image::from_u16(5, 2, ChannelLayout::Rgb, &(0..30u16).map(|i| i * 2000 + 1).collect::<Vec<_>>()).unwrap();
+ for (choice, bits) in [(DpxBits::Bits10, 10), (DpxBits::Bits12, 12)] {
+ let opened = decode(&encode(&img, Format::Dpx, &opts(Some(choice))).unwrap()).unwrap();
+ assert_eq!(depth_warnings(&opened, Format::Dpx, &opts(Some(choice))), [], "{bits}-bit");
+ assert_eq!(decode(&encode(&opened, Format::Dpx, &opts(Some(choice))).unwrap()).unwrap(), opened, "{bits}-bit");
+ }
+ // A 12-bit frame saved at 10 bits does lose its two low bits.
+ let twelve = decode(&encode(&img, Format::Dpx, &opts(Some(DpxBits::Bits12))).unwrap()).unwrap();
+ assert_eq!(depth_warnings(&twelve, Format::Dpx, &opts(Some(DpxBits::Bits10))), [FidelityWarning::BitsReduced { from: SampleType::U16, bits: 10 }]);
+ let cineon = decode(&cineon_bytes(3, 4, 2, &cineon_codes(24))).unwrap();
+ assert_eq!(depth_warnings(&cineon, Format::Cineon, &EncodeOptions::default()), []);
+ assert_eq!(depth_warnings(&cineon, Format::Dpx, &opts(Some(DpxBits::Bits10))), []);
+}
+
#[test]
fn gray_with_alpha_is_written_as_luma_with_a_warning() {
let img = Image::from_u8(2, 1, ChannelLayout::GrayA, vec![10, 128, 200, 255]).unwrap();
diff --git a/crates/codecs/tests/it/fidelity.rs b/crates/codecs/tests/it/fidelity.rs
index 2c584a559..2cdaf20c5 100644
--- a/crates/codecs/tests/it/fidelity.rs
+++ b/crates/codecs/tests/it/fidelity.rs
@@ -180,6 +180,7 @@ fn every_warning_has_a_message() {
let all = [
W::WriteUnsupported { format: Format::Avif },
W::DepthReduced { from: SampleType::F32, to: SampleType::F16 },
+ W::BitsReduced { from: SampleType::U16, bits: 10 },
W::RangeClipped,
W::AlphaDiscarded,
W::AlphaBinarized,
@@ -209,9 +210,19 @@ fn warnings_match_actual_roundtrip_behaviour() {
let img = test_image(l, s);
let w = warns(&img, f);
let back = decode(&encode(&img, f, &EncodeOptions::default()).unwrap()).unwrap();
- let depth_reduced = w.iter().any(|w| matches!(w, W::DepthReduced { .. }));
+ let depth_reduced = w.iter().any(|w| match w {
+ W::DepthReduced { .. } => true,
+ W::BitsReduced { from, .. } => from.is_float(),
+ _ => false,
+ });
let lost_depth = back.sample_type() != s && back.sample_type() != SampleType::F32 && s != SampleType::U8;
assert_eq!(depth_reduced, lost_depth, "{f:?} {l:?} {s:?} {w:?} -> {:?}", back.sample_type());
+ // Cineon stores 10 bits: 16-bit samples come back changed exactly when warned.
+ if f == Format::Cineon && s == SampleType::U16 && back.sample_type() == s {
+ let bits_reduced = w.iter().any(|w| matches!(w, W::BitsReduced { .. }));
+ let changed = back.to_u16_samples() != img.convert(back.layout(), s).to_u16_samples();
+ assert_eq!(bits_reduced, changed, "{f:?} {l:?} {w:?}");
+ }
let alpha_lost = l.has_alpha() && !back.layout().has_alpha();
assert_eq!(w.contains(&W::AlphaDiscarded), alpha_lost, "{f:?} {l:?} {s:?}");
let cmyk_lost = l.is_cmyk() && !back.layout().is_cmyk();