mod bit_writer;
mod block;
mod cdf;
mod coeffs;
mod context;
mod delta_q;
mod entropy;
mod headers;
mod mode_info;
mod palette;
mod plane;
mod predict;
mod quant;
mod search;
mod syntax;
mod tables;
mod tile;
mod transform;
use std::fmt;
use self::coeffs::Scans;
use self::context::Contexts;
use self::headers::{OBU_FRAME, OBU_SEQUENCE_HEADER, Sequence, TILE_SIZE_BYTES, TileLayout};
use self::plane::Plane;
use self::quant::Quantizer;
use self::tile::{Frame, TileBounds, encode_tile};
use self::transform::Bases;
pub const MAX_SIDE: u32 = 1 << 16;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ColorDescription {
pub primaries: u8,
pub transfer: u8,
pub matrix: u8,
}
impl ColorDescription {
pub const SRGB_BT601: Self = Self {
primaries: 1,
transfer: 13,
matrix: 6,
};
pub const SRGB_IDENTITY: Self = Self {
primaries: 1,
transfer: 13,
matrix: 0,
};
pub(crate) fn is_srgb_identity(self) -> bool {
self == Self::SRGB_IDENTITY
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ChromaSampling {
Monochrome,
Yuv420,
Yuv444,
}
impl ChromaSampling {
pub const fn subsampling(self) -> (u32, u32) {
match self {
Self::Monochrome | Self::Yuv420 => (1, 1),
Self::Yuv444 => (0, 0),
}
}
pub const fn planes(self) -> usize {
match self {
Self::Monochrome => 1,
Self::Yuv420 | Self::Yuv444 => 3,
}
}
pub const fn profile(self) -> u8 {
match self {
Self::Monochrome | Self::Yuv420 => 0,
Self::Yuv444 => 1,
}
}
fn plane_size(self, plane: usize, width: u32, height: u32) -> (usize, usize) {
let (ss_x, ss_y) = if plane == 0 {
(0, 0)
} else {
self.subsampling()
};
(
width.div_ceil(1 << ss_x) as usize,
height.div_ceil(1 << ss_y) as usize,
)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub enum Av1Error {
Size {
width: u32,
height: u32,
},
Planes,
IdentityNeeds444,
}
impl fmt::Display for Av1Error {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
match self {
Self::Size { width, height } => {
write!(f, "a {width}×{height} picture cannot be coded in AV1")
}
Self::Planes => f.write_str("the planes do not match the picture's size and sampling"),
Self::IdentityNeeds444 => {
f.write_str("the identity matrix needs 4:4:4 chroma sampling")
}
}
}
}
impl std::error::Error for Av1Error {}
#[derive(Clone, Debug)]
pub struct Picture<'a> {
width: u32,
height: u32,
sampling: ChromaSampling,
planes: Vec<&'a [u8]>,
color: Option<ColorDescription>,
full_range: bool,
}
impl<'a> Picture<'a> {
pub fn new(
width: u32,
height: u32,
sampling: ChromaSampling,
planes: &[&'a [u8]],
) -> Result<Self, Av1Error> {
if width == 0 || height == 0 || width > MAX_SIDE || height > MAX_SIDE {
return Err(Av1Error::Size { width, height });
}
let lengths_match = planes.iter().enumerate().all(|(plane, samples)| {
let (w, h) = sampling.plane_size(plane, width, height);
samples.len() == w * h
});
if planes.len() != sampling.planes() || !lengths_match {
return Err(Av1Error::Planes);
}
Ok(Self {
width,
height,
sampling,
planes: planes.to_vec(),
color: None,
full_range: true,
})
}
pub fn with_color(
mut self,
color: ColorDescription,
full_range: bool,
) -> Result<Self, Av1Error> {
if color.is_srgb_identity() && (self.sampling != ChromaSampling::Yuv444 || !full_range) {
return Err(Av1Error::IdentityNeeds444);
}
self.color = Some(color);
self.full_range = full_range;
Ok(self)
}
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Bitstream {
pub data: Vec<u8>,
pub profile: u8,
pub level: u8,
pub sampling: ChromaSampling,
}
pub fn encode(picture: &Picture<'_>, qindex: u8) -> Bitstream {
let (width, height) = (picture.width, picture.height);
let sampling = picture.sampling;
let ss = sampling.subsampling();
let mi = (
2 * width.div_ceil(8) as usize,
2 * height.div_ceil(8) as usize,
);
let superblocks = (mi.0.div_ceil(16), mi.1.div_ceil(16));
let source: Vec<Plane> = picture
.planes
.iter()
.enumerate()
.map(|(plane, samples)| {
let (ss_x, ss_y) = if plane == 0 { (0, 0) } else { ss };
let padded = ((superblocks.0 * 64) >> ss_x, (superblocks.1 * 64) >> ss_y);
Plane::padded(samples, sampling.plane_size(plane, width, height), padded)
})
.collect();
let recon = source.iter().map(Plane::blank_like).collect();
let quantizer = Quantizer::new(qindex, ss);
let delta_q_res = (qindex > 0).then(|| delta_q::resolution_log2(qindex));
let mut frame = Frame {
source,
recon,
ss,
mi,
quantizer,
delta_q_res,
bases: Bases::new(),
scans: Scans::new(),
};
let mut contexts = Contexts::new((superblocks.0 * 16, superblocks.1 * 16), ss);
let layout = TileLayout::new(mi.0, mi.1);
let chroma_delta = (sampling.planes() > 1).then(|| quantizer.chroma_delta());
let mut payload = headers::frame_header(qindex, chroma_delta, delta_q_res, &layout);
let count = layout.count();
let mut index = 0;
for rows in layout.row_starts.windows(2) {
for cols in layout.col_starts.windows(2) {
let bounds = TileBounds {
rows: (rows[0], rows[1]),
cols: (cols[0], cols[1]),
};
let tile = encode_tile(&mut frame, &mut contexts, bounds);
index += 1;
if index < count {
let size = u32::try_from(tile.len() - 1)
.expect("a tile of at most 4096 × 2304 samples codes in less than 4 GiB");
payload.extend_from_slice(&size.to_le_bytes()[..TILE_SIZE_BYTES]);
}
payload.extend(tile);
}
}
let sequence = Sequence {
profile: sampling.profile(),
level: headers::level(width, height),
size: (width, height),
monochrome: sampling == ChromaSampling::Monochrome,
color: picture.color,
full_range: picture.full_range,
};
let mut data = headers::obu(OBU_SEQUENCE_HEADER, &sequence.header());
data.extend(headers::obu(OBU_FRAME, &payload));
Bitstream {
data,
profile: sequence.profile,
level: sequence.level,
sampling,
}
}
#[cfg(test)]
mod tests;