Skip to content
Merged
41 changes: 24 additions & 17 deletions crates/codecs/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -159,9 +159,10 @@ pub fn encode_jpeg(img: &EncodeImage, quality: u8, subsampling: ChromaSubsamplin
pub fn encode_png(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<u8>> {
img.validate()?;
let n = img.width as usize * img.height as usize * img.channels as usize;
let (bytes, depth): (Vec<u8>, png::BitDepth) = match img.samples {
Samples::U8(s) => (s[..n].to_vec(), png::BitDepth::Eight),
Samples::U16(s) => (s[..n].iter().flat_map(|v| v.to_be_bytes()).collect(), png::BitDepth::Sixteen),
// (8-bit samples are written as they are: no copy of the image)
let (bytes, depth): (std::borrow::Cow<[u8]>, png::BitDepth) = match img.samples {
Samples::U8(s) => (std::borrow::Cow::Borrowed(&s[..n]), png::BitDepth::Eight),
Samples::U16(s) => (s[..n].iter().flat_map(|v| v.to_be_bytes()).collect::<Vec<u8>>().into(), png::BitDepth::Sixteen),
Samples::F32(_) => return Err(Error::Encode("PNG needs 8- or 16-bit samples".into())),
};
let mut info = png::Info::with_size(img.width, img.height);
Expand Down Expand Up @@ -405,20 +406,26 @@ pub fn encode_webp_lossy(img: &EncodeImage, quality: u8, meta: &EncodeMeta) -> R
let n = img.width as usize * img.height as usize;
let ch = img.channels as usize;
let alpha = ch == 2 || ch == 4;
let px: Vec<u8> = s
.chunks_exact(ch.max(1))
.take(n)
.flat_map(|c| match *c {
[g] => [g, g, g, 255],
[g, a] => [g, g, g, a],
[r, g, b] => [r, g, b, 255],
[r, g, b, a, ..] => [r, g, b, a],
_ => [0, 0, 0, 255],
})
.enumerate()
.filter(|(i, _)| alpha || i % 4 != 3)
.map(|(_, v)| v)
.collect();
// RGB and RGBA samples are what libwebp reads, so they are handed over as they are (no copy of the image); grey is
// widened to RGB(A)
let px: std::borrow::Cow<[u8]> = match (ch, s.get(..n * ch)) {
(3 | 4, Some(whole)) => std::borrow::Cow::Borrowed(whole),
_ => s
.chunks_exact(ch.max(1))
.take(n)
.flat_map(|c| match *c {
[g] => [g, g, g, 255],
[g, a] => [g, g, g, a],
[r, g, b] => [r, g, b, 255],
[r, g, b, a, ..] => [r, g, b, a],
_ => [0, 0, 0, 255],
})
.enumerate()
.filter(|(i, _)| alpha || i % 4 != 3)
.map(|(_, v)| v)
.collect::<Vec<u8>>()
.into(),
};
if px.len() != n * if alpha { 4 } else { 3 } {
return Err(Error::Encode("WebP: fewer samples than the image needs".into()));
}
Expand Down
35 changes: 35 additions & 0 deletions crates/codecs/tests/it/roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -603,6 +603,41 @@ fn webp_lossy_close_with_metadata() {
assert!(encode_webp_lossy(&EncodeImage::new(4, 4, 3, Samples::U16(&deep)), 90, &meta).is_err());
}

/// The PNG and lossy WebP encoders hand RGB(A) samples to their codec as they are (FX-234): the same file as when the
/// samples are widened first, and samples past the end of the image are left out as they always were.
#[test]
fn png_and_lossy_webp_write_rgb_samples_as_given() {
let meta = EncodeMeta::default();
let (w, h) = (24u32, 10u32);
let n = (w * h) as usize;
let grey: Vec<u8> = (0..n).map(|i| ((i * 37) % 251) as u8).collect();
let grey_alpha: Vec<u8> = grey.iter().enumerate().flat_map(|(i, &g)| [g, (i * 11 % 256) as u8]).collect();
let rgb: Vec<u8> = grey.iter().flat_map(|&g| [g, g, g]).collect();
let rgba: Vec<u8> = grey.iter().enumerate().flat_map(|(i, &g)| [g, g, g, (i * 11 % 256) as u8]).collect();
let image = |ch: u8, s: &'static [u8]| EncodeImage::new(w, h, ch, Samples::U8(s));
let leak = |v: &[u8]| -> &'static [u8] { Box::leak(v.to_vec().into_boxed_slice()) };
// (a longer buffer than the image needs: what lies past it is not written)
let longer = |v: &[u8]| -> &'static [u8] { leak(&[v, &[7u8; 64]].concat()) };
if WEBP_LOSSY {
for q in [30u8, 90] {
// grey is widened to RGB: the same file as the RGB samples
let widened = encode_webp_lossy(&image(3, leak(&rgb)), q, &meta).unwrap();
assert_eq!(encode_webp_lossy(&image(1, leak(&grey)), q, &meta).unwrap(), widened, "grey, q{q}");
assert_eq!(encode_webp_lossy(&image(3, longer(&rgb)), q, &meta).unwrap(), widened, "RGB with samples past the end, q{q}");
let widened = encode_webp_lossy(&image(4, leak(&rgba)), q, &meta).unwrap();
assert_eq!(encode_webp_lossy(&image(2, leak(&grey_alpha)), q, &meta).unwrap(), widened, "grey and alpha, q{q}");
assert_eq!(encode_webp_lossy(&image(4, longer(&rgba)), q, &meta).unwrap(), widened, "RGBA with samples past the end, q{q}");
}
}
for (ch, samples) in [(3u8, &rgb), (4, &rgba)] {
let whole = encode_png(&image(ch, leak(samples)), &meta).unwrap();
assert_eq!(encode_png(&image(ch, longer(samples)), &meta).unwrap(), whole, "{ch} channels with samples past the end");
let d = decode(&whole, DecodeOptions::default()).unwrap();
assert_eq!((d.image.width, d.image.height), (w as usize, h as usize));
assert_eq!(d.to_srgb8().data.iter().flat_map(|p| [p[0], p[1], p[2]]).collect::<Vec<u8>>(), rgb, "{ch} channels: the pixels come back");
}
}

/// Lossless WebP takes 16,384 pixels a side, one more than lossy WebP's [`WEBP_MAX_SIDE`]; one more pixel is refused.
#[test]
fn lossless_webp_takes_one_pixel_more_than_lossy() {
Expand Down
Loading