1mod color;
21mod container;
22
23use std::fmt;
24
25use crate::av1::{self, Av1Error, Bitstream, ChromaSampling, ColorDescription, Picture};
26use container::Item;
27
28pub const MAX_SIDE: u32 = 32768;
30pub const MAX_PIXELS: u64 = 16384 * 16384;
32
33#[rustfmt::skip]
36const COLOR_QUANTIZERS: [u8; 100] = [
37 63, 63, 63, 62, 62, 62, 61, 61, 60, 60, 59, 59, 58, 58, 57, 57, 56, 56, 55, 55,
38 54, 54, 53, 53, 52, 52, 51, 51, 50, 50, 49, 49, 48, 48, 47, 46, 46, 45, 45, 44,
39 43, 43, 42, 42, 41, 40, 40, 39, 39, 38, 37, 37, 36, 36, 35, 34, 33, 33, 32, 31,
40 30, 30, 29, 28, 27, 27, 26, 25, 24, 24, 23, 22, 21, 21, 20, 19, 18, 18, 17, 16,
41 15, 15, 14, 13, 12, 12, 11, 10, 9, 9, 8, 7, 6, 6, 5, 4, 3, 3, 2, 1,
42];
43
44#[derive(Clone, Copy, Debug, PartialEq, Eq)]
46pub struct AvifOptions {
47 pub quality: u8,
50 pub subsampling: ChromaSampling,
53}
54
55impl Default for AvifOptions {
56 fn default() -> Self {
58 Self {
59 quality: 75,
60 subsampling: ChromaSampling::Yuv420,
61 }
62 }
63}
64
65#[derive(Clone, Debug, PartialEq, Eq)]
67pub enum AvifError {
68 Size {
71 width: u32,
73 height: u32,
75 },
76 DataLength,
78 Quality(u8),
80 Av1(Av1Error),
82}
83
84impl fmt::Display for AvifError {
85 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
86 match self {
87 Self::Size { width, height } => write!(f, "cannot write a {width}×{height} AVIF"),
88 Self::DataLength => f.write_str("the pixel data does not match the image size"),
89 Self::Quality(quality) => write!(f, "invalid AVIF quality {quality} (0 to 100)"),
90 Self::Av1(err) => write!(f, "cannot encode the AV1 picture: {err}"),
91 }
92 }
93}
94
95impl std::error::Error for AvifError {
96 fn source(&self) -> Option<&(dyn std::error::Error + 'static)> {
97 match self {
98 Self::Av1(err) => Some(err),
99 _ => None,
100 }
101 }
102}
103
104impl From<Av1Error> for AvifError {
105 fn from(err: Av1Error) -> Self {
106 Self::Av1(err)
107 }
108}
109
110fn qindex(quantizer: u8) -> u8 {
112 match quantizer {
113 0..=61 => quantizer * 4,
114 62 => 249,
115 _ => 255,
116 }
117}
118
119fn color_qindex(quality: u8) -> u8 {
121 qindex(COLOR_QUANTIZERS[usize::from(quality)])
122}
123
124fn alpha_qindex(quality: u8) -> u8 {
127 let quantizer = ((100 - u32::from(quality)) * 63 + 50) / 100;
128 qindex(quantizer as u8)
129}
130
131pub fn encode_rgba8(
140 width: u32,
141 height: u32,
142 pixels: &[u8],
143 options: &AvifOptions,
144) -> Result<Vec<u8>, AvifError> {
145 let area = u64::from(width) * u64::from(height);
146 if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE || area > MAX_PIXELS {
147 return Err(AvifError::Size { width, height });
148 }
149 if usize::try_from(area * 4) != Ok(pixels.len()) {
150 return Err(AvifError::DataLength);
151 }
152 if options.quality > 100 {
153 return Err(AvifError::Quality(options.quality));
154 }
155 let (w, h) = (width as usize, height as usize);
156 let lossless = options.quality == 100;
157 let (planes, sampling, description, qindex) = if lossless {
158 let planes = color::identity(pixels);
159 (
160 planes,
161 ChromaSampling::Yuv444,
162 ColorDescription::SRGB_IDENTITY,
163 0,
164 )
165 } else {
166 let planes = color::bt601(w, h, pixels, options.subsampling);
167 let qindex = color_qindex(options.quality);
168 (
169 planes,
170 options.subsampling,
171 ColorDescription::SRGB_BT601,
172 qindex,
173 )
174 };
175 let plane_slices: Vec<&[u8]> = [&planes.y, &planes.u, &planes.v]
176 .into_iter()
177 .take(sampling.planes())
178 .map(Vec::as_slice)
179 .collect();
180 let picture =
181 Picture::new(width, height, sampling, &plane_slices)?.with_color(description, true)?;
182 let color_stream = av1::encode(&picture, qindex);
183 let alpha = color::alpha(pixels);
184 let alpha_stream: Option<Bitstream> = if alpha.iter().all(|&a| a == 255) {
185 None
186 } else {
187 let picture = Picture::new(width, height, ChromaSampling::Monochrome, &[&alpha])?;
188 let qindex = if lossless {
189 0
190 } else {
191 alpha_qindex(options.quality)
192 };
193 Some(av1::encode(&picture, qindex))
194 };
195 let mut items = vec![Item {
196 bitstream: &color_stream,
197 color: Some((description, true)),
198 }];
199 if let Some(stream) = &alpha_stream {
200 items.push(Item {
201 bitstream: stream,
202 color: None,
203 });
204 }
205 Ok(container::write((width, height), &items))
206}
207
208#[cfg(test)]
209mod tests {
210 use super::*;
211
212 #[test]
213 fn qualities_map_as_libavif_maps_them() {
214 assert_eq!(color_qindex(75), 76);
215 assert_eq!(color_qindex(0), 255);
216 assert_eq!(color_qindex(60), 120);
217 assert_eq!(alpha_qindex(75), 64);
218 assert_eq!(alpha_qindex(0), 255);
219 assert_eq!(alpha_qindex(99), 4);
220 }
221
222 #[test]
223 fn inputs_are_checked() {
224 let options = AvifOptions::default();
225 assert_eq!(
226 encode_rgba8(0, 1, &[], &options),
227 Err(AvifError::Size {
228 width: 0,
229 height: 1
230 })
231 );
232 let huge = encode_rgba8(MAX_SIDE + 1, 1, &[], &options);
233 assert!(matches!(huge, Err(AvifError::Size { .. })));
234 assert_eq!(
235 encode_rgba8(1, 1, &[0; 3], &options),
236 Err(AvifError::DataLength)
237 );
238 let bad = AvifOptions {
239 quality: 101,
240 ..options
241 };
242 assert_eq!(
243 encode_rgba8(1, 1, &[0; 4], &bad),
244 Err(AvifError::Quality(101))
245 );
246 }
247
248 #[test]
249 fn alpha_is_stored_only_when_some_pixel_is_translucent() {
250 let options = AvifOptions::default();
251 let opaque = encode_rgba8(2, 2, &[90, 20, 30, 255].repeat(4), &options).unwrap();
252 let translucent = encode_rgba8(2, 2, &[90, 20, 30, 254].repeat(4), &options).unwrap();
253 let has_alpha = |file: &[u8]| file.windows(4).any(|w| w == b"auxC");
254 assert!(!has_alpha(&opaque));
255 assert!(has_alpha(&translucent));
256 }
257}