Skip to content
Merged
Show file tree
Hide file tree
Changes from all 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
20 changes: 20 additions & 0 deletions Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -133,6 +133,8 @@ ab_glyph = { version = "0.2", default-features = false, features = ["std"] } #
png = "0.18"
tiff = "0.11"
image-webp = "0.2"
# lossy WebP export (libwebp, C; AGENTS.md → "Rust first", #1482): its safe wrapper, without the `image` integration
webp = { version = "0.3", default-features = false }
exr = { version = "1.74", default-features = false } # BSD-3-Clause, pure Rust (no unsafe) OpenEXR; scene-linear export
moxcms = { version = "0.9", default-features = false, features = ["lut"] }
jxl-oxide = { version = "0.12", default-features = false }
Expand Down
10 changes: 10 additions & 0 deletions NOTICE
Original file line number Diff line number Diff line change
Expand Up @@ -226,6 +226,16 @@ downloads cities15000.zip, admin1CodesASCII.txt and countryInfo.txt from GeoName
under Creative Commons Attribution 4.0 (https://creativecommons.org/licenses/by/4.0/);
attribution: "GeoNames, geonames.org". The lookup code (crates/geocode) is our own.

Lossy WebP export (native builds)
---------------------------------
Desktop builds encode lossy WebP with libwebp 1.3.1 with the CVE-2023-4863 fix
(https://chromium.googlesource.com/webm/libwebp),
Copyright (c) 2010, Google Inc., licensed under the BSD 3-Clause License with Google's additional
patent grant (crates/codecs/LICENSE-libwebp.txt). It is compiled from the C sources vendored in the
libwebp-sys crate 0.9.6 (MIT License, https://github.com/NoXF/libwebp-sys) and called through the
webp crate 0.3.1 (MIT OR Apache-2.0, https://github.com/jaredforth/webp). libwebp is a C library, used under the
Rust-first rule (AGENTS.md) behind the codecs crate's `webp-lossy` feature. Web and Android builds leave it out and export lossless WebP only.

ONNX Runtime (AI models on the graphics card)
---------------------------------------------
Desktop releases (Windows x64 and ARM64, Linux x86-64 and ARM64, macOS on Apple silicon) ship
Expand Down
10 changes: 9 additions & 1 deletion crates/codecs/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -42,8 +42,16 @@ avif-serialize = { workspace = true, optional = true }
# spawns threads of its own (std::thread), which wasm32 has not got
jixel = { workspace = true, optional = true }

# Lossy WebP export through libwebp (C, BSD-3-Clause) behind its maintained safe wrapper `webp`: the one C library
# AGENTS.md → "Rust first" approves for this (#1482). Desktop only: the web build and Android keep lossless WebP
# (`image-webp`, pure Rust), and the export dialog says so.
[target.'cfg(not(any(target_arch = "wasm32", target_os = "android")))'.dependencies]
webp = { workspace = true, optional = true }

[features]
default = ["parallel", "jxl", "avif"]
default = ["parallel", "jxl", "avif", "webp-lossy"]
## Lossy WebP encoding (libwebp via `webp`); desktop targets only, lossless elsewhere.
webp-lossy = ["dep:webp"]
parallel = ["dep:rayon", "lcc-raster/parallel", "jpeg-decoder/rayon"]
## JPEG XL decode (jxl-oxide) and, on native targets, encode (jixel); both pure Rust.
jxl = ["dep:jxl-oxide", "dep:jixel"]
Expand Down
56 changes: 56 additions & 0 deletions crates/codecs/LICENSE-libwebp.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
Copyright (c) 2010, Google Inc. All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:

* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in
the documentation and/or other materials provided with the
distribution.

* Neither the name of Google nor the names of its contributors may
be used to endorse or promote products derived from this software
without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.


----- PATENTS -----

Additional IP Rights Grant (Patents)
------------------------------------

"These implementations" means the copyrightable works that implement the WebM
codecs distributed by Google as part of the WebM Project.

Google hereby grants to you a perpetual, worldwide, non-exclusive, no-charge,
royalty-free, irrevocable (except as stated in this section) patent license to
make, have made, use, offer to sell, sell, import, transfer, and otherwise
run, modify and propagate the contents of these implementations of WebM, where
such license applies only to those patent claims, both currently owned by
Google and acquired in the future, licensable by Google that are necessarily
infringed by these implementations of WebM. This grant does not include claims
that would be infringed only as a consequence of further modification of these
implementations. If you or your agent or exclusive licensee institute or order
or agree to the institution of patent litigation or any other patent
enforcement activity against any entity (including a cross-claim or
counterclaim in a lawsuit) alleging that any of these implementations of WebM
or any code incorporated within any of these implementations of WebM
constitute direct or contributory patent infringement, or inducement of
patent infringement, then any patent rights granted to you under this License
for these implementations of WebM shall terminate as of the date such
litigation is filed.
132 changes: 132 additions & 0 deletions crates/codecs/src/encode.rs
Original file line number Diff line number Diff line change
Expand Up @@ -394,6 +394,138 @@ pub fn encode_webp_lossless(img: &EncodeImage, meta: &EncodeMeta) -> Result<Vec<
Ok(out)
}

/// Whether this build writes lossy WebP ([`encode_webp_lossy`]): desktop builds with the `webp-lossy` feature.
pub const WEBP_LOSSY: bool = cfg!(all(feature = "webp-lossy", not(any(target_arch = "wasm32", target_os = "android"))));

/// Longest side a WebP file can have.
pub const WEBP_MAX_SIDE: u32 = 16383;

/// Encode lossy WebP (VP8, and VP8L-compressed alpha when the image has some) at `quality` 1..=100 through libwebp,
/// with `meta`'s ICC profile, EXIF and XMP in an extended (`VP8X`) file. Grey images are written as RGB. An error
/// for samples other than 8-bit, sides past [`WEBP_MAX_SIDE`], or a build without [`WEBP_LOSSY`].
pub fn encode_webp_lossy(img: &EncodeImage, quality: u8, meta: &EncodeMeta) -> Result<Vec<u8>> {
img.validate()?;
let Samples::U8(s) = img.samples else {
return Err(Error::Encode("WebP needs 8-bit samples".into()));
};
if img.width == 0 || img.height == 0 || img.width > WEBP_MAX_SIDE || img.height > WEBP_MAX_SIDE {
return Err(Error::Encode(format!("WebP images are at most {WEBP_MAX_SIDE} pixels a side ({} × {})", img.width, img.height)));
}
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();
if px.len() != n * if alpha { 4 } else { 3 } {
return Err(Error::Encode("WebP: fewer samples than the image needs".into()));
}
let bitstream = webp_lossy_bitstream(&px, alpha, img.width, img.height, quality.clamp(1, 100))?;
webp_with_metadata(&bitstream, img.width, img.height, meta)
}

#[cfg(all(feature = "webp-lossy", not(any(target_arch = "wasm32", target_os = "android"))))]
fn webp_lossy_bitstream(px: &[u8], alpha: bool, w: u32, h: u32, quality: u8) -> Result<Vec<u8>> {
let layout = if alpha { webp::PixelLayout::Rgba } else { webp::PixelLayout::Rgb };
// (the sizes were checked against `px` above: the wrapper's own check can't fail)
let enc = webp::Encoder::new(px, layout, w, h);
let out = enc.encode_simple(false, f32::from(quality)).map_err(|e| Error::Encode(format!("WebP: {e:?}")))?;
Ok(out.to_vec())
}

#[cfg(not(all(feature = "webp-lossy", not(any(target_arch = "wasm32", target_os = "android")))))]
fn webp_lossy_bitstream(_px: &[u8], _alpha: bool, _w: u32, _h: u32, _quality: u8) -> Result<Vec<u8>> {
Err(Error::Encode("lossy WebP is not available in this build (lossless WebP is)".into()))
}

/// A RIFF chunk: tag, little-endian size, payload, padded to an even length.
fn riff_chunk(out: &mut Vec<u8>, tag: &[u8; 4], payload: &[u8]) -> Result<()> {
let len = u32::try_from(payload.len()).map_err(|_| Error::Encode("WebP: a chunk over 4 GB".into()))?;
out.extend_from_slice(tag);
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(payload);
if payload.len() % 2 == 1 {
out.push(0);
}
Ok(())
}

/// The chunks of a WebP file after `RIFF size WEBP`, as (tag, payload); `None` when it isn't one.
fn webp_chunks(file: &[u8]) -> Option<Vec<([u8; 4], &[u8])>> {
if file.get(0..4)? != b"RIFF" || file.get(8..12)? != b"WEBP" {
return None;
}
let mut out = Vec::new();
let mut at = 12usize;
while at < file.len() {
let tag: [u8; 4] = file.get(at..at + 4)?.try_into().ok()?;
let len = u32::from_le_bytes(file.get(at + 4..at + 8)?.try_into().ok()?) as usize;
let body = file.get(at + 8..at.checked_add(8)?.checked_add(len)?)?;
out.push((tag, body));
at = at.checked_add(8)?.checked_add(len)?.checked_add(len % 2)?;
}
Some(out)
}

/// `bitstream` (a simple or extended WebP file from the encoder) rewritten as an extended file carrying `meta`'s
/// ICC profile, EXIF and XMP, in the order the WebP container specification gives (VP8X, ICCP, ALPH, VP8, EXIF, XMP).
/// Unchanged when `meta` has none of them.
fn webp_with_metadata(bitstream: &[u8], w: u32, h: u32, meta: &EncodeMeta) -> Result<Vec<u8>> {
let xmp = meta.xmp.map(str::as_bytes);
if meta.icc.is_none() && meta.exif.is_none() && xmp.is_none() {
return Ok(bitstream.to_vec());
}
let chunks = webp_chunks(bitstream).ok_or_else(|| Error::Encode("WebP: the encoder made no WebP file".into()))?;
let image: Vec<_> = chunks.iter().filter(|(t, _)| t == b"ALPH" || t == b"VP8 " || t == b"VP8L").collect();
let has_alpha = image.iter().any(|(t, _)| t == b"ALPH");
let mut flags = 0u8;
if meta.icc.is_some() {
flags |= 0x20;
}
if has_alpha {
flags |= 0x10;
}
if meta.exif.is_some() {
flags |= 0x08;
}
if xmp.is_some() {
flags |= 0x04;
}
let mut vp8x = vec![flags, 0, 0, 0];
vp8x.extend_from_slice(&(w.saturating_sub(1)).to_le_bytes()[..3]);
vp8x.extend_from_slice(&(h.saturating_sub(1)).to_le_bytes()[..3]);
let mut body = b"WEBP".to_vec();
riff_chunk(&mut body, b"VP8X", &vp8x)?;
if let Some(icc) = meta.icc {
riff_chunk(&mut body, b"ICCP", icc)?;
}
for (tag, payload) in image {
riff_chunk(&mut body, tag, payload)?;
}
if let Some(exif) = meta.exif {
riff_chunk(&mut body, b"EXIF", exif)?;
}
if let Some(xmp) = xmp {
riff_chunk(&mut body, b"XMP ", xmp)?;
}
let len = u32::try_from(body.len()).map_err(|_| Error::Encode("WebP: file over 4 GB".into()))?;
let mut out = b"RIFF".to_vec();
out.extend_from_slice(&len.to_le_bytes());
out.extend_from_slice(&body);
Ok(out)
}

/// Encode AVIF (sRGB, 4:4:4, 10-bit AV1) with `ravif` (rav1e). 8-bit samples are widened by the
/// encoder; 16-bit samples keep 10 bits of precision (BT.601 full-range YCbCr computed here).
/// `quality` 1..=100, `speed` 1 (slow) ..= 10. EXIF is embedded; ICC is not supported by the muxer
Expand Down
6 changes: 3 additions & 3 deletions crates/codecs/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -48,9 +48,9 @@ mod webp;

pub use avif_gainmap::encode_avif_gain_map;
pub use encode::{
ChromaSubsampling, EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, HLG_REFERENCE_PEAK_NITS, HdrTransfer, Samples, TiffCompression,
encode_avif, encode_avif_hdr, encode_avif_pq, encode_jpeg, encode_png, encode_png_pq, encode_psd, encode_tiff, encode_tiff_associated,
encode_webp_lossless, hlg_signal,
ChromaSubsampling, EncodeImage, EncodeMeta, HDR_REFERENCE_WHITE_NITS, HLG_REFERENCE_PEAK_NITS, HdrTransfer, Samples, TiffCompression, WEBP_LOSSY,
WEBP_MAX_SIDE, encode_avif, encode_avif_hdr, encode_avif_pq, encode_jpeg, encode_png, encode_png_pq, encode_psd, encode_tiff,
encode_tiff_associated, encode_webp_lossless, encode_webp_lossy, hlg_signal,
};
pub use exr_encode::{ACESCG, ExrOptions, encode_exr};
pub use jxl_encode::{JxlColour, JxlEffort, JxlOptions, encode_jxl, encode_jxl_gain_map};
Expand Down
47 changes: 47 additions & 0 deletions crates/codecs/tests/it/roundtrip.rs
Original file line number Diff line number Diff line change
Expand Up @@ -483,6 +483,53 @@ fn webp_lossless_exact() {
assert_eq!(d.xmp.as_deref(), Some("<w/>"));
}

/// Lossy WebP (#1482) decodes close to its source, keeps its metadata and alpha, gets smaller at a lower quality,
/// and refuses what WebP can't hold instead of panicking; a build without it says so.
#[test]
fn webp_lossy_close_with_metadata() {
let img = gradient(64, 48);
let icc = write_named(NamedSpace::Srgb);
let exif = minimal_exif(6);
let meta = EncodeMeta { icc: Some(&icc), exif: Some(&exif), xmp: Some("<w/>"), ..Default::default() };
let e = EncodeImage::rgba8(&img);
if !WEBP_LOSSY {
assert!(encode_webp_lossy(&e, 90, &meta).is_err());
return;
}
let bytes = encode_webp_lossy(&e, 90, &meta).unwrap();
assert_eq!(sniff(&bytes), Some(Format::WebP));
let d = decode(&bytes, DecodeOptions::default()).unwrap();
assert_eq!((d.image.width, d.image.height, d.orientation), (64, 48, 6));
assert_eq!(d.icc.as_deref(), Some(&icc[..]));
assert_eq!(d.xmp.as_deref(), Some("<w/>"));
let got = d.to_srgb8();
let err: f64 =
got.data.iter().zip(&img.data).flat_map(|(a, b)| (0..3).map(move |k| (a[k] as f64 - b[k] as f64).abs())).sum::<f64>() / (64.0 * 48.0 * 3.0);
assert!(err < 6.0, "mean error {err}");
// no metadata: the encoder's own file
let plain = encode_webp_lossy(&e, 90, &EncodeMeta::default()).unwrap();
assert!(decode(&plain, DecodeOptions::default()).is_ok());
// alpha survives
let mut see = img.clone();
see.data.iter_mut().enumerate().for_each(|(i, p)| p[3] = if i % 2 == 0 { 255 } else { 0 });
let a = encode_webp_lossy(&EncodeImage::rgba8(&see), 90, &meta).unwrap();
let d = decode(&a, DecodeOptions::default()).unwrap();
assert!(d.alpha.is_some(), "the transparency is kept");
// grey and RGB inputs
let grey = vec![128u8; 16 * 8];
assert!(encode_webp_lossy(&EncodeImage::new(16, 8, 1, Samples::U8(&grey)), 50, &meta).is_ok());
// a smaller file at a lower quality
let noisy: Vec<u8> = (0..128 * 96 * 3).map(|i| ((i * 7919) % 251) as u8).collect();
let n = EncodeImage::new(128, 96, 3, Samples::U8(&noisy));
assert!(encode_webp_lossy(&n, 20, &meta).unwrap().len() < encode_webp_lossy(&n, 95, &meta).unwrap().len());
// hostile: too wide, quality out of range, wrong depth
let wide = vec![0u8; (WEBP_MAX_SIDE as usize + 1) * 3];
assert!(encode_webp_lossy(&EncodeImage::new(WEBP_MAX_SIDE + 1, 1, 3, Samples::U8(&wide)), 90, &meta).is_err());
assert!(encode_webp_lossy(&n, 0, &meta).is_ok() && encode_webp_lossy(&n, 255, &meta).is_ok());
let deep = vec![0u16; 4 * 4 * 3];
assert!(encode_webp_lossy(&EncodeImage::new(4, 4, 3, Samples::U16(&deep)), 90, &meta).is_err());
}

#[test]
fn gif_and_bmp_decode() {
use image::ImageEncoder;
Expand Down
Loading
Loading