Skip to content
Closed
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion crates/engine/src/media/source.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use super::{Arc, DcpProfile, Deserialize, DevelopSettings, MediaKind, Photo, Rgb32f, Rgba8, Serialize, SourceInfo};

/// Bump when the pipeline's output changes, to invalidate cached thumbnails.
pub const RENDER_CACHE_VERSION: u64 = 76;
pub const RENDER_CACHE_VERSION: u64 = 77;

/// Thumbnails render at one of these long edges (so window/cell size changes reuse the cache).
pub const THUMB_SIZES: [usize; 4] = [128, 256, 384, 512];
Expand Down
33 changes: 24 additions & 9 deletions crates/heif/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -336,21 +336,36 @@ fn decode_item(ctx: &Context<'_>, id: u32, options: &Options, with_alpha: bool)
}
_ => return Err(Error::Limit(format!("the image canvas is {w}x{h}, beyond the {limit}-pixel limit"))),
}
let mode = if options.apply_transforms && orient::odd_crop(w, h, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest };
let mut data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode)
// The transforms apply to the picture at its declared size, so the `clap` parity that
// decides the upsampling is measured there, not on the coded picture.
let (dw, dh) = (cw as usize, ch as usize);
let mode =
if options.apply_transforms && orient::odd_crop(dw, dh, &p.transforms)? { ycc::Upsampling::Bilinear } else { ycc::Upsampling::Nearest };
let data = ycc::to_rgb16(&planes, signal, alpha_id.is_some(), mode)
.ok_or_else(|| Error::Malformed("the decoded pictures don't cover the image".into()))?;
let bit_depth = planes.bit_depth();
let has_alpha = alpha_id.is_some();
let mut img = orient::Pixels { width: w, height: h, ch: if has_alpha { 4 } else { 3 }, data };
// A coded picture is a whole number of coding blocks and may be larger than the image the
// container declares (Sony codes 1920 x 1080 as 1920 x 1088 and writes no SPS conformance
// window). Crop to `ispe` before the alpha merge and the transforms, both of which are
// defined on that size, so decoding agrees with [`probe`] instead of handing back the
// encoder's padding.
img = orient::to_declared(img, dw, dh)?;
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
if let Some(aux) = alpha_id {
let ap = ctx.props(aux).map_err(err)?;
let alpha = Coded::decode(ctx, aux, &ap, limit)?;
let alpha_planes = alpha.planes()?;
if alpha_planes.size() != (w, h) {
// The alpha is a coded item of its own: it declares its own size and may pad it to whole
// coding blocks differently from the picture. What has to agree is what the two declare,
// not how either is coded; the padding comes off both the same way. Checked before the
// alpha is decoded, so a mismatch costs nothing.
if ctx.coded_size(aux, &ap).map_err(err)? != (cw, ch) {
return Err(Error::Unsupported("an alpha image of a different size than the picture"));
}
ycc::put_alpha(&alpha_planes, &mut data).ok_or_else(|| Error::Malformed("the alpha image is incomplete".into()))?;
let alpha = Coded::decode(ctx, aux, &ap, limit)?;
let alpha_planes = alpha.planes()?;
// `put_alpha` refuses a plane that does not cover the declared size.
ycc::put_alpha(&alpha_planes, &mut img.data, dw).ok_or_else(|| Error::Malformed("the alpha image is incomplete".into()))?;
}
let bit_depth = planes.bit_depth();
let has_alpha = alpha_id.is_some();
let mut img = orient::Pixels { width: w, height: h, ch: if has_alpha { 4 } else { 3 }, data };
if options.apply_transforms {
img = orient::apply(img, &p.transforms)?;
}
Expand Down
39 changes: 39 additions & 0 deletions crates/heif/src/orient.rs
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,45 @@ impl Pixels {
}
}

/// Crops a decoded picture to the size the container declares (`ispe`), dropping the encoder's
/// padding. The visible image is the top-left corner.
///
/// A coded HEVC picture holds whole coding blocks, so a camera writing 1920 × 1080 may code
/// 1920 × 1088 and leave the real size to `ispe`. The SPS conformance window would say so inside
/// the bitstream, but it is optional and Sony's HEIF files omit it: without this, the eight
/// padding rows (video-range black, so a visible dark band on a full-range picture) reach the
/// caller and every size disagrees with [`crate::probe`], which reads `ispe`.
///
/// Grids are already composed at their declared output size, so this is a no-op for them.
pub fn to_declared(mut img: Pixels, width: usize, height: usize) -> Result<Pixels, Error> {
if img.width == width && img.height == height {
return Ok(img);
}
if img.width < width || img.height < height {
return Err(Error::Malformed(format!(
"the decoded picture is {}x{}, smaller than the {width}x{height} the container declares",
img.width, img.height
)));
}
let (ch, stride) = (img.ch, img.width * img.ch);
let kept = width * ch;
// Only the height shrank, the common 1920 x 1088 -> 1920 x 1080: every kept row is already
// where it belongs and the truncate is the whole job. Moving them would memmove the picture
// onto itself.
if kept != stride {
// Compact the kept rows in place rather than allocating the picture again: row `y` keeps
// its first `kept` samples and moves left, so source and destination never cross.
for y in 0..height {
let (src, dst) = (y * stride, y * kept);
img.data.copy_within(src..src + kept, dst);
}
}
img.data.truncate(width * height * ch);
img.width = width;
img.height = height;
Ok(img)
}

/// The rectangle `(left, top, width, height)` a `clap` selects from a `w` × `h` image. Its centre
/// is `((w - 1) / 2 + horizOff, (h - 1) / 2 + vertOff)`; a corner that falls between two pixels
/// is rounded as libheif does: left down, top up.
Expand Down
156 changes: 156 additions & 0 deletions crates/heif/src/tests_synthetic.rs
Original file line number Diff line number Diff line change
Expand Up @@ -198,3 +198,159 @@ fn too_many_transform_properties_are_refused() {
let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (32, 32));
}

/// A coded picture holds whole coding blocks, so a camera may code more rows than it shows and
/// leave the real size to `ispe`: Sony writes 1920 × 1080 as 1920 × 1088 and no SPS conformance
/// window says so. The padding must not reach the caller, and `decode` must agree with `probe`.
#[test]
fn a_picture_coded_larger_than_its_ispe_is_cropped() {
let mut bytes = build(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &grey) });
// The single picture's `ispe` declares 32 × 32; make it 32 × 24, leaving the coded picture
// (and every other box) alone, exactly as a camera's bottom padding looks.
let want: Vec<u8> = b"ispe".iter().copied().chain([0, 0, 0, 0]).chain(32u32.to_be_bytes()).chain(32u32.to_be_bytes()).collect();
let at = bytes.windows(want.len()).position(|w| w == want).expect("the 32 x 32 ispe");
let height = at + b"ispe".len() + 4 + 4;
bytes[height..height + 4].copy_from_slice(&24u32.to_be_bytes());

let info = probe(&bytes).unwrap();
assert_eq!((info.width, info.height), (32, 24));
let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (32, 24), "decode must agree with probe");
// What survives is the top-left corner, sample for sample.
for y in 0..24 {
for x in 0..32 {
let px = &d.data[((y * 32 + x) * 3) as usize..][..3];
assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})");
}
}
}

/// The width crop is the one that moves samples: `to_declared` compacts each kept row to the left,
/// where a height-only crop just drops the tail. A portrait file takes this path after `irot`.
#[test]
fn a_width_crop_realigns_every_row() {
let mut bytes = build(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &grey) });
let want: Vec<u8> = b"ispe".iter().copied().chain([0, 0, 0, 0]).chain(32u32.to_be_bytes()).chain(32u32.to_be_bytes()).collect();
let at = bytes.windows(want.len()).position(|w| w == want).expect("the 32 x 32 ispe");
let width = at + b"ispe".len() + 4;
bytes[width..width + 4].copy_from_slice(&24u32.to_be_bytes());

let info = probe(&bytes).unwrap();
assert_eq!((info.width, info.height), (24, 32));
let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (24, 32), "decode must agree with probe");
// Every row must have kept its own left-hand samples, not slid along from the next row.
for y in 0..32 {
for x in 0..24 {
let px = &d.data[((y * 24 + x) * 3) as usize..][..3];
assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})");
}
}
}

/// Both edges at once, so the row compaction and the row drop run together.
#[test]
fn a_crop_on_both_edges_keeps_the_corner() {
let mut bytes = build(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &grey) });
let want: Vec<u8> = b"ispe".iter().copied().chain([0, 0, 0, 0]).chain(32u32.to_be_bytes()).chain(32u32.to_be_bytes()).collect();
let at = bytes.windows(want.len()).position(|w| w == want).expect("the 32 x 32 ispe");
let width = at + b"ispe".len() + 4;
bytes[width..width + 4].copy_from_slice(&20u32.to_be_bytes());
bytes[width + 4..width + 8].copy_from_slice(&12u32.to_be_bytes());

let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (20, 12));
for y in 0..12 {
for x in 0..20 {
let px = &d.data[((y * 20 + x) * 3) as usize..][..3];
assert_eq!(px, [luma(x, y) * 257; 3], "({x}, {y})");
}
}
}

/// Every `ispe` in a built file, in the order they were written: the primary image's first, then
/// each auxiliary image's. Each is (offset of its width field, width, height).
fn ispe_fields(bytes: &[u8]) -> Vec<(usize, u32, u32)> {
let mut out = Vec::new();
for i in 0..bytes.len().saturating_sub(16) {
if &bytes[i..i + 4] == b"ispe" && bytes[i + 4..i + 8] == [0, 0, 0, 0] {
let g = |o: usize| u32::from_be_bytes([bytes[o], bytes[o + 1], bytes[o + 2], bytes[o + 3]]);
out.push((i + 8, g(i + 8), g(i + 12)));
}
}
out
}

fn set_ispe(bytes: &mut [u8], at: usize, w: u32, h: u32) {
bytes[at..at + 4].copy_from_slice(&w.to_be_bytes());
bytes[at + 4..at + 8].copy_from_slice(&h.to_be_bytes());
}

/// An alpha image is its own coded item, so it may pad its declared size differently from the
/// picture's. What has to agree is what the two declare; the padding comes off both.
#[test]
fn an_alpha_padded_on_its_own_still_lines_up() {
let alpha = |x: u32, _: u32| (x * 4) as u16;
let mut bytes = build(&Spec { props: vec![FULL_601], alpha: Some(&alpha), ..Spec::new(32, 32, &grey) });
// Both items code 32 x 32; declare 32 x 24 for each, as a camera's bottom padding looks.
let f = ispe_fields(&bytes);
assert_eq!(f.len(), 2, "one ispe for the picture and one for the alpha: {f:?}");
for (at, _, _) in f {
set_ispe(&mut bytes, at, 32, 24);
}
let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (32, 24));
assert!(d.has_alpha);
assert_eq!(d.data.len(), 32 * 24 * 4);
// the alpha ramp still sits under the right columns, on the last kept row as on the first
for y in [0u32, 23] {
for x in [0u32, 10, 31] {
let i = ((y * 32 + x) * 4) as usize;
assert_eq!(d.data[i + 3], alpha(x, y) * 257, "alpha at ({x}, {y})");
assert_eq!(d.data[i..i + 3], [luma(x, y) * 257; 3], "colour at ({x}, {y})");
}
}
}

/// Two different declared sizes are two different images, which would need resampling.
#[test]
fn an_alpha_declaring_another_size_is_unsupported() {
let alpha = |x: u32, _: u32| (x * 4) as u16;
let mut bytes = build(&Spec { props: vec![FULL_601], alpha: Some(&alpha), ..Spec::new(32, 32, &grey) });
let f = ispe_fields(&bytes);
set_ispe(&mut bytes, f[0].0, 32, 24);
set_ispe(&mut bytes, f[1].0, 32, 20);
let r = decode(&bytes, &Options::default());
assert!(matches!(r, Err(Error::Unsupported(m)) if m.contains("alpha")), "{r:?}");
}

/// The other way round -- a declared size larger than the coded picture -- is a broken file, not
/// something to pad out.
#[test]
fn an_ispe_larger_than_the_coded_picture_is_malformed() {
let mut bytes = build(&Spec { props: vec![FULL_601], ..Spec::new(32, 32, &grey) });
let want: Vec<u8> = b"ispe".iter().copied().chain([0, 0, 0, 0]).chain(32u32.to_be_bytes()).chain(32u32.to_be_bytes()).collect();
let at = bytes.windows(want.len()).position(|w| w == want).expect("the 32 x 32 ispe");
let height = at + b"ispe".len() + 4 + 4;
bytes[height..height + 4].copy_from_slice(&64u32.to_be_bytes());
let r = decode(&bytes, &Options::default());
assert!(matches!(r, Err(Error::Malformed(ref m)) if m.contains("declares")), "{r:?}");
}

/// The crop happens before the container's transforms, which are defined on the declared size:
/// a quarter turn of a picture coded 32 × 32 but declared 32 × 24 is 24 × 32, not 32 × 32.
#[test]
fn the_ispe_crop_precedes_the_transforms() {
let mut bytes = build(&Spec { props: vec![FULL_601, Prop::Irot(1)], ..Spec::new(32, 32, &grey) });
let want: Vec<u8> = b"ispe".iter().copied().chain([0, 0, 0, 0]).chain(32u32.to_be_bytes()).chain(32u32.to_be_bytes()).collect();
let at = bytes.windows(want.len()).position(|w| w == want).expect("the 32 x 32 ispe");
let height = at + b"ispe".len() + 4 + 4;
bytes[height..height + 4].copy_from_slice(&24u32.to_be_bytes());
let d = decode(&bytes, &Options::default()).unwrap();
assert_eq!((d.width, d.height), (24, 32));
// Counter-clockwise: the right column of the cropped picture becomes the top row.
for x in 0..24u32 {
let px = &d.data[(x as usize) * 3..][..3];
assert_eq!(px, [luma(31, x) * 257; 3], "({x}, 0)");
}
}
25 changes: 21 additions & 4 deletions crates/heif/src/ycc.rs
Original file line number Diff line number Diff line change
Expand Up @@ -229,13 +229,22 @@ pub fn to_rgb16(planes: &Planes<'_>, signal: Signal, alpha: bool, mode: Upsampli
}

/// Writes an alpha picture's luma, full range, into channel 3 of `rgba`.
pub fn put_alpha(planes: &Planes<'_>, rgba: &mut [u16]) -> Option<()> {
/// Writes `planes`' luma into the alpha channel of `rgba`, whose rows are `width` pixels wide.
///
/// The alpha image may be coded larger than the picture it belongs to, the way a picture can be
/// coded larger than its `ispe` (see [`crate::orient::to_declared`]); its top-left `width`
/// columns are the ones that line up, so the rest of each row is skipped rather than shifting
/// the alpha across the picture.
pub fn put_alpha(planes: &Planes<'_>, rgba: &mut [u16], width: usize) -> Option<()> {
let (w, h) = planes.size();
if width == 0 || w < width || rgba.len() % (width * 4) != 0 || h < rgba.len() / (width * 4) {
return None;
}
let max = ((1u32 << u32::from(planes.bit_depth()).clamp(1, 16)) - 1) as f32;
let mut luma = vec![0u16; w];
for (y, row) in rgba.chunks_exact_mut(w * 4).enumerate().take(h) {
for (y, row) in rgba.chunks_exact_mut(width * 4).enumerate().take(h) {
planes.luma_row(y, &mut luma)?;
for (px, &a) in row.as_chunks_mut::<4>().0.iter_mut().zip(&luma) {
for (px, &a) in row.as_chunks_mut::<4>().0.iter_mut().zip(&luma[..width]) {
let v = (f32::from(a) / max).clamp(0.0, 1.0);
px[3] = (v * 65535.0 + 0.5) as u16;
}
Expand Down Expand Up @@ -315,8 +324,16 @@ mod tests {
let f = frame(2, 2, 8, ChromaFormat::Yuv420, 128, 128, 128);
let mut v = to_rgb16(&Planes::Picture(&f), Signal { matrix: 6, full_range: true }, true, Upsampling::Nearest).unwrap();
assert_eq!(v[3], 65535);
put_alpha(&Planes::Picture(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v).unwrap();
put_alpha(&Planes::Picture(&frame(2, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v, 2).unwrap();
assert_eq!(v[3], 51 * 257);
// an alpha coded wider than the picture lines up on its left columns, not across the row
let wide = frame(4, 2, 8, ChromaFormat::Monochrome, 0, 0, 0);
let mut wide = wide;
wide.y = vec![10, 20, 99, 99, 30, 40, 99, 99];
put_alpha(&Planes::Picture(&wide), &mut v, 2).unwrap();
assert_eq!([v[3], v[7], v[11], v[15]], [10 * 257, 20 * 257, 30 * 257, 40 * 257]);
// an alpha narrower than the picture has no such alignment: refused, not stretched
assert!(put_alpha(&Planes::Picture(&frame(1, 2, 8, ChromaFormat::Monochrome, 51, 0, 0)), &mut v, 2).is_none());
let mut short = frame(4, 4, 8, ChromaFormat::Yuv420, 128, 128, 128);
short.y.truncate(5);
assert!(to_rgb16(&Planes::Picture(&short), Signal { matrix: 6, full_range: true }, false, Upsampling::Bilinear).is_none());
Expand Down
Loading