#![doc = include_str!("../README.md")]
#![no_std]
#![forbid(unsafe_code)]
#[cfg(feature = "alloc")]
extern crate alloc;
#[cfg(any(feature = "std", test))]
extern crate std;
mod audio;
#[cfg(feature = "std")]
pub use audio::AudioDecoder;
pub use audio::{
AudioBufferRequirements, AudioInfo, AudioLimits, AudioPacketDecoder, AudioPacketMode,
SliceAudioDecoder,
};
mod container;
mod entropy;
mod error;
mod storage;
mod syntax;
mod video;
#[cfg(feature = "std")]
pub use container::VideoDecoder;
pub use container::{Header, SliceVideoDecoder};
pub use error::{BufferKind, Error};
pub use syntax::BlockState;
pub use video::{VideoBuffers, VideoPacketDecoder};
pub type BorrowedVideoPacketDecoder<'a> = VideoPacketDecoder<&'a mut [u8], &'a mut [BlockState]>;
#[cfg(feature = "alloc")]
pub type OwnedVideoPacketDecoder =
VideoPacketDecoder<alloc::vec::Vec<u8>, alloc::vec::Vec<BlockState>>;
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum Version {
V13,
V15,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
#[repr(u16)]
pub enum FrameType {
I = 0x10,
P = 0x20,
B = 0x30,
}
impl TryFrom<u16> for FrameType {
type Error = Error;
fn try_from(value: u16) -> Result<Self, Error> {
match value {
0x10 => Ok(Self::I),
0x20 => Ok(Self::P),
0x30 => Ok(Self::B),
_ => Err(Error::Invalid("unknown frame type")),
}
}
}
#[derive(Debug, Clone, Copy)]
pub struct VideoLimits {
pub max_pixels: usize,
pub max_frame_bytes: usize,
}
impl Default for VideoLimits {
fn default() -> Self {
Self {
max_pixels: 4096 * 4096,
max_frame_bytes: 64 * 1024 * 1024,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ChromaSampling {
Yuv444,
Yuv422,
Yuv420,
}
impl ChromaSampling {
pub const fn horizontal_factor(self) -> u8 {
match self {
Self::Yuv444 => 1,
Self::Yuv422 | Self::Yuv420 => 2,
}
}
pub const fn vertical_factor(self) -> u8 {
match self {
Self::Yuv444 | Self::Yuv422 => 1,
Self::Yuv420 => 2,
}
}
}
impl TryFrom<(u8, u8)> for ChromaSampling {
type Error = Error;
fn try_from(factors: (u8, u8)) -> Result<Self, Error> {
match factors {
(1, 1) => Ok(Self::Yuv444),
(2, 1) => Ok(Self::Yuv422),
(2, 2) => Ok(Self::Yuv420),
_ => Err(Error::Invalid(
"unsupported chroma sampling (expected 4:4:4, 4:2:2 or 4:2:0)",
)),
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VideoBufferRequirements {
pub frame_bytes: usize,
pub block_states: usize,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct VideoInfo {
version: Version,
width: u16,
height: u16,
sampling: ChromaSampling,
}
impl VideoInfo {
pub fn new(
version: Version,
width: u16,
height: u16,
sampling: ChromaSampling,
) -> Result<Self, Error> {
if width == 0 || height == 0 || !width.is_multiple_of(8) || !height.is_multiple_of(8) {
return Err(Error::Invalid(
"dimensions must be nonzero multiples of eight",
));
}
let pixels = usize::from(width)
.checked_mul(usize::from(height))
.ok_or(Error::Limit("pixel count"))?;
if pixels > isize::MAX as usize / 9 {
return Err(Error::Limit("pixel count"));
}
Ok(Self {
version,
width,
height,
sampling,
})
}
pub const fn version(self) -> Version {
self.version
}
pub const fn width(self) -> u16 {
self.width
}
pub const fn height(self) -> u16 {
self.height
}
pub const fn sampling(self) -> ChromaSampling {
self.sampling
}
pub fn buffer_requirements(self) -> VideoBufferRequirements {
let width = usize::from(self.width);
let height = usize::from(self.height);
let chroma_width = width / usize::from(self.sampling.horizontal_factor());
let chroma_height = height / usize::from(self.sampling.vertical_factor());
VideoBufferRequirements {
frame_bytes: width * height + 2 * chroma_width * chroma_height,
block_states: (width / 4 + 2) * (height / 4 + 2)
+ 2 * (chroma_width / 4 + 2) * (chroma_height / 4 + 2),
}
}
pub fn rgb_buffer_size(self) -> usize {
usize::from(self.width) * usize::from(self.height) * 3
}
pub fn validate_limits(self, limits: VideoLimits) -> Result<(), Error> {
if usize::from(self.width) * usize::from(self.height) > limits.max_pixels {
return Err(Error::Limit("pixel count"));
}
Ok(())
}
}
#[derive(Debug, Clone, Copy)]
pub struct Plane<'a> {
data: &'a [u8],
width: usize,
height: usize,
}
impl<'a> Plane<'a> {
pub const fn data(self) -> &'a [u8] {
self.data
}
pub const fn width(self) -> usize {
self.width
}
pub const fn height(self) -> usize {
self.height
}
}
#[derive(Debug, Clone, Copy)]
pub struct Frame<'a> {
display_index: u32,
kind: FrameType,
info: VideoInfo,
y: Plane<'a>,
u: Plane<'a>,
v: Plane<'a>,
}
impl<'a> Frame<'a> {
pub fn from_planes(
info: VideoInfo,
kind: FrameType,
display_index: u32,
planes: [&'a [u8]; 3],
) -> Result<Self, Error> {
let width = usize::from(info.width);
let height = usize::from(info.height);
let cw = width / usize::from(info.sampling.horizontal_factor());
let ch = height / usize::from(info.sampling.vertical_factor());
if planes[0].len() != width * height
|| planes[1].len() != cw * ch
|| planes[2].len() != cw * ch
{
return Err(Error::Invalid("plane lengths disagree with video layout"));
}
Ok(Self {
info,
kind,
display_index,
y: Plane {
data: planes[0],
width,
height,
},
u: Plane {
data: planes[1],
width: cw,
height: ch,
},
v: Plane {
data: planes[2],
width: cw,
height: ch,
},
})
}
pub(crate) fn new(
info: VideoInfo,
kind: FrameType,
display_index: u32,
data: &'a [u8],
) -> Result<Self, Error> {
let width = usize::from(info.width);
let height = usize::from(info.height);
let cw = width / usize::from(info.sampling.horizontal_factor());
let ch = height / usize::from(info.sampling.vertical_factor());
let (y, rest) = data
.split_at_checked(width * height)
.ok_or(Error::Truncated)?;
let (u, v) = rest.split_at_checked(cw * ch).ok_or(Error::Truncated)?;
Self::from_planes(info, kind, display_index, [y, u, v])
}
pub const fn display_index(self) -> u32 {
self.display_index
}
pub const fn kind(self) -> FrameType {
self.kind
}
pub const fn info(self) -> VideoInfo {
self.info
}
pub const fn y(self) -> Plane<'a> {
self.y
}
pub const fn u(self) -> Plane<'a> {
self.u
}
pub const fn v(self) -> Plane<'a> {
self.v
}
pub const fn planes(self) -> [Plane<'a>; 3] {
[self.y, self.u, self.v]
}
pub fn rgb_buffer_size(self) -> usize {
self.info.rgb_buffer_size()
}
pub fn to_rgb_into(&self, output: &mut [u8]) -> Result<(), Error> {
let required = self.rgb_buffer_size();
if output.len() < required {
return Err(Error::BufferTooSmall {
buffer: BufferKind::Rgb,
required,
provided: output.len(),
});
}
let output = &mut output[..required];
let hs = usize::from(self.info.sampling.horizontal_factor());
let vs = usize::from(self.info.sampling.vertical_factor());
for row in 0..self.y.height {
for col in 0..self.y.width {
let pos = row * self.y.width + col;
let uv = (row / vs) * self.u.width + col / hs;
let y = f32::from(self.y.data[pos]);
let u = f32::from(self.u.data[uv]) - 128.0;
let v = f32::from(self.v.data[uv]) - 128.0;
output[pos * 3] = (y + 1.402 * v) as u8;
output[pos * 3 + 1] = (y - 0.34414 * u - 0.71414 * v) as u8;
output[pos * 3 + 2] = (y + 1.772 * u) as u8;
}
}
Ok(())
}
#[cfg(feature = "alloc")]
pub fn to_rgb(&self, output: &mut alloc::vec::Vec<u8>) -> Result<(), Error> {
let required = self.rgb_buffer_size();
output.try_reserve(required.saturating_sub(output.len()))?;
output.resize(required, 0);
self.to_rgb_into(output)
}
#[cfg(feature = "std")]
pub fn write_ppm<W: std::io::Write>(
&self,
mut writer: W,
scratch: &mut alloc::vec::Vec<u8>,
) -> Result<(), Error> {
self.to_rgb(scratch)?;
write!(writer, "P6\n{} {}\n255\n", self.y.width, self.y.height)?;
writer.write_all(scratch)?;
Ok(())
}
#[cfg(feature = "std")]
pub fn write_yuv<W: std::io::Write>(&self, mut writer: W) -> Result<(), Error> {
writer.write_all(self.y.data)?;
writer.write_all(self.u.data)?;
writer.write_all(self.v.data)?;
Ok(())
}
}