Skip to main content

y4m_codec/
colorspace.rs

1//! Colorspace tags, subsampling families, and plane geometry.
2
3use crate::Error;
4
5/// Chroma subsampling family of a colorspace tag.
6#[non_exhaustive]
7#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
8pub enum Subsampling {
9    /// 4:2:0: chroma planes are `ceil(W/2) x ceil(H/2)` samples.
10    C420,
11    /// 4:2:2: chroma planes are `ceil(W/2) x H` samples.
12    C422,
13    /// 4:4:4: chroma planes are `W x H` samples.
14    C444,
15    /// Grayscale: no chroma planes.
16    Mono,
17}
18
19/// Chroma sample siting carried by the 8-bit 4:2:0 tag variants.
20///
21/// Siting is positioning metadata only. Plane sizes and byte layout are
22/// identical across all 4:2:0 variants.
23#[non_exhaustive]
24#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
25pub enum ChromaSiting {
26    /// No siting stated (`C420`, all `p<depth>` tags, and non-4:2:0 tags).
27    Unspecified,
28    /// Centered siting (`C420jpeg`).
29    Jpeg,
30    /// Left-cosited siting (`C420mpeg2`).
31    Mpeg2,
32    /// PAL-DV siting (`C420paldv`).
33    PalDv,
34}
35
36/// A recognized colorspace: subsampling family, chroma siting, and bit depth.
37///
38/// Values exist only for the tags in the YUV4MPEG2 contract (mjpegtools core
39/// plus the ffmpeg high-bit-depth extension). Parsing an unknown `C` value
40/// returns [`Error::Unsupported`].
41#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
42pub struct Colorspace {
43    sub: Subsampling,
44    siting: ChromaSiting,
45    depth: u8,
46    tag: &'static str,
47}
48
49macro_rules! colorspaces {
50    ($($name:ident => $tag:literal, $sub:ident, $sit:ident, $depth:literal;)*) => {
51        impl Colorspace {
52            $(
53                #[doc = concat!("The `C", $tag, "` colorspace tag.")]
54                pub const $name: Colorspace = Colorspace {
55                    sub: Subsampling::$sub,
56                    siting: ChromaSiting::$sit,
57                    depth: $depth,
58                    tag: $tag,
59                };
60            )*
61
62            /// Every recognized colorspace, in tag-table order.
63            pub const ALL: &'static [Colorspace] = &[$(Colorspace::$name),*];
64        }
65    };
66}
67
68colorspaces! {
69    C420JPEG => "420jpeg", C420, Jpeg, 8;
70    C420MPEG2 => "420mpeg2", C420, Mpeg2, 8;
71    C420PALDV => "420paldv", C420, PalDv, 8;
72    C420 => "420", C420, Unspecified, 8;
73    C420P9 => "420p9", C420, Unspecified, 9;
74    C420P10 => "420p10", C420, Unspecified, 10;
75    C420P12 => "420p12", C420, Unspecified, 12;
76    C420P14 => "420p14", C420, Unspecified, 14;
77    C420P16 => "420p16", C420, Unspecified, 16;
78    C422 => "422", C422, Unspecified, 8;
79    C422P9 => "422p9", C422, Unspecified, 9;
80    C422P10 => "422p10", C422, Unspecified, 10;
81    C422P12 => "422p12", C422, Unspecified, 12;
82    C422P14 => "422p14", C422, Unspecified, 14;
83    C422P16 => "422p16", C422, Unspecified, 16;
84    C444 => "444", C444, Unspecified, 8;
85    C444P9 => "444p9", C444, Unspecified, 9;
86    C444P10 => "444p10", C444, Unspecified, 10;
87    C444P12 => "444p12", C444, Unspecified, 12;
88    C444P14 => "444p14", C444, Unspecified, 14;
89    C444P16 => "444p16", C444, Unspecified, 16;
90    MONO => "mono", Mono, Unspecified, 8;
91    MONO9 => "mono9", Mono, Unspecified, 9;
92    MONO10 => "mono10", Mono, Unspecified, 10;
93    MONO12 => "mono12", Mono, Unspecified, 12;
94    MONO16 => "mono16", Mono, Unspecified, 16;
95}
96
97impl Colorspace {
98    /// Looks up a colorspace by its wire tag value (the bytes after `C`).
99    ///
100    /// Returns [`Error::Unsupported`] for any value outside the recognized
101    /// set, including `444alpha`.
102    pub fn from_tag(tag: &str) -> Result<Colorspace, Error> {
103        Colorspace::ALL
104            .iter()
105            .find(|cs| cs.tag == tag)
106            .copied()
107            .ok_or_else(|| Error::Unsupported(tag.to_owned()))
108    }
109
110    pub(crate) fn from_tag_bytes(tag: &[u8]) -> Result<Colorspace, Error> {
111        match std::str::from_utf8(tag) {
112            Ok(s) => Colorspace::from_tag(s),
113            Err(_) => Err(Error::Unsupported(
114                String::from_utf8_lossy(tag).into_owned(),
115            )),
116        }
117    }
118
119    /// The chroma subsampling family.
120    pub fn subsampling(self) -> Subsampling {
121        self.sub
122    }
123
124    /// The chroma sample siting carried by the tag.
125    pub fn chroma_siting(self) -> ChromaSiting {
126        self.siting
127    }
128
129    /// Bits per sample, `8..=16`.
130    pub fn bit_depth(self) -> u8 {
131        self.depth
132    }
133
134    /// Bytes per sample on the wire: 1 for depth <= 8, 2 otherwise.
135    pub fn bytes_per_sample(self) -> usize {
136        if self.depth <= 8 {
137            1
138        } else {
139            2
140        }
141    }
142
143    /// The wire tag value without the leading `C`, e.g. `"420p10"`.
144    pub fn tag(self) -> &'static str {
145        self.tag
146    }
147
148    /// Per-plane sample dimensions `(width, height)` for a `width x height`
149    /// frame. Chroma planes of mono streams are `(0, 0)`.
150    pub(crate) fn plane_dims(self, width: usize, height: usize) -> [(usize, usize); 3] {
151        // ceil(x / 2) written overflow-free: `x + 1` would wrap for
152        // `usize::MAX`, which a hostile header can produce on 64-bit hosts.
153        let half_w = width / 2 + width % 2;
154        let half_h = height / 2 + height % 2;
155        let (cw, ch) = match self.sub {
156            Subsampling::C420 => (half_w, half_h),
157            Subsampling::C422 => (half_w, height),
158            Subsampling::C444 => (width, height),
159            Subsampling::Mono => (0, 0),
160        };
161        [(width, height), (cw, ch), (cw, ch)]
162    }
163
164    /// Per-plane byte sizes for a `width x height` frame, using checked
165    /// arithmetic. Overflow of any product or of the total is
166    /// [`Error::Limits`].
167    pub(crate) fn plane_sizes(self, width: usize, height: usize) -> Result<[usize; 3], Error> {
168        let bps = self.bytes_per_sample();
169        let dims = self.plane_dims(width, height);
170        let mut sizes = [0usize; 3];
171        let mut total = 0usize;
172        for (i, (w, h)) in dims.iter().enumerate() {
173            let size = w
174                .checked_mul(*h)
175                .and_then(|n| n.checked_mul(bps))
176                .ok_or(Error::Limits)?;
177            total = total.checked_add(size).ok_or(Error::Limits)?;
178            sizes[i] = size;
179        }
180        Ok(sizes)
181    }
182}
183
184#[cfg(test)]
185mod tests {
186    use super::*;
187
188    #[test]
189    fn tag_lookup_round_trips() {
190        for cs in Colorspace::ALL {
191            let back = Colorspace::from_tag(cs.tag()).unwrap();
192            assert_eq!(back, *cs);
193        }
194    }
195
196    #[test]
197    fn alpha_is_unsupported() {
198        assert!(matches!(
199            Colorspace::from_tag("444alpha"),
200            Err(Error::Unsupported(t)) if t == "444alpha"
201        ));
202    }
203
204    #[test]
205    fn odd_dims_round_up() {
206        assert_eq!(
207            Colorspace::C420.plane_sizes(5, 5).unwrap(),
208            [25, 9, 9],
209            "5x5 4:2:0 chroma is ceil(5/2)^2 = 9"
210        );
211        assert_eq!(Colorspace::C422P10.plane_sizes(3, 2).unwrap(), [12, 8, 8]);
212        assert_eq!(Colorspace::MONO.plane_sizes(5, 3).unwrap(), [15, 0, 0]);
213    }
214}