//! Pixel buffers and conversions that need no VA-API: planar I420 and its //! 10-bit sibling, the colour metadata, and the NV12 conversions. use ec_core::color::{ColorDescription, ContentLight, Matrix}; use crate::error::{Error, Result}; /// A stream's colour metadata, resolved from its own headers: VUI tags for the /// primaries/transfer/matrix triplet, and — for HEVC — the two HDR prefix SEI /// messages for the peak the mastering grade and the content itself declared. /// No container tier here: ec-hw only ever sees the elementary stream, so a /// caller that also holds the container's tags resolves those over this. #[derive(Debug, Clone, Copy, PartialEq)] pub struct Colour { /// Matrix/transfer/range, resolved from the bitstream's own VUI. pub description: ColorDescription, /// HDR peak: MaxCLL/MaxFALL and the mastering display's luminance, when /// the stream carried them (HEVC prefix SEI only). pub light: ContentLight, } /// 8-bit planar 4:2:0, the currency edith's software path speaks. #[derive(Debug, Clone, PartialEq, Eq)] pub struct I420 { /// Luma plane, `width * height`. pub y: Vec, /// Cb plane, `(width + 1) / 2 * ((height + 1) / 2)`. pub u: Vec, /// Cr plane, same size as `u`. pub v: Vec, /// Width in luma samples. pub width: u32, /// Height in luma samples. pub height: u32, } /// A packed 32-bit RGB picture, alpha 255, `stride` bytes per row. #[derive(Debug, Clone, Default, PartialEq, Eq)] pub struct RgbPicture { /// Pixels, `stride * height` bytes. pub data: Vec, /// Width in pixels. pub width: u32, /// Height in pixels. pub height: u32, /// Row stride in bytes: `width * 4`. pub stride: u32, } impl RgbPicture { pub(crate) fn new(data: Vec, width: u32, height: u32) -> Self { RgbPicture { data, width, height, stride: width * 4, } } } /// A decoded picture as DMA-BUF file descriptors: NV12 or P010, Y then UV, in an exportable layout. #[cfg(target_os = "linux")] #[derive(Debug)] pub struct DmaBufPicture { /// The DMA-BUF objects. Each is closed when the picture drops. pub fds: Vec, /// DRM fourcc: NV12 or P010. pub fourcc: u32, /// DRM format modifier, 0 for linear. pub modifier: u64, /// Width in luma samples. pub width: u32, /// Height in luma samples. pub height: u32, /// Y plane then UV plane. pub planes: [ec_vk::DmaBufPlane; 2], } #[cfg(target_os = "linux")] impl From for DmaBufPicture { fn from(export: ec_vk::DmaBufExport) -> DmaBufPicture { let fourcc = if export.p010 { u32::from_le_bytes(*b"P010") } else { u32::from_le_bytes(*b"NV12") }; DmaBufPicture { fds: vec![export.fd], fourcc, modifier: export.modifier, width: export.width, height: export.height, planes: export.planes, } } } #[cfg(target_os = "linux")] impl DmaBufPicture { /// A second handle on the same memory, for a picture shown again from a reference. pub fn try_clone(&self) -> std::io::Result { Ok(DmaBufPicture { fds: self .fds .iter() .map(|fd| fd.try_clone()) .collect::>()?, fourcc: self.fourcc, modifier: self.modifier, width: self.width, height: self.height, planes: self.planes, }) } } /// The YUV to RGB coefficients for a matrix; BT.2020 is taken as BT.709, the nearest integer set here. pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb { match matrix { Matrix::Bt601 => ec_dsp::rgb::BT601_LIMITED, Matrix::Bt709 | Matrix::Bt2020Ncl => ec_dsp::rgb::BT709_LIMITED, } } /// Packed RGB of an 8-bit I420 picture, scaled into `bound`, converted on the CPU with the coefficients of `matrix`. pub(crate) fn i420_to_rgb( frame: &I420, bound: (Option, Option), bgra: bool, matrix: Matrix, ) -> RgbPicture { let (w, h) = rgb_size(frame.width, frame.height, bound); let data = ec_dsp::rgb::i420_to_packed( &frame.y, &frame.u, &frame.v, (frame.width as usize, frame.height as usize), (w as usize, h as usize), bgra, &yuv_to_rgb(matrix), ); RgbPicture::new(data, w, h) } /// Output size of an RGB picture of `width` x `height` fit inside `(max_width, max_height)` keeping the aspect; a scaled height is even. pub(crate) fn rgb_size(width: u32, height: u32, bound: (Option, Option)) -> (u32, u32) { let (w, h) = (u64::from(width), u64::from(height)); let limit = |max: Option, full: u64| max.filter(|&m| m > 0).map_or(full, u64::from).min(full); let (mw, mh) = (limit(bound.0, w), limit(bound.1, h)); if mw == w && mh == h { return (width, height); } if mw * h <= mh * w { let even = 2 * ((h * mw + w) / (2 * w)); (mw as u32, even.clamp(2, h) as u32) } else { let even = (mh & !1).max(2); let scaled = (w * even + h / 2) / h; (scaled.clamp(1, w) as u32, even as u32) } } /// 10-bit planar 4:2:0, samples right-aligned in the low 10 bits. #[derive(Debug, Clone, PartialEq, Eq)] pub struct I420_16 { /// Luma plane. pub y: Vec, /// Cb plane. pub u: Vec, /// Cr plane. pub v: Vec, /// Width in luma samples. pub width: u32, /// Height in luma samples. pub height: u32, /// Luma bit depth: always 10 for this format. pub bit_depth: u8, } /// Deinterleave an NV12 chroma plane into I420 U and V planes. /// /// The same conversion the software path in edith expects on the way out of a /// hardware frame; kept as a free function because an encoder's input path /// needs it in reverse. pub fn nv12_to_i420( y_plane: &[u8], y_pitch: usize, uv_plane: &[u8], uv_pitch: usize, width: usize, height: usize, ) -> I420 { let (cw, ch) = (width.div_ceil(2), height.div_ceil(2)); let mut out = I420 { y: vec![0; width * height], u: vec![0; cw * ch], v: vec![0; cw * ch], width: width as u32, height: height as u32, }; for row in 0..height { let src = row * y_pitch; if src + width > y_plane.len() { break; } out.y[row * width..(row + 1) * width].copy_from_slice(&y_plane[src..src + width]); } for row in 0..ch { let src = row * uv_pitch; if src + cw * 2 > uv_plane.len() { break; } for col in 0..cw { out.u[row * cw + col] = uv_plane[src + col * 2]; out.v[row * cw + col] = uv_plane[src + col * 2 + 1]; } } out } pub(crate) fn semi_planar_to_i420( bit_depth: u8, y: &[u8], uv: &[u8], pitch: usize, origin: (usize, usize), size: (u32, u32), ) -> Result { let bytes = if bit_depth == 8 { 1 } else { 2 }; let pitch = pitch * bytes; let (x, top) = (origin.0 * bytes, origin.1); let y = y.get(top * pitch + x..).unwrap_or(&[]); let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]); let (width, height) = size; let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2)); let mut out = I420 { y: vec![0; width as usize * height as usize], u: vec![0; cw * ch], v: vec![0; cw * ch], width, height, }; fill_i420(&mut out, bit_depth, y, pitch, uv, pitch)?; Ok(out) } /// Copy NV12/P010 planes into `out`, after validating every plane against it. pub(crate) fn fill_i420_16( out: &mut I420_16, bit_depth: u8, y_plane: &[u8], y_pitch: usize, uv_plane: &[u8], uv_pitch: usize, ) -> Result<()> { let (w, h) = (out.width as usize, out.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let bytes = if bit_depth == 8 { 1 } else { 2 }; check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; match bit_depth { 8 => { for row in 0..h { let line = plane_row(y_plane, y_pitch, row, w); for (dst, &sample) in out.y[row * w..(row + 1) * w].iter_mut().zip(line) { *dst = u16::from(sample) << 2; } } for row in 0..ch { let line = plane_row(uv_plane, uv_pitch, row, cw * 2); for col in 0..cw { out.u[row * cw + col] = u16::from(line[col * 2]) << 2; out.v[row * cw + col] = u16::from(line[col * 2 + 1]) << 2; } } } _ => { // P010 is 16-bit little endian with the sample in the top ten // bits; the low six are zero padding. for row in 0..h { let line = plane_row(y_plane, y_pitch, row, w * 2); for col in 0..w { out.y[row * w + col] = u16::from_le_bytes([line[col * 2], line[col * 2 + 1]]) >> 6; } } for row in 0..ch { let line = plane_row(uv_plane, uv_pitch, row, cw * 4); for col in 0..cw { out.u[row * cw + col] = u16::from_le_bytes([line[col * 4], line[col * 4 + 1]]) >> 6; out.v[row * cw + col] = u16::from_le_bytes([line[col * 4 + 2], line[col * 4 + 3]]) >> 6; } } } } Ok(()) } pub(crate) fn semi_planar_to_i420_16( bit_depth: u8, y: &[u8], uv: &[u8], pitch: usize, origin: (usize, usize), size: (u32, u32), ) -> Result { let bytes = if bit_depth == 8 { 1 } else { 2 }; let pitch = pitch * bytes; let (x, top) = (origin.0 * bytes, origin.1); let y = y.get(top * pitch + x..).unwrap_or(&[]); let uv = uv.get((top / 2) * pitch + x..).unwrap_or(&[]); let (width, height) = size; let (cw, ch) = ((width as usize).div_ceil(2), (height as usize).div_ceil(2)); let mut out = I420_16 { y: vec![0; width as usize * height as usize], u: vec![0; cw * ch], v: vec![0; cw * ch], width, height, bit_depth: 10, }; fill_i420_16(&mut out, bit_depth, y, pitch, uv, pitch)?; Ok(out) } /// Copy NV12/P010 planes into `out`, after validating every plane against it. pub(crate) fn fill_i420( out: &mut I420, bit_depth: u8, y_plane: &[u8], y_pitch: usize, uv_plane: &[u8], uv_pitch: usize, ) -> Result<()> { let (w, h) = (out.width as usize, out.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); let bytes = if bit_depth == 8 { 1 } else { 2 }; check_plane("luma", y_plane.len(), y_pitch, h, w * bytes)?; check_plane("chroma", uv_plane.len(), uv_pitch, ch, cw * 2 * bytes)?; match bit_depth { 8 => { for row in 0..h { out.y[row * w..(row + 1) * w].copy_from_slice(plane_row(y_plane, y_pitch, row, w)); } for row in 0..ch { let line = plane_row(uv_plane, uv_pitch, row, cw * 2); for col in 0..cw { out.u[row * cw + col] = line[col * 2]; out.v[row * cw + col] = line[col * 2 + 1]; } } } _ => { // P010 keeps the sample in the *high* bits of each u16, so the // 8-bit value is the high byte — a shift by 8, not by 2. for row in 0..h { let line = plane_row(y_plane, y_pitch, row, w * 2); for col in 0..w { out.y[row * w + col] = line[col * 2 + 1]; } } for row in 0..ch { let line = plane_row(uv_plane, uv_pitch, row, cw * 4); for col in 0..cw { out.u[row * cw + col] = line[col * 4 + 1]; out.v[row * cw + col] = line[col * 4 + 3]; } } } } Ok(()) } fn plane_row(plane: &[u8], pitch: usize, row: usize, len: usize) -> &[u8] { &plane[row * pitch..row * pitch + len] } /// Check that `rows` rows of `row_bytes` bytes at `pitch` fit in a plane of /// `len` bytes. A lost or half-initialised GPU context can hand back a short /// or odd mapping; this turns what would be a slice panic into an error. pub(crate) fn check_plane( name: &str, len: usize, pitch: usize, rows: usize, row_bytes: usize, ) -> Result<()> { if rows == 0 || row_bytes == 0 { return Ok(()); } let need = (rows - 1) .checked_mul(pitch) .and_then(|n| n.checked_add(row_bytes)); match need { Some(need) if pitch >= row_bytes && need <= len => Ok(()), _ => Err(Error::config(format!( "VA image {name} plane does not cover the frame: {rows} rows x {row_bytes} bytes at pitch {pitch}, mapped {len} bytes" ))), } } pub(crate) fn i420_16_to_p010(src: &I420_16) -> (Vec, Vec) { let le = |v: &u16| (v << 6).to_le_bytes(); let y = src.y.iter().flat_map(le).collect(); let uv = src .u .iter() .zip(&src.v) .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten()) .collect(); (y, uv) } /// Interleave I420 chroma into an NV12 buffer, for the encoder input path. pub fn i420_to_nv12( src: &I420, y_out: &mut [u8], y_pitch: usize, uv_out: &mut [u8], uv_pitch: usize, ) { let (w, h) = (src.width as usize, src.height as usize); let (cw, ch) = (w.div_ceil(2), h.div_ceil(2)); for row in 0..h { let dst = row * y_pitch; if dst + w > y_out.len() { break; } y_out[dst..dst + w].copy_from_slice(&src.y[row * w..row * w + w]); } for row in 0..ch { let dst = row * uv_pitch; if dst + cw * 2 > uv_out.len() { break; } for col in 0..cw { uv_out[dst + col * 2] = src.u[row * cw + col]; uv_out[dst + col * 2 + 1] = src.v[row * cw + col]; } } }