Skip to main content

moq_video/
size.rs

1use crate::Error;
2
3/// A frame resolution in pixels.
4///
5/// Names the pair that [`decode::Config::resize`](crate::decode::Config::resize)
6/// and [`decode::Frame::resize`](crate::decode::Frame::resize) both take, so
7/// width and height can't be swapped at a call site.
8#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]
9pub struct Size {
10	/// Width in pixels.
11	pub width: u32,
12	/// Height in pixels.
13	pub height: u32,
14}
15
16impl Size {
17	/// A size of `width` x `height` pixels.
18	pub fn new(width: u32, height: u32) -> Self {
19		Self { width, height }
20	}
21
22	/// Total pixels. Can't overflow: the widest `u32` square still fits a `u64`.
23	pub fn pixels(&self) -> u64 {
24		self.width as u64 * self.height as u64
25	}
26
27	/// Reject anything the I420 pipeline can't represent.
28	///
29	/// I420 chroma is subsampled 2x2, so every stage (encode, decode, resize)
30	/// needs even, non-zero dimensions. Checking here keeps the rule in one place
31	/// instead of re-deriving it at each boundary.
32	pub(crate) fn validate(&self, what: &str) -> Result<(), Error> {
33		if self.width == 0 || self.height == 0 {
34			return Err(Error::Codec(anyhow::anyhow!(
35				"{what} {self}: dimensions must be non-zero"
36			)));
37		}
38		if !self.width.is_multiple_of(2) || !self.height.is_multiple_of(2) {
39			return Err(Error::Codec(anyhow::anyhow!("{what} {self}: dimensions must be even")));
40		}
41		Ok(())
42	}
43}
44
45impl std::fmt::Display for Size {
46	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
47		write!(f, "{}x{}", self.width, self.height)
48	}
49}
50
51impl From<(u32, u32)> for Size {
52	fn from((width, height): (u32, u32)) -> Self {
53		Self::new(width, height)
54	}
55}
56
57#[cfg(test)]
58mod tests {
59	use super::*;
60
61	#[test]
62	fn validate_rejects_odd_and_zero() {
63		assert!(Size::new(320, 240).validate("frame").is_ok());
64		assert!(Size::new(0, 240).validate("frame").is_err());
65		assert!(Size::new(320, 0).validate("frame").is_err());
66		assert!(Size::new(321, 240).validate("frame").is_err());
67		assert!(Size::new(320, 241).validate("frame").is_err());
68	}
69
70	#[test]
71	fn display_reads_as_a_resolution() {
72		assert_eq!(Size::new(1920, 1080).to_string(), "1920x1080");
73	}
74}