Skip to main content

y4m_codec/
lib.rs

1//! Streaming reader and writer for the YUV4MPEG2 (`.y4m`) uncompressed
2//! planar video format.
3//!
4//! The decoder works over any [`std::io::Read`] and the encoder over any
5//! [`std::io::Write`]. Design points:
6//!
7//! - **Borrowed frames.** [`Decoder::read_frame`] returns a [`FrameRef`]
8//!   borrowing one reusable internal buffer, so the decode and encode hot
9//!   paths reuse the same storage for every frame. The counting-allocator
10//!   test `tests/zero_alloc.rs` pins both loops at zero heap allocations.
11//! - **Defined endianness.** Samples deeper than 8 bits are little-endian on
12//!   the wire on every host. [`FrameRef::plane_u16`] yields host-order
13//!   samples, and [`Encoder::write_frame_u16`] converts host-order samples to
14//!   little-endian wire bytes.
15//! - **Byte-exact round-trips.** Raw header and frame parameter bytes are
16//!   preserved verbatim, so decode followed by re-encode reproduces the
17//!   input byte-for-byte.
18//! - **Typed errors.** Malformed, truncated, or over-budget input yields a
19//!   matching [`Error`] variant, and all size arithmetic is checked.
20//!
21//! # Reading
22//!
23//! ```
24//! use y4m_codec::{Decoder, Error};
25//!
26//! let data: &[u8] = b"YUV4MPEG2 W2 H2 F25:1 C420\nFRAME\n\x00\x01\x02\x03\x80\x80";
27//! let mut decoder = Decoder::new(data)?;
28//! assert_eq!((decoder.width(), decoder.height()), (2, 2));
29//! let frame = decoder.read_frame()?;
30//! assert_eq!(frame.y(), &[0x00, 0x01, 0x02, 0x03]);
31//! assert!(matches!(decoder.read_frame(), Err(Error::EndOfStream)));
32//! # Ok::<(), y4m_codec::Error>(())
33//! ```
34//!
35//! # Writing
36//!
37//! ```
38//! use y4m_codec::{EncoderBuilder, Ratio};
39//!
40//! let mut out = Vec::new();
41//! let mut encoder = EncoderBuilder::new(2, 2, Ratio::new(25, 1)).write_header(&mut out)?;
42//! encoder.write_frame([&[0, 1, 2, 3], &[0x80], &[0x80]])?;
43//! assert!(out.starts_with(b"YUV4MPEG2 W2 H2 F25:1 C420\nFRAME\n"));
44//! # Ok::<(), y4m_codec::Error>(())
45//! ```
46
47#![forbid(unsafe_code)]
48#![deny(missing_docs)]
49
50mod colorspace;
51mod decode;
52mod encode;
53mod error;
54
55pub use colorspace::{ChromaSiting, Colorspace, Subsampling};
56pub use decode::{Decoder, FrameRef, Limits};
57pub use encode::{Encoder, EncoderBuilder};
58pub use error::Error;
59
60/// An exact rational value, used for the `F` (framerate) and `A` (pixel
61/// aspect) header tags. `0:0` is the unknown-aspect sentinel.
62#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
63pub struct Ratio {
64    /// Numerator.
65    pub num: u32,
66    /// Denominator.
67    pub den: u32,
68}
69
70impl Ratio {
71    /// Builds a ratio from numerator and denominator.
72    pub const fn new(num: u32, den: u32) -> Self {
73        Ratio { num, den }
74    }
75}
76
77impl std::fmt::Display for Ratio {
78    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
79        write!(f, "{}:{}", self.num, self.den)
80    }
81}
82
83/// Interlacing mode from the stream header `I` tag.
84///
85/// Metadata only: plane layout is unaffected, and an absent tag reads as
86/// [`Interlace::Unknown`], treated as progressive.
87#[non_exhaustive]
88#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
89pub enum Interlace {
90    /// `Ip`: progressive.
91    Progressive,
92    /// `It`: top field first.
93    TopFirst,
94    /// `Ib`: bottom field first.
95    BottomFirst,
96    /// `Im`: mixed, with per-frame `I` parameters describing each frame.
97    Mixed,
98    /// `I?` or tag absent: unknown.
99    Unknown,
100}