forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

frame.rs387 lines, 14.3 KiBHistoryRawDownload
1//! Decoded frames: what comes out of a decoder, and the two ways to get at the
2//! pixels — DRM PRIME export (zero copy) and mapped readback.
3
4use std::rc::Rc;
5
6use ec_va::va::{VA_FOURCC_NV12, VA_FOURCC_P010};
7use ec_va::{Display, Image, PrimeSurface, Surface, SurfaceExt};
8
9use crate::error::{Error, Result};
10use crate::picture::{fill_i420, fill_i420_16};
11use crate::pool::PooledSurface;
12
13pub use crate::picture::{Colour, I420, I420_16, i420_to_nv12, nv12_to_i420};
14
15/// One decoded picture, in display order.
16///
17/// Holding a frame holds its surface out of the decoder's pool, so a consumer
18/// that keeps every frame will starve the decoder — by design: that is the back
19/// pressure a zero-copy pipeline needs.
20pub struct Frame {
21 surface: Rc<PooledSurface>,
22 display: Rc<Display>,
23 /// Presentation timestamp carried through from the access unit.
24 pub timestamp: i64,
25 /// Size the picture is displayed at, after cropping.
26 pub display_size: (u32, u32),
27 /// Size the picture is coded at (a multiple of the codec's block size).
28 pub coded_size: (u32, u32),
29 /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.
30 pub bit_depth: u8,
31 /// This stream's colour metadata, when the codec's decoder resolves one.
32 pub colour: Option<Colour>,
33 /// The GPU reset epoch this frame was decoded in.
34 epoch: u64,
35}
36
37impl Frame {
38 pub(crate) fn new(
39 surface: Rc<PooledSurface>,
40 display: Rc<Display>,
41 timestamp: i64,
42 display_size: (u32, u32),
43 coded_size: (u32, u32),
44 bit_depth: u8,
45 colour: Option<Colour>,
46 ) -> Frame {
47 Frame {
48 surface,
49 display,
50 timestamp,
51 display_size,
52 coded_size,
53 bit_depth,
54 colour,
55 epoch: crate::reset::gpu_reset_epoch(),
56 }
57 }
58
59 /// Refuse to touch the surface of a context the GPU has since reset.
60 fn check_epoch(&self) -> Result<()> {
61 if crate::reset::gpu_reset_epoch() == self.epoch {
62 Ok(())
63 } else {
64 Err(Error::hw_reset(
65 "the GPU was reset after this frame was decoded; its surface is lost",
66 ))
67 }
68 }
69
70 /// The surface this frame lives on.
71 pub fn surface(&self) -> &Rc<Surface> {
72 &self.surface
73 }
74
75 /// The display the surface was created on.
76 pub(crate) fn display(&self) -> &Rc<Display> {
77 &self.display
78 }
79
80 /// This frame's colour metadata, when the codec's decoder resolves one.
81 pub fn colour(&self) -> Option<Colour> {
82 self.colour
83 }
84
85 /// Export the surface as DRM PRIME file descriptors.
86 ///
87 /// This is the path edith's `engine-hw` takes: the fds are imported into
88 /// gbm on the other side, so no pixel ever crosses the PCIe bus. The frame
89 /// is synchronised first, because an exported fd carries no fence.
90 pub fn export_prime(&self) -> Result<PrimeSurface> {
91 self.check_epoch()?;
92 crate::reset::sync_watched(&self.surface)?;
93 Ok(self.surface.export()?)
94 }
95
96 /// Read the frame back as 8-bit I420, truncating a 10-bit surface.
97 ///
98 /// Truncation is what the `vh_*` C ABI takes today (one byte per sample);
99 /// [`Frame::to_i420_16`] is the lossless path for a caller that wants the
100 /// ten bits.
101 pub fn to_i420(&self) -> Result<I420> {
102 let (w, h) = self.display_size;
103 let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
104 let (w, h) = (w as usize, h as usize);
105 let mut out = I420 {
106 y: vec![0; w * h],
107 u: vec![0; cw * ch],
108 v: vec![0; cw * ch],
109 width: self.display_size.0,
110 height: self.display_size.1,
111 };
112
113 self.with_planes(|image| {
114 let (y_plane, y_pitch, uv_plane, uv_pitch) = planes_of(image)?;
115 fill_i420(
116 &mut out,
117 self.bit_depth,
118 y_plane,
119 y_pitch,
120 uv_plane,
121 uv_pitch,
122 )?;
123 Ok(out)
124 })
125 }
126
127 /// Read the frame back as 10-bit I420 (samples in the low 10 bits).
128 ///
129 /// An 8-bit surface is widened rather than refused, so a caller can hold
130 /// one frame type across a mixed-depth timeline.
131 pub fn to_i420_16(&self) -> Result<I420_16> {
132 let (w, h) = self.display_size;
133 let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
134 let (w, h) = (w as usize, h as usize);
135 let mut out = I420_16 {
136 y: vec![0; w * h],
137 u: vec![0; cw * ch],
138 v: vec![0; cw * ch],
139 width: self.display_size.0,
140 height: self.display_size.1,
141 bit_depth: 10,
142 };
143
144 self.with_planes(|image| {
145 let (y_plane, y_pitch, uv_plane, uv_pitch) = planes_of(image)?;
146 fill_i420_16(
147 &mut out,
148 self.bit_depth,
149 y_plane,
150 y_pitch,
151 uv_plane,
152 uv_pitch,
153 )?;
154 Ok(out)
155 })
156 }
157
158 /// Map the surface's pixels and hand the planes to `read`.
159 ///
160 /// `vaGetImage` into a fresh image, *not* `vaDeriveImage`. (cros-libva's
161 /// image borrows its surface, so the per-stream image cache of the C-era
162 /// layer cannot be kept; one `vaCreateImage` per readback replaces it.)
163 /// Deriving looks cheaper — it is a view rather than a
164 /// copy — and it does return the same pixels here (checked row for row),
165 /// but the view is device memory across the PCIe bar: reading a 1080p frame
166 /// through it costs 48 ms against 10 ms for a driver-side copy into system
167 /// memory followed by a normal read (measured, 719-frame loop).
168 fn with_planes<R>(&self, read: impl FnOnce(&Image<'_>) -> Result<R>) -> Result<R> {
169 self.check_epoch()?;
170 crate::reset::sync_watched(&self.surface)?;
171 let fourcc = if self.bit_depth > 8 {
172 VA_FOURCC_P010
173 } else {
174 VA_FOURCC_NV12
175 };
176 let (w, h) = self.coded_size;
177 let format = ec_va::surface::image_format(&self.display, fourcc)?;
178 let surface: &Surface = &self.surface;
179 let image = ec_va::surface::create_image(surface, format, (w, h), (w, h))?;
180 read(&image)
181 }
182}
183
184impl std::fmt::Debug for Frame {
185 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
186 f.debug_struct("Frame")
187 .field("surface", &self.surface.id())
188 .field("timestamp", &self.timestamp)
189 .field("display_size", &self.display_size)
190 .field("bit_depth", &self.bit_depth)
191 .finish()
192 }
193}
194
195/// Luma and chroma planes of a read-back NV12/P010 image, with their pitches.
196fn planes_of<'a>(image: &'a Image<'_>) -> Result<(&'a [u8], usize, &'a [u8], usize)> {
197 let data: &[u8] = image.as_ref();
198 let va = image.image();
199 let plane = |i: usize| -> Result<&[u8]> {
200 let off = *va
201 .offsets
202 .get(i)
203 .ok_or_else(|| Error::config("VA image has no such plane"))? as usize;
204 data.get(off..)
205 .ok_or_else(|| Error::config("VA image plane lies outside the mapping"))
206 };
207 let y_plane = plane(0)?;
208 let uv_plane = plane(1)?;
209 let y_pitch = va.pitches[0] as usize;
210 let uv_pitch = va.pitches[1] as usize;
211 Ok((y_plane, y_pitch, uv_plane, uv_pitch))
212}
213
214#[cfg(test)]
215mod tests {
216 use super::*;
217 use crate::picture::check_plane;
218
219 fn blank(w: u32, h: u32) -> I420 {
220 I420 {
221 y: vec![0; (w * h) as usize],
222 u: vec![0; (w.div_ceil(2) * h.div_ceil(2)) as usize],
223 v: vec![0; (w.div_ceil(2) * h.div_ceil(2)) as usize],
224 width: w,
225 height: h,
226 }
227 }
228
229 #[test]
230 fn a_plane_that_covers_the_frame_passes() {
231 // 4 rows of 6 bytes at pitch 8: the last row needs no padding.
232 assert!(check_plane("luma", 3 * 8 + 6, 8, 4, 6).is_ok());
233 assert!(check_plane("luma", 4 * 8, 8, 4, 6).is_ok());
234 assert!(check_plane("luma", 0, 8, 0, 6).is_ok());
235 }
236
237 #[test]
238 fn a_short_or_odd_plane_is_an_error_not_a_panic() {
239 assert!(check_plane("luma", 3 * 8 + 5, 8, 4, 6).is_err());
240 assert!(check_plane("luma", 0, 8, 1, 6).is_err());
241 // Pitch narrower than a row.
242 assert!(check_plane("luma", 1000, 4, 2, 6).is_err());
243 assert!(check_plane("luma", 1000, 0, 2, 6).is_err());
244 // Arithmetic that would overflow.
245 assert!(check_plane("luma", usize::MAX, usize::MAX, 3, 6).is_err());
246 }
247
248 #[test]
249 fn short_mappings_are_refused_on_every_path() {
250 let (w, h) = (6u32, 4u32);
251 let y = vec![0u8; 8 * 4];
252 let uv = vec![0u8; 8 * 2];
253 for depth in [8u8, 10] {
254 let bytes = if depth == 8 { 1 } else { 2 };
255 let (yp, uvp) = (8 * bytes, 8 * bytes);
256 let mut out8 = blank(w, h);
257 let mut out16 = I420_16 {
258 y: vec![0; 24],
259 u: vec![0; 6],
260 v: vec![0; 6],
261 width: w,
262 height: h,
263 bit_depth: 10,
264 };
265 // Mapped one row short of a full luma plane, and a chroma plane cut
266 // in half: what a lost context can leave behind.
267 let y_full = vec![0u8; yp * 4];
268 let uv_full = vec![0u8; uvp * 2];
269 assert!(fill_i420(&mut out8, depth, &y_full, yp, &uv_full, uvp).is_ok());
270 assert!(fill_i420_16(&mut out16, depth, &y_full, yp, &uv_full, uvp).is_ok());
271 let short_y = &y_full[..yp * 3];
272 let short_uv = &uv_full[..uvp / 2];
273 assert!(fill_i420(&mut out8, depth, short_y, yp, &uv_full, uvp).is_err());
274 assert!(fill_i420(&mut out8, depth, &y_full, yp, short_uv, uvp).is_err());
275 assert!(fill_i420_16(&mut out16, depth, short_y, yp, &uv_full, uvp).is_err());
276 assert!(fill_i420_16(&mut out16, depth, &y_full, yp, short_uv, uvp).is_err());
277 // An empty mapping and a zero pitch.
278 assert!(fill_i420(&mut out8, depth, &[], yp, &[], uvp).is_err());
279 assert!(fill_i420(&mut out8, depth, &y_full, 0, &uv_full, uvp).is_err());
280 }
281 let _ = (y, uv);
282 }
283
284 #[test]
285 fn nv12_round_trips_through_i420() {
286 let (w, h) = (6usize, 4usize);
287 let (y_pitch, uv_pitch) = (8usize, 8usize);
288 let mut y = vec![0u8; y_pitch * h];
289 let mut uv = vec![0u8; uv_pitch * h / 2];
290 for row in 0..h {
291 for col in 0..w {
292 y[row * y_pitch + col] = (row * w + col) as u8;
293 }
294 }
295 for row in 0..h / 2 {
296 for col in 0..w {
297 uv[row * uv_pitch + col] = (100 + row * w + col) as u8;
298 }
299 }
300
301 let i420 = nv12_to_i420(&y, y_pitch, &uv, uv_pitch, w, h);
302 assert_eq!(i420.y.len(), w * h);
303 assert_eq!(i420.u.len(), (w / 2) * (h / 2));
304 assert_eq!(i420.y[0], 0);
305 assert_eq!(i420.y[w], w as u8);
306 // U takes the even bytes of the interleaved plane, V the odd ones.
307 assert_eq!(i420.u[0], 100);
308 assert_eq!(i420.v[0], 101);
309 assert_eq!(i420.u[1], 102);
310
311 let mut y2 = vec![0u8; y_pitch * h];
312 let mut uv2 = vec![0u8; uv_pitch * h / 2];
313 i420_to_nv12(&i420, &mut y2, y_pitch, &mut uv2, uv_pitch);
314 let back = nv12_to_i420(&y2, y_pitch, &uv2, uv_pitch, w, h);
315 assert_eq!(back, i420);
316 }
317
318 /// `fill_i420_16` is the lossless 10-bit readback: samples that collapse
319 /// together under 8-bit truncation (`512 >> 2 == 513 >> 2 == 128`) must
320 /// survive distinctly. The test feeds the conversion synthetic P010 planes
321 /// directly: cros-libva has no `vaPutImage`, so the GPU upload this test
322 /// used to do is not available, and the plane conversion is what it checks.
323 #[test]
324 fn p010_readback_preserves_ten_bits() {
325 let (w, h) = (4u32, 4u32);
326 // Synthetic P010: 10-bit samples packed into the high bits of each
327 // u16, exactly how the decoder's P010 surfaces carry them. 512 and 513
328 // both truncate to 128 in 8-bit, so they prove the 16-bit path is not
329 // silently losing the low bits.
330 let y_samples = [512u16, 513, 1023, 5];
331 let y_pitch = w as usize * 2;
332 let uv_pitch = w as usize * 2;
333 let mut y_plane = vec![0u8; y_pitch * h as usize];
334 for row in 0..h as usize {
335 for col in 0..w as usize {
336 let sample = y_samples[(row * w as usize + col) % y_samples.len()] << 6;
337 let o = row * y_pitch + col * 2;
338 y_plane[o..o + 2].copy_from_slice(&sample.to_le_bytes());
339 }
340 }
341 let mut uv_plane = vec![0u8; uv_pitch * h as usize / 2];
342 let (u, v) = (512u16 << 6, 1023u16 << 6);
343 for row in 0..h as usize / 2 {
344 for col in 0..w as usize / 2 {
345 let o = row * uv_pitch + col * 4;
346 uv_plane[o..o + 2].copy_from_slice(&u.to_le_bytes());
347 uv_plane[o + 2..o + 4].copy_from_slice(&v.to_le_bytes());
348 }
349 }
350
351 let mut i16 = I420_16 {
352 y: vec![0; (w * h) as usize],
353 u: vec![0; (w * h / 4) as usize],
354 v: vec![0; (w * h / 4) as usize],
355 width: w,
356 height: h,
357 bit_depth: 10,
358 };
359 fill_i420_16(&mut i16, 10, &y_plane, y_pitch, &uv_plane, uv_pitch).expect("16-bit fill");
360 let mut i8 = I420 {
361 y: vec![0; (w * h) as usize],
362 u: vec![0; (w * h / 4) as usize],
363 v: vec![0; (w * h / 4) as usize],
364 width: w,
365 height: h,
366 };
367 fill_i420(&mut i8, 10, &y_plane, y_pitch, &uv_plane, uv_pitch).expect("8-bit fill");
368
369 assert_eq!(i16.width, w);
370 assert_eq!(i16.height, h);
371 assert_eq!(i16.bit_depth, 10);
372 let want_y: Vec<u16> = (0..w as usize * h as usize)
373 .map(|i| y_samples[i % y_samples.len()])
374 .collect();
375 assert_eq!(
376 i16.y, want_y,
377 "16-bit luma must preserve the 10-bit samples"
378 );
379 let want_y8: Vec<u8> = want_y.iter().map(|&s| (s >> 2) as u8).collect();
380 assert_eq!(i8.y, want_y8, "8-bit luma must be the >> 2 truncation");
381
382 assert_eq!(i16.u, vec![512u16; 4]);
383 assert_eq!(i16.v, vec![1023u16; 4]);
384 assert_eq!(i8.u, vec![128u8; 4]);
385 assert_eq!(i8.v, vec![255u8; 4]);
386 }
387}