1mod bit_writer;
29mod block;
30mod cdf;
31mod coeffs;
32mod context;
33mod delta_q;
34mod entropy;
35mod headers;
36mod mode_info;
37mod palette;
38mod plane;
39mod predict;
40mod quant;
41mod search;
42mod syntax;
43mod tables;
44mod tile;
45mod transform;
46
47use std::fmt;
48
49use self::coeffs::Scans;
50use self::context::Contexts;
51use self::headers::{OBU_FRAME, OBU_SEQUENCE_HEADER, Sequence, TILE_SIZE_BYTES, TileLayout};
52use self::plane::Plane;
53use self::quant::Quantizer;
54use self::tile::{Frame, TileBounds, encode_tile};
55use self::transform::Bases;
56
57pub const MAX_SIDE: u32 = 1 << 16;
59
60#[derive(Clone, Copy, Debug, PartialEq, Eq)]
64pub struct ColorDescription {
65 pub primaries: u8,
67 pub transfer: u8,
69 pub matrix: u8,
72}
73
74impl ColorDescription {
75 pub const SRGB_BT601: Self = Self {
77 primaries: 1,
78 transfer: 13,
79 matrix: 6,
80 };
81
82 pub const SRGB_IDENTITY: Self = Self {
84 primaries: 1,
85 transfer: 13,
86 matrix: 0,
87 };
88
89 pub(crate) fn is_srgb_identity(self) -> bool {
92 self == Self::SRGB_IDENTITY
93 }
94}
95
96#[derive(Clone, Copy, Debug, PartialEq, Eq)]
98pub enum ChromaSampling {
99 Monochrome,
101 Yuv420,
103 Yuv444,
105}
106
107impl ChromaSampling {
108 pub const fn subsampling(self) -> (u32, u32) {
110 match self {
111 Self::Monochrome | Self::Yuv420 => (1, 1),
112 Self::Yuv444 => (0, 0),
113 }
114 }
115
116 pub const fn planes(self) -> usize {
118 match self {
119 Self::Monochrome => 1,
120 Self::Yuv420 | Self::Yuv444 => 3,
121 }
122 }
123
124 pub const fn profile(self) -> u8 {
127 match self {
128 Self::Monochrome | Self::Yuv420 => 0,
129 Self::Yuv444 => 1,
130 }
131 }
132
133 fn plane_size(self, plane: usize, width: u32, height: u32) -> (usize, usize) {
135 let (ss_x, ss_y) = if plane == 0 {
136 (0, 0)
137 } else {
138 self.subsampling()
139 };
140 (
141 width.div_ceil(1 << ss_x) as usize,
142 height.div_ceil(1 << ss_y) as usize,
143 )
144 }
145}
146
147#[derive(Clone, Debug, PartialEq, Eq)]
149pub enum Av1Error {
150 Size {
152 width: u32,
154 height: u32,
156 },
157 Planes,
160 IdentityNeeds444,
162}
163
164impl fmt::Display for Av1Error {
165 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
166 match self {
167 Self::Size { width, height } => {
168 write!(f, "a {width}×{height} picture cannot be coded in AV1")
169 }
170 Self::Planes => f.write_str("the planes do not match the picture's size and sampling"),
171 Self::IdentityNeeds444 => {
172 f.write_str("the identity matrix needs 4:4:4 chroma sampling")
173 }
174 }
175 }
176}
177
178impl std::error::Error for Av1Error {}
179
180#[derive(Clone, Debug)]
183pub struct Picture<'a> {
184 width: u32,
185 height: u32,
186 sampling: ChromaSampling,
187 planes: Vec<&'a [u8]>,
188 color: Option<ColorDescription>,
189 full_range: bool,
190}
191
192impl<'a> Picture<'a> {
193 pub fn new(
201 width: u32,
202 height: u32,
203 sampling: ChromaSampling,
204 planes: &[&'a [u8]],
205 ) -> Result<Self, Av1Error> {
206 if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {
207 return Err(Av1Error::Size { width, height });
208 }
209 let lengths_match = planes.iter().enumerate().all(|(plane, samples)| {
210 let (w, h) = sampling.plane_size(plane, width, height);
211 samples.len() == w * h
212 });
213 if planes.len() != sampling.planes() || !lengths_match {
214 return Err(Av1Error::Planes);
215 }
216 Ok(Self {
217 width,
218 height,
219 sampling,
220 planes: planes.to_vec(),
221 color: None,
222 full_range: true,
223 })
224 }
225
226 pub fn with_color(
234 mut self,
235 color: ColorDescription,
236 full_range: bool,
237 ) -> Result<Self, Av1Error> {
238 if color.is_srgb_identity() && (self.sampling != ChromaSampling::Yuv444 || !full_range) {
239 return Err(Av1Error::IdentityNeeds444);
240 }
241 self.color = Some(color);
242 self.full_range = full_range;
243 Ok(self)
244 }
245}
246
247#[derive(Clone, Debug, PartialEq, Eq)]
249pub struct Bitstream {
250 pub data: Vec<u8>,
252 pub profile: u8,
254 pub level: u8,
256 pub sampling: ChromaSampling,
258}
259
260pub fn encode(picture: &Picture<'_>, qindex: u8) -> Bitstream {
264 let (width, height) = (picture.width, picture.height);
265 let sampling = picture.sampling;
266 let ss = sampling.subsampling();
267 let mi = (
268 2 * width.div_ceil(8) as usize,
269 2 * height.div_ceil(8) as usize,
270 );
271 let superblocks = (mi.0.div_ceil(16), mi.1.div_ceil(16));
272 let source: Vec<Plane> = picture
273 .planes
274 .iter()
275 .enumerate()
276 .map(|(plane, samples)| {
277 let (ss_x, ss_y) = if plane == 0 { (0, 0) } else { ss };
278 let padded = ((superblocks.0 * 64) >> ss_x, (superblocks.1 * 64) >> ss_y);
279 Plane::padded(samples, sampling.plane_size(plane, width, height), padded)
280 })
281 .collect();
282 let recon = source.iter().map(Plane::blank_like).collect();
283 let quantizer = Quantizer::new(qindex, ss);
284 let delta_q_res = (qindex > 0).then(|| delta_q::resolution_log2(qindex));
285 let mut frame = Frame {
286 source,
287 recon,
288 ss,
289 mi,
290 quantizer,
291 delta_q_res,
292 bases: Bases::new(),
293 scans: Scans::new(),
294 };
295 let mut contexts = Contexts::new((superblocks.0 * 16, superblocks.1 * 16), ss);
296 let layout = TileLayout::new(mi.0, mi.1);
297 let chroma_delta = (sampling.planes() > 1).then(|| quantizer.chroma_delta());
298 let mut payload = headers::frame_header(qindex, chroma_delta, delta_q_res, &layout);
299 let count = layout.count();
300 let mut index = 0;
301 for rows in layout.row_starts.windows(2) {
302 for cols in layout.col_starts.windows(2) {
303 let bounds = TileBounds {
304 rows: (rows[0], rows[1]),
305 cols: (cols[0], cols[1]),
306 };
307 let tile = encode_tile(&mut frame, &mut contexts, bounds);
308 index += 1;
309 if index < count {
310 let size = u32::try_from(tile.len() - 1)
311 .expect("a tile of at most 4096 × 2304 samples codes in less than 4 GiB");
312 payload.extend_from_slice(&size.to_le_bytes()[..TILE_SIZE_BYTES]);
313 }
314 payload.extend(tile);
315 }
316 }
317 let sequence = Sequence {
318 profile: sampling.profile(),
319 level: headers::level(width, height),
320 size: (width, height),
321 monochrome: sampling == ChromaSampling::Monochrome,
322 color: picture.color,
323 full_range: picture.full_range,
324 };
325 let mut data = headers::obu(OBU_SEQUENCE_HEADER, &sequence.header());
326 data.extend(headers::obu(OBU_FRAME, &payload));
327 Bitstream {
328 data,
329 profile: sequence.profile,
330 level: sequence.level,
331 sampling,
332 }
333}
334
335#[cfg(test)]
336mod tests;