Skip to main content

y4m_codec/
encode.rs

1//! Streaming encoder over any [`Write`].
2
3use std::io::Write;
4
5use crate::colorspace::Colorspace;
6use crate::decode::{
7    is_forbidden_param_byte, parse_stream_params, validate_param_list, MAX_HEADER_LINE,
8};
9use crate::{Error, Interlace, Ratio};
10
11/// Builds a stream header and produces an [`Encoder`].
12///
13/// Canonical emit order: `W`, `H`, `F`, `I`, `A`, `C`, then `X*` in
14/// insertion order. Tags with no value set are omitted. `A0:0` is the one
15/// legal sentinel and is emitted when set explicitly.
16#[derive(Debug, Clone)]
17pub struct EncoderBuilder {
18    width: usize,
19    height: usize,
20    framerate: Ratio,
21    colorspace: Colorspace,
22    pixel_aspect: Option<Ratio>,
23    interlace: Option<Interlace>,
24    extensions: Vec<Vec<u8>>,
25    raw: Option<Vec<u8>>,
26}
27
28impl EncoderBuilder {
29    /// Starts a builder with the three required stream parameters.
30    pub fn new(width: usize, height: usize, framerate: Ratio) -> Self {
31        EncoderBuilder {
32            width,
33            height,
34            framerate,
35            colorspace: Colorspace::C420,
36            pixel_aspect: None,
37            interlace: None,
38            extensions: Vec::new(),
39            raw: None,
40        }
41    }
42
43    /// Sets the colorspace tag. Default: plain `C420`.
44    pub fn colorspace(mut self, cs: Colorspace) -> Self {
45        self.colorspace = cs;
46        self
47    }
48
49    /// Sets the pixel aspect ratio, including the `0:0` unknown sentinel.
50    /// Default: the `A` tag is omitted.
51    pub fn pixel_aspect(mut self, aspect: Ratio) -> Self {
52        self.pixel_aspect = Some(aspect);
53        self
54    }
55
56    /// Sets the interlacing mode. Default: the `I` tag is omitted.
57    /// [`Interlace::Unknown`] is treated as no value and omitted.
58    pub fn interlace(mut self, interlace: Interlace) -> Self {
59        self.interlace = Some(interlace);
60        self
61    }
62
63    /// Appends an `X` vendor extension (value bytes after the `X`).
64    /// Repeatable, with insertion order preserved on the wire. The value must
65    /// be non-empty and free of SP, LF, CR, and NUL bytes, else
66    /// [`Error::BadInput`].
67    pub fn extension(mut self, value: &[u8]) -> Result<Self, Error> {
68        if value.is_empty()
69            || value
70                .iter()
71                .any(|&b| b == b' ' || is_forbidden_param_byte(b))
72        {
73            return Err(Error::BadInput);
74        }
75        self.extensions.push(value.to_vec());
76        Ok(self)
77    }
78
79    /// Byte-exact re-encode path: emit `raw` verbatim as the header
80    /// parameter bytes (everything after `"YUV4MPEG2 "`, LF excluded)
81    /// instead of building canonical tags.
82    ///
83    /// `raw` must be a well-formed single-line parameter list: SP-separated
84    /// parameters, each a single ASCII letter tag followed by a value of one
85    /// byte or more, with no empty parameter (no leading, trailing, or
86    /// doubled SP) and no LF, CR, or NUL byte. A violation is
87    /// [`Error::BadInput`], returned before anything is written, so the
88    /// header can never span two lines. The list is then parsed with the
89    /// decoder's grammar, so a missing `W` or `H`, a zero dimension, or an
90    /// unknown `C` value returns the decoder's error for it. Frame geometry
91    /// for plane validation is derived from the list, overriding the
92    /// builder's width, height, and colorspace. Pass
93    /// [`Decoder::raw_params`](crate::Decoder::raw_params) to reproduce a
94    /// decoded stream byte-for-byte.
95    pub fn raw_params(mut self, raw: &[u8]) -> Result<Self, Error> {
96        validate_param_list(raw).map_err(|_| Error::BadInput)?;
97        let params = parse_stream_params(raw)?;
98        self.width = params.width;
99        self.height = params.height;
100        self.colorspace = params.colorspace;
101        self.raw = Some(raw.to_vec());
102        Ok(self)
103    }
104
105    /// Writes the stream header and returns the frame encoder.
106    ///
107    /// Zero dimensions or a zero framerate denominator are
108    /// [`Error::BadInput`]. Plane-size overflow and an over-budget header
109    /// line are [`Error::Limits`]. The high-bit-depth scratch buffer is
110    /// allocated here, once.
111    pub fn write_header<W: Write>(self, mut writer: W) -> Result<Encoder<W>, Error> {
112        if self.width == 0 || self.height == 0 || self.framerate.den == 0 {
113            return Err(Error::BadInput);
114        }
115        let plane_sizes = self.colorspace.plane_sizes(self.width, self.height)?;
116
117        let mut header: Vec<u8> = Vec::with_capacity(64);
118        header.extend_from_slice(b"YUV4MPEG2 ");
119        match &self.raw {
120            Some(raw) => header.extend_from_slice(raw),
121            None => {
122                write!(
123                    header,
124                    "W{} H{} F{}:{}",
125                    self.width, self.height, self.framerate.num, self.framerate.den
126                )
127                .map_err(Error::Io)?;
128                let interlace_char = match self.interlace {
129                    Some(Interlace::Progressive) => Some('p'),
130                    Some(Interlace::TopFirst) => Some('t'),
131                    Some(Interlace::BottomFirst) => Some('b'),
132                    Some(Interlace::Mixed) => Some('m'),
133                    _ => None,
134                };
135                if let Some(c) = interlace_char {
136                    write!(header, " I{c}").map_err(Error::Io)?;
137                }
138                if let Some(aspect) = self.pixel_aspect {
139                    write!(header, " A{}:{}", aspect.num, aspect.den).map_err(Error::Io)?;
140                }
141                write!(header, " C{}", self.colorspace.tag()).map_err(Error::Io)?;
142                for ext in &self.extensions {
143                    header.extend_from_slice(b" X");
144                    header.extend_from_slice(ext);
145                }
146            }
147        }
148        header.push(b'\n');
149        if header.len() > MAX_HEADER_LINE {
150            return Err(Error::Limits);
151        }
152        writer.write_all(&header).map_err(Error::from)?;
153
154        let scratch = if self.colorspace.bytes_per_sample() == 2 {
155            vec![0u8; plane_sizes[0]]
156        } else {
157            Vec::new()
158        };
159
160        Ok(Encoder {
161            writer,
162            plane_sizes,
163            bit_depth: self.colorspace.bit_depth(),
164            scratch,
165        })
166    }
167}
168
169/// Writes frames for one stream. Produced by [`EncoderBuilder::write_header`].
170///
171/// The hot path is `write_all` calls only. The optional `u16`-to-LE scratch
172/// buffer is allocated once at header time, and the counting-allocator test
173/// `tests/zero_alloc.rs` pins frame writes at zero heap allocations.
174pub struct Encoder<W: Write> {
175    writer: W,
176    plane_sizes: [usize; 3],
177    bit_depth: u8,
178    scratch: Vec<u8>,
179}
180
181impl<W: Write> Encoder<W> {
182    /// Writes one frame with a bare `FRAME` header from wire-format byte
183    /// planes. Plane byte lengths must match the header-derived sizes, else
184    /// [`Error::BadInput`].
185    pub fn write_frame(&mut self, planes: [&[u8]; 3]) -> Result<(), Error> {
186        self.write_frame_with_params(planes, b"")
187    }
188
189    /// Writes one frame carrying verbatim frame header parameters (the
190    /// bytes after `"FRAME "`, LF excluded, or empty for a bare header).
191    ///
192    /// Parameters must follow the frame header grammar: SP-separated,
193    /// each a single ASCII letter tag plus a value of one byte or more, no
194    /// empty piece, and no LF, CR, or NUL byte, else [`Error::BadInput`]
195    /// before anything is written. An over-budget frame header line is
196    /// [`Error::Limits`].
197    pub fn write_frame_with_params(
198        &mut self,
199        planes: [&[u8]; 3],
200        params: &[u8],
201    ) -> Result<(), Error> {
202        for (plane, &size) in planes.iter().zip(self.plane_sizes.iter()) {
203            if plane.len() != size {
204                return Err(Error::BadInput);
205            }
206        }
207        self.write_frame_header(params)?;
208        for plane in planes {
209            if !plane.is_empty() {
210                self.writer.write_all(plane).map_err(Error::from)?;
211            }
212        }
213        Ok(())
214    }
215
216    /// Writes one frame from host-order `u16` sample planes, encoding each
217    /// sample little-endian on the wire regardless of host endianness.
218    ///
219    /// Requires a >8-bit colorspace. Plane sample counts must match the
220    /// header-derived sizes and every sample must fit the stream bit depth,
221    /// else [`Error::BadInput`].
222    pub fn write_frame_u16(&mut self, planes: [&[u16]; 3]) -> Result<(), Error> {
223        if self.scratch.is_empty() {
224            return Err(Error::BadInput);
225        }
226        let max = if self.bit_depth >= 16 {
227            u16::MAX
228        } else {
229            (1u16 << self.bit_depth) - 1
230        };
231        for (plane, &size) in planes.iter().zip(self.plane_sizes.iter()) {
232            if plane.len() != size / 2 {
233                return Err(Error::BadInput);
234            }
235            if plane.iter().any(|&s| s > max) {
236                return Err(Error::BadInput);
237            }
238        }
239        self.write_frame_header(b"")?;
240        for plane in planes {
241            if plane.is_empty() {
242                continue;
243            }
244            let out = &mut self.scratch[..plane.len() * 2];
245            for (sample, wire) in plane.iter().zip(out.chunks_exact_mut(2)) {
246                wire.copy_from_slice(&sample.to_le_bytes());
247            }
248            self.writer.write_all(out).map_err(Error::from)?;
249        }
250        Ok(())
251    }
252
253    fn write_frame_header(&mut self, params: &[u8]) -> Result<(), Error> {
254        if !params.is_empty() {
255            validate_param_list(params).map_err(|_| Error::BadInput)?;
256            if 5 + 1 + params.len() + 1 > MAX_HEADER_LINE {
257                return Err(Error::Limits);
258            }
259        }
260        self.writer.write_all(b"FRAME").map_err(Error::from)?;
261        if !params.is_empty() {
262            self.writer.write_all(b" ").map_err(Error::from)?;
263            self.writer.write_all(params).map_err(Error::from)?;
264        }
265        self.writer.write_all(b"\n").map_err(Error::from)?;
266        Ok(())
267    }
268
269    /// Flushes and returns the underlying writer.
270    pub fn into_inner(mut self) -> Result<W, Error> {
271        self.writer.flush().map_err(Error::from)?;
272        Ok(self.writer)
273    }
274}
275
276impl<W: Write> std::fmt::Debug for Encoder<W> {
277    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
278        f.debug_struct("Encoder")
279            .field("plane_sizes", &self.plane_sizes)
280            .field("bit_depth", &self.bit_depth)
281            .finish_non_exhaustive()
282    }
283}