forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

frame.rs526 lines, 19.7 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::sync::{Arc, Mutex};
5
6use ec_core::color::{ColorDescription, ContentLight};
7use ec_va::sys::{VA_FOURCC_NV12, VA_FOURCC_P010};
8use ec_va::{Image, MappedImage, PrimeSurface, Surface};
9
10use crate::error::{Error, Result};
11use crate::pool::PooledSurface;
12
13/// A stream's colour metadata, resolved from its own headers: VUI tags for the
14/// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI
15/// messages for the peak the mastering grade and the content itself declared.
16/// No container tier here: ec-hw only ever sees the elementary stream, so a
17/// caller that also holds the container's tags resolves those over this.
18#[derive(Debug, Clone, Copy, PartialEq)]
19pub struct Colour {
20 /// Matrix/transfer/range, resolved from the bitstream's own VUI.
21 pub description: ColorDescription,
22 /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when
23 /// the stream carried them (HEVC prefix SEI only).
24 pub light: ContentLight,
25}
26
27/// The readback image a decoder reuses across frames.
28///
29/// One `vaCreateImage`/`vaDestroyImage` pair per frame costs ~20 ms at 1080p on
30/// this driver — more than the decode — because each one allocates and frees a
31/// 3 MB driver buffer. The image is therefore created once per stream and kept
32/// here, shared by every frame that stream produces.
33pub(crate) type ImageCache = Arc<Mutex<Option<Image>>>;
34
35/// One decoded picture, in display order.
36///
37/// Holding a frame holds its surface out of the decoder's pool, so a consumer
38/// that keeps every frame will starve the decoder — by design: that is the back
39/// pressure a zero-copy pipeline needs.
40pub struct Frame {
41 surface: Arc<PooledSurface>,
42 images: ImageCache,
43 /// Presentation timestamp carried through from the access unit.
44 pub timestamp: i64,
45 /// Size the picture is displayed at, after cropping.
46 pub display_size: (u32, u32),
47 /// Size the picture is coded at (a multiple of the codec's block size).
48 pub coded_size: (u32, u32),
49 /// Luma bit depth: 8 for NV12 surfaces, 10 for P010.
50 pub bit_depth: u8,
51 /// This stream's colour metadata, when the codec's decoder resolves one.
52 pub colour: Option<Colour>,
53}
54
55/// 8-bit planar 4:2:0, the currency edith's software path speaks.
56#[derive(Debug, Clone, PartialEq, Eq)]
57pub struct I420 {
58 /// Luma plane, `width * height`.
59 pub y: Vec<u8>,
60 /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`.
61 pub u: Vec<u8>,
62 /// Cr plane, same size as `u`.
63 pub v: Vec<u8>,
64 /// Width in luma samples.
65 pub width: u32,
66 /// Height in luma samples.
67 pub height: u32,
68}
69
70/// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits.
71#[derive(Debug, Clone, PartialEq, Eq)]
72pub struct I420_16 {
73 /// Luma plane.
74 pub y: Vec<u16>,
75 /// Cb plane.
76 pub u: Vec<u16>,
77 /// Cr plane.
78 pub v: Vec<u16>,
79 /// Width in luma samples.
80 pub width: u32,
81 /// Height in luma samples.
82 pub height: u32,
83 /// Luma bit depth: always 10 for this format.
84 pub bit_depth: u8,
85}
86
87impl Frame {
88 pub(crate) fn new(
89 surface: Arc<PooledSurface>,
90 images: ImageCache,
91 timestamp: i64,
92 display_size: (u32, u32),
93 coded_size: (u32, u32),
94 bit_depth: u8,
95 colour: Option<Colour>,
96 ) -> Frame {
97 Frame {
98 surface,
99 images,
100 timestamp,
101 display_size,
102 coded_size,
103 bit_depth,
104 colour,
105 }
106 }
107
108 /// The surface this frame lives on.
109 pub fn surface(&self) -> &Arc<Surface> {
110 &self.surface
111 }
112
113 /// This frame's colour metadata, when the codec's decoder resolves one.
114 pub fn colour(&self) -> Option<Colour> {
115 self.colour
116 }
117
118 /// Export the surface as DRM PRIME file descriptors.
119 ///
120 /// This is the path edith's `engine-hw` takes: the fds are imported into
121 /// gbm on the other side, so no pixel ever crosses the PCIe bus. The frame
122 /// is synchronised first, because an exported fd carries no fence.
123 pub fn export_prime(&self) -> Result<PrimeSurface> {
124 self.surface.sync()?;
125 Ok(self
126 .surface
127 .export_prime(ec_va::sys::VA_EXPORT_SURFACE_READ_ONLY)?)
128 }
129
130 /// Read the frame back as 8-bit I420, truncating a 10-bit surface.
131 ///
132 /// Truncation is what the `vh_*` C ABI takes today (one byte per sample);
133 /// [`Frame::to_i420_16`] is the lossless path for a caller that wants the
134 /// ten bits.
135 pub fn to_i420(&self) -> Result<I420> {
136 let (w, h) = self.display_size;
137 let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
138 let (w, h) = (w as usize, h as usize);
139 let mut out = I420 {
140 y: vec![0; w * h],
141 u: vec![0; cw * ch],
142 v: vec![0; cw * ch],
143 width: self.display_size.0,
144 height: self.display_size.1,
145 };
146
147 self.with_planes(|mapped| {
148 let y_pitch = mapped.pitch(0).unwrap_or(0) as usize;
149 let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize;
150 let y_plane = mapped
151 .plane(0)
152 .ok_or_else(|| Error::config("VA image has no luma plane"))?;
153 let uv_plane = mapped
154 .plane(1)
155 .ok_or_else(|| Error::config("VA image has no chroma plane"))?;
156
157 // Mapped VA memory is uncached (write-combining on this driver), where a
158 // byte-at-a-time read runs at a few hundred MB/s. Every plane is
159 // therefore pulled out one whole row at a time with `copy_from_slice`
160 // and unpacked from ordinary memory afterwards: same result, 10x the
161 // throughput (27 ms -> 2.6 ms per 1080p frame, measured).
162 let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)];
163 match self.bit_depth {
164 8 => {
165 for row in 0..h {
166 let src = row * y_pitch;
167 out.y[row * w..(row + 1) * w].copy_from_slice(&y_plane[src..src + w]);
168 }
169 for row in 0..ch {
170 let src = row * uv_pitch;
171 let line = &mut row_buf[..cw * 2];
172 line.copy_from_slice(&uv_plane[src..src + cw * 2]);
173 for col in 0..cw {
174 out.u[row * cw + col] = line[col * 2];
175 out.v[row * cw + col] = line[col * 2 + 1];
176 }
177 }
178 }
179 _ => {
180 // P010 keeps the sample in the *high* bits of each u16, so the
181 // 8-bit value is the high byte — a shift by 8, not by 2.
182 for row in 0..h {
183 let src = row * y_pitch;
184 let line = &mut row_buf[..w * 2];
185 line.copy_from_slice(&y_plane[src..src + w * 2]);
186 for col in 0..w {
187 out.y[row * w + col] = line[col * 2 + 1];
188 }
189 }
190 for row in 0..ch {
191 let src = row * uv_pitch;
192 let line = &mut row_buf[..cw * 4];
193 line.copy_from_slice(&uv_plane[src..src + cw * 4]);
194 for col in 0..cw {
195 out.u[row * cw + col] = line[col * 4 + 1];
196 out.v[row * cw + col] = line[col * 4 + 3];
197 }
198 }
199 }
200 }
201 Ok(out)
202 })
203 }
204
205 /// Read the frame back as 10-bit I420 (samples in the low 10 bits).
206 ///
207 /// An 8-bit surface is widened rather than refused, so a caller can hold
208 /// one frame type across a mixed-depth timeline.
209 pub fn to_i420_16(&self) -> Result<I420_16> {
210 let (w, h) = self.display_size;
211 let (cw, ch) = ((w as usize).div_ceil(2), (h as usize).div_ceil(2));
212 let (w, h) = (w as usize, h as usize);
213 let mut out = I420_16 {
214 y: vec![0; w * h],
215 u: vec![0; cw * ch],
216 v: vec![0; cw * ch],
217 width: self.display_size.0,
218 height: self.display_size.1,
219 bit_depth: 10,
220 };
221
222 self.with_planes(|mapped| {
223 let y_pitch = mapped.pitch(0).unwrap_or(0) as usize;
224 let uv_pitch = mapped.pitch(1).unwrap_or(0) as usize;
225 let y_plane = mapped
226 .plane(0)
227 .ok_or_else(|| Error::config("VA image has no luma plane"))?;
228 let uv_plane = mapped
229 .plane(1)
230 .ok_or_else(|| Error::config("VA image has no chroma plane"))?;
231
232 // Row at a time, for the reason given in `to_i420`.
233 let mut row_buf = vec![0u8; (uv_pitch.max(y_pitch)).max(w * 2)];
234 match self.bit_depth {
235 8 => {
236 for row in 0..h {
237 let src = row * y_pitch;
238 row_buf[..w].copy_from_slice(&y_plane[src..src + w]);
239 for (dst, &sample) in
240 out.y[row * w..(row + 1) * w].iter_mut().zip(&row_buf[..w])
241 {
242 *dst = u16::from(sample) << 2;
243 }
244 }
245 for row in 0..ch {
246 let src = row * uv_pitch;
247 let line = &mut row_buf[..cw * 2];
248 line.copy_from_slice(&uv_plane[src..src + cw * 2]);
249 for col in 0..cw {
250 out.u[row * cw + col] = u16::from(line[col * 2]) << 2;
251 out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2;
252 }
253 }
254 }
255 _ => {
256 // P010 is 16-bit little endian with the sample in the top ten
257 // bits; the low six are zero padding.
258 for row in 0..h {
259 let src = row * y_pitch;
260 let line = &mut row_buf[..w * 2];
261 line.copy_from_slice(&y_plane[src..src + w * 2]);
262 for col in 0..w {
263 out.y[row * w + col] =
264 u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6;
265 }
266 }
267 for row in 0..ch {
268 let src = row * uv_pitch;
269 let line = &mut row_buf[..cw * 4];
270 line.copy_from_slice(&uv_plane[src..src + cw * 4]);
271 for col in 0..cw {
272 out.u[row * cw + col] =
273 u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6;
274 out.v[row * cw + col] =
275 u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6;
276 }
277 }
278 }
279 }
280 Ok(out)
281 })
282 }
283
284 /// Map the surface's pixels and hand the planes to `read`.
285 ///
286 /// `vaGetImage` into an image kept for the life of the stream, *not*
287 /// `vaDeriveImage`. Deriving looks cheaper — it is a view rather than a
288 /// copy — and it does return the same pixels here (checked row for row),
289 /// but the view is device memory across the PCIe bar: reading a 1080p frame
290 /// through it costs 48 ms against 10 ms for a driver-side copy into system
291 /// memory followed by a normal read (measured, 719-frame loop).
292 fn with_planes<R>(&self, read: impl FnOnce(&MappedImage<'_>) -> Result<R>) -> Result<R> {
293 self.surface.sync()?;
294 let fourcc = if self.bit_depth > 8 {
295 VA_FOURCC_P010
296 } else {
297 VA_FOURCC_NV12
298 };
299 let (w, h) = self.coded_size;
300
301 let mut slot = match self.images.lock() {
302 Ok(slot) => slot,
303 // The lock guards a cached image, not an invariant: a panicking
304 // reader leaves it perfectly usable.
305 Err(poisoned) => poisoned.into_inner(),
306 };
307 let reusable = slot
308 .as_ref()
309 .is_some_and(|image| image.fourcc() == fourcc && image.size() == (w, h));
310 if !reusable {
311 *slot = Some(Image::create(self.surface.display(), fourcc, w, h)?);
312 }
313 let image = slot
314 .as_mut()
315 .ok_or_else(|| Error::config("no readback image"))?;
316 self.surface.read_into(image, 0, 0, w, h)?;
317 let mapped = image.map()?;
318 read(&mapped)
319 }
320}
321
322impl std::fmt::Debug for Frame {
323 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
324 f.debug_struct("Frame")
325 .field("surface", &self.surface.id())
326 .field("timestamp", &self.timestamp)
327 .field("display_size", &self.display_size)
328 .field("bit_depth", &self.bit_depth)
329 .finish()
330 }
331}
332
333/// Deinterleave an NV12 chroma plane into I420 U and V planes.
334///
335/// The same conversion the software path in edith expects on the way out of a
336/// hardware frame; kept as a free function because an encoder's input path
337/// needs it in reverse.
338pub fn nv12_to_i420(
339 y_plane: &[u8],
340 y_pitch: usize,
341 uv_plane: &[u8],
342 uv_pitch: usize,
343 width: usize,
344 height: usize,
345) -> I420 {
346 let (cw, ch) = (width.div_ceil(2), height.div_ceil(2));
347 let mut out = I420 {
348 y: vec![0; width * height],
349 u: vec![0; cw * ch],
350 v: vec![0; cw * ch],
351 width: width as u32,
352 height: height as u32,
353 };
354 for row in 0..height {
355 let src = row * y_pitch;
356 if src + width > y_plane.len() {
357 break;
358 }
359 out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]);
360 }
361 for row in 0..ch {
362 let src = row * uv_pitch;
363 if src + cw * 2 > uv_plane.len() {
364 break;
365 }
366 for col in 0..cw {
367 out.u[row * cw + col] = uv_plane[src + col * 2];
368 out.v[row * cw + col] = uv_plane[src + col * 2 + 1];
369 }
370 }
371 out
372}
373
374/// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
375pub fn i420_to_nv12(
376 src: &I420,
377 y_out: &mut [u8],
378 y_pitch: usize,
379 uv_out: &mut [u8],
380 uv_pitch: usize,
381) {
382 let (w, h) = (src.width as usize, src.height as usize);
383 let (cw, ch) = (w.div_ceil(2), h.div_ceil(2));
384 for row in 0..h {
385 let dst = row * y_pitch;
386 if dst + w > y_out.len() {
387 break;
388 }
389 y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]);
390 }
391 for row in 0..ch {
392 let dst = row * uv_pitch;
393 if dst + cw * 2 > uv_out.len() {
394 break;
395 }
396 for col in 0..cw {
397 uv_out[dst + col * 2] = src.u[row * cw + col];
398 uv_out[dst + col * 2 + 1] = src.v[row * cw + col];
399 }
400 }
401}
402
403#[cfg(test)]
404mod tests {
405 use super::*;
406
407 #[test]
408 fn nv12_round_trips_through_i420() {
409 let (w, h) = (6usize, 4usize);
410 let (y_pitch, uv_pitch) = (8usize, 8usize);
411 let mut y = vec![0u8; y_pitch * h];
412 let mut uv = vec![0u8; uv_pitch * h / 2];
413 for row in 0..h {
414 for col in 0..w {
415 y[row * y_pitch + col] = (row * w + col) as u8;
416 }
417 }
418 for row in 0..h / 2 {
419 for col in 0..w {
420 uv[row * uv_pitch + col] = (100 + row * w + col) as u8;
421 }
422 }
423
424 let i420 = nv12_to_i420(&y, y_pitch, &uv, uv_pitch, w, h);
425 assert_eq!(i420.y.len(), w * h);
426 assert_eq!(i420.u.len(), (w / 2) * (h / 2));
427 assert_eq!(i420.y[0], 0);
428 assert_eq!(i420.y[w], w as u8);
429 // U takes the even bytes of the interleaved plane, V the odd ones.
430 assert_eq!(i420.u[0], 100);
431 assert_eq!(i420.v[0], 101);
432 assert_eq!(i420.u[1], 102);
433
434 let mut y2 = vec![0u8; y_pitch * h];
435 let mut uv2 = vec![0u8; uv_pitch * h / 2];
436 i420_to_nv12(&i420, &mut y2, y_pitch, &mut uv2, uv_pitch);
437 let back = nv12_to_i420(&y2, y_pitch, &uv2, uv_pitch, w, h);
438 assert_eq!(back, i420);
439 }
440
441 /// `to_i420_16` is the lossless 10-bit readback: samples that collapse
442 /// together under 8-bit truncation (`512 >> 2 == 513 >> 2 == 128`) must
443 /// survive distinctly. Skips when there is no VA device, the same gate the
444 /// live GPU tests use.
445 #[test]
446 fn p010_readback_preserves_ten_bits() {
447 let Ok(display) = ec_va::Display::open() else {
448 eprintln!("skipped: no VA display");
449 return;
450 };
451 let (w, h) = (4u32, 4u32);
452 let pool =
453 crate::pool::SurfacePool::new(&display, &ec_va::SurfaceSpec::p010(w, h), 1)
454 .expect("P010 surface pool");
455 let surface = pool.acquire().expect("surface from pool");
456
457 // Synthetic P010: 10-bit samples packed into the high bits of each
458 // u16, exactly how the decoder's P010 surfaces carry them. 512 and 513
459 // both truncate to 128 in 8-bit, so they prove the 16-bit path is not
460 // silently losing the low bits.
461 let y_samples = [512u16, 513, 1023, 5];
462 let mut image = Image::create(&display, VA_FOURCC_P010, w, h).expect("P010 upload image");
463 {
464 let mut mapped = image.map().expect("map upload image");
465 let y_pitch = mapped.pitch(0).expect("luma pitch") as usize;
466 let uv_pitch = mapped.pitch(1).expect("chroma pitch") as usize;
467 if let Some(dst) = mapped.plane_mut(0) {
468 for row in 0..h as usize {
469 for col in 0..w as usize {
470 let sample = y_samples[(row * w as usize + col) % y_samples.len()] << 6;
471 let b = sample.to_le_bytes();
472 let o = row * y_pitch + col * 2;
473 dst[o] = b[0];
474 dst[o + 1] = b[1];
475 }
476 }
477 }
478 if let Some(dst) = mapped.plane_mut(1) {
479 let (u, v) = (512u16 << 6, 1023u16 << 6);
480 let ub = u.to_le_bytes();
481 let vb = v.to_le_bytes();
482 for row in 0..h as usize / 2 {
483 for col in 0..w as usize / 2 {
484 let o = row * uv_pitch + col * 4;
485 dst[o] = ub[0];
486 dst[o + 1] = ub[1];
487 dst[o + 2] = vb[0];
488 dst[o + 3] = vb[1];
489 }
490 }
491 }
492 }
493 surface.write_from(&image, w, h).expect("P010 upload");
494
495 let frame = Frame::new(
496 surface,
497 Arc::new(Mutex::new(None)),
498 0,
499 (w, h),
500 (w, h),
501 10,
502 None,
503 );
504
505 let i16 = frame.to_i420_16().expect("to_i420_16");
506 let i8 = frame.to_i420().expect("to_i420");
507
508 assert_eq!(i16.width, w);
509 assert_eq!(i16.height, h);
510 assert_eq!(i16.bit_depth, 10);
511 let want_y: Vec<u16> = (0..w as usize * h as usize)
512 .map(|i| y_samples[i % y_samples.len()])
513 .collect();
514 assert_eq!(
515 i16.y, want_y,
516 "16-bit luma must preserve the 10-bit samples"
517 );
518 let want_y8: Vec<u8> = want_y.iter().map(|&s| (s >> 2) as u8).collect();
519 assert_eq!(i8.y, want_y8, "8-bit luma must be the >> 2 truncation");
520
521 assert_eq!(i16.u, vec![512u16; 4]);
522 assert_eq!(i16.v, vec![1023u16; 4]);
523 assert_eq!(i8.u, vec![128u8; 4]);
524 assert_eq!(i8.v, vec![255u8; 4]);
525 }
526}