Skip to main content

moq_video/
convert.rs

1//! CPU conversion of native video surfaces to packed pixels.
2//!
3//! [`Surface::to_rgba`](crate::Surface::to_rgba) is the portable rendering exit: it
4//! downloads a GPU surface when necessary, applies the surface's color space, and
5//! returns owned pixels for an image or UI toolkit.
6
7use yuv::{YuvPlanarImage, yuv420_to_rgba};
8
9use crate::{Color, Error, Size, Surface};
10
11/// CPU surface conversion options.
12///
13/// `#[non_exhaustive]`: build via [`Config::new`] (or `default()`) and set the
14/// fields you care about, so future output options stay additive.
15#[derive(Clone, Debug, Default)]
16#[non_exhaustive]
17pub struct Config {
18	/// How to interpret the source's YUV samples, overriding its own metadata.
19	///
20	/// `None` uses [`Surface::color`] and falls back to [`Color::infer`] when the
21	/// decoder or native surface carries no color description.
22	pub color: Option<Color>,
23}
24
25impl Config {
26	/// A default config that honors surface metadata and otherwise infers color.
27	pub fn new() -> Self {
28		Self::default()
29	}
30}
31
32/// Owned, tightly packed RGBA8 pixels in row-major order.
33#[derive(Clone)]
34pub struct Rgba {
35	size: Size,
36	stride: usize,
37	data: Vec<u8>,
38}
39
40impl Rgba {
41	/// Wrap tightly packed `size` RGBA8 pixels.
42	#[cfg(feature = "render")]
43	pub(crate) fn new(size: Size, data: Vec<u8>) -> Self {
44		debug_assert_eq!(data.len(), size.width as usize * size.height as usize * 4);
45		Self {
46			size,
47			stride: size.width as usize * 4,
48			data,
49		}
50	}
51
52	/// Image dimensions in pixels.
53	pub fn size(&self) -> Size {
54		self.size
55	}
56
57	/// Image width in pixels.
58	pub fn width(&self) -> u32 {
59		self.size.width
60	}
61
62	/// Image height in pixels.
63	pub fn height(&self) -> u32 {
64		self.size.height
65	}
66
67	/// Bytes between adjacent rows, always `width * 4`.
68	pub fn stride(&self) -> usize {
69		self.stride
70	}
71
72	/// Tightly packed RGBA8 pixels.
73	pub fn data(&self) -> &[u8] {
74		&self.data
75	}
76
77	/// Consume the image and return its tightly packed RGBA8 pixels.
78	pub fn into_data(self) -> Vec<u8> {
79		self.data
80	}
81}
82
83/// Downloads `surface` if it is not already on the CPU and converts it to RGBA.
84///
85/// By reference rather than by value: a caller often holds the surface behind
86/// an `Arc` it cannot unwrap, most obviously a publisher's preview frame, which
87/// is shared with every rendition's encoder and so never has a refcount of one.
88/// Nothing here needs to own the surface, and requiring it forced those callers
89/// into a full-resolution rescale purely to obtain pixels they already had.
90pub(crate) fn rgba(surface: &Surface, config: &Config) -> Result<Rgba, Error> {
91	let size = Size::new(surface.width(), surface.height());
92	let color = config
93		.color
94		.or_else(|| surface.color())
95		.unwrap_or_else(|| Color::infer(size));
96	let i420 = surface.to_i420()?;
97	let luma = usize::try_from(size.pixels())
98		.map_err(|_| Error::codec(anyhow::anyhow!("RGBA frame {size}: dimensions too large to represent")))?;
99	let stride = size.width.checked_mul(4).ok_or_else(|| {
100		Error::codec(anyhow::anyhow!(
101			"RGBA frame {size}: row stride is too large to represent"
102		))
103	})?;
104	let stride_usize = usize::try_from(stride).map_err(|_| {
105		Error::codec(anyhow::anyhow!(
106			"RGBA frame {size}: row stride is too large to represent"
107		))
108	})?;
109	let len = stride_usize.checked_mul(size.height as usize).ok_or_else(|| {
110		Error::codec(anyhow::anyhow!(
111			"RGBA frame {size}: byte length is too large to represent"
112		))
113	})?;
114	let chroma = luma / 4;
115	let planar = YuvPlanarImage {
116		y_plane: &i420.data[..luma],
117		y_stride: size.width,
118		u_plane: &i420.data[luma..luma + chroma],
119		u_stride: size.width / 2,
120		v_plane: &i420.data[luma + chroma..],
121		v_stride: size.width / 2,
122		width: size.width,
123		height: size.height,
124	};
125	let mut data = vec![0; len];
126	let (range, matrix) = color.yuv();
127	yuv420_to_rgba(&planar, &mut data, stride, range, matrix)
128		.map_err(|e| Error::codec(anyhow::anyhow!("RGBA conversion failed for {size}: {e}")))?;
129
130	Ok(Rgba {
131		size,
132		stride: stride_usize,
133		data,
134	})
135}
136
137#[cfg(test)]
138mod tests {
139	use super::*;
140	use crate::I420;
141
142	/// A resized surface keeps its original matrix even after crossing the
143	/// standard-definition boundary. Ignoring that metadata tints saturated
144	/// colors while leaving grayscale test images apparently correct.
145	#[test]
146	fn conversion_uses_the_surface_color() {
147		let source_size = Size::new(64, 64);
148		let red = [255u8, 0, 0, 255].repeat(source_size.pixels() as usize);
149		let source = I420::from_rgba(&red, source_size.width * 4, source_size).unwrap();
150		let source = source.resize(Size::new(1280, 720)).unwrap();
151		assert_eq!(source.color(), Some(Color::BT601));
152		assert_eq!(Color::infer(Size::new(1280, 720)), Color::BT709);
153
154		let image = rgba(&Surface::I420(source), &Config::default()).unwrap();
155		let center = (image.height() as usize / 2 * image.stride) + image.width() as usize / 2 * 4;
156		let pixel = &image.data[center..center + 4];
157		assert!(pixel[0] >= 250, "red channel drifted: {pixel:?}");
158		assert!(pixel[1] <= 2 && pixel[2] <= 2, "surface matrix was ignored: {pixel:?}");
159		assert_eq!(pixel[3], 255);
160	}
161
162	#[test]
163	fn conversion_reports_a_tightly_packed_layout() {
164		let size = Size::new(64, 32);
165		let surface = Surface::I420(I420::new(size, vec![128; I420::len(size).unwrap()]).unwrap());
166
167		let image = rgba(&surface, &Config::default()).unwrap();
168		assert_eq!(image.size(), size);
169		assert_eq!(image.width(), size.width);
170		assert_eq!(image.height(), size.height);
171		assert_eq!(image.stride(), size.width as usize * 4);
172		assert_eq!(image.data().len(), image.stride() * size.height as usize);
173	}
174}