//! What a decoder hands out: a picture held in its GPU ring slot (Vulkan) or //! a VA-API frame, converted on request to I420, 10-bit I420, packed RGB or a //! DMA-BUF. use std::cell::RefCell; use std::rc::Rc; use ec_av1_syntax::{FilmGrainParams, SequenceHeader}; use ec_core::color::Matrix; #[cfg(target_os = "linux")] use ec_core::color::{ColorDescription, Tags}; use ec_vk::{ Av1DecodeSession, H264DecodeSession, H265DecodeSession, Vp9DecodeSession, }; use crate::error::{Error, Result}; use crate::hw::{RgbOrder, RgbOutput}; use crate::picture::{ Colour, I420, I420_16, RgbPicture, i420_16_to_p010, i420_to_rgb, i420_to_nv12, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb, }; use crate::vkdec_av1::{synthesize, synthesize16}; #[cfg(target_os = "linux")] use crate::frame::Frame; #[cfg(target_os = "linux")] use crate::picture::DmaBufPicture; /// One decoded picture, as a handle on its ring slot in the decode session. pub struct HwPicture { /// Presentation timestamp of the access unit the picture came from. pub timestamp: i64, /// Display width in luma samples. pub width: u32, /// Display height in luma samples. pub height: u32, /// Luma bit depth: 8 or 10. pub bit_depth: u8, /// Colour metadata, when the decoder resolved some. pub colour: Option, source: Source, } enum Source { Vk(VkPicture), #[cfg(target_os = "linux")] Va(Frame), } impl HwPicture { pub(crate) fn vk(timestamp: i64, picture: VkPicture) -> HwPicture { HwPicture { timestamp, width: picture.width, height: picture.height, bit_depth: picture.bit_depth, colour: None, source: Source::Vk(picture), } } #[cfg(target_os = "linux")] pub(crate) fn va(frame: Frame) -> HwPicture { HwPicture { timestamp: frame.timestamp, width: frame.display_size.0, height: frame.display_size.1, bit_depth: frame.bit_depth, colour: frame.colour, source: Source::Va(frame), } } /// 8-bit I420 at display size. A 10-bit picture is truncated to 8 bits. pub fn to_i420(&self) -> Result { match &self.source { Source::Vk(picture) => picture.i420(), #[cfg(target_os = "linux")] Source::Va(frame) => frame.to_i420(), } } /// 10-bit I420 at display size. An 8-bit picture is widened to 10 bits. pub fn to_i420_16(&self) -> Result { match &self.source { Source::Vk(picture) => picture.i420_16(), #[cfg(target_os = "linux")] Source::Va(frame) => frame.to_i420_16(), } } /// Packed RGB, scaled and byte-ordered as `output` asks. pub fn to_rgb(&self, output: &RgbOutput) -> Result { let mut dst = RgbPicture::default(); self.rgb_into(output, &mut dst)?; Ok(dst) } /// [`HwPicture::to_rgb`] into `dst`, reusing its allocation. pub fn rgb_into(&self, output: &RgbOutput, dst: &mut RgbPicture) -> Result<()> { match &self.source { Source::Vk(picture) => picture.rgb(output, dst), #[cfg(target_os = "linux")] Source::Va(frame) => { let i420 = frame.to_i420()?; let matrix = frame .colour .map(|c| c.description.matrix) .unwrap_or_else(|| default_matrix(i420.height)); *dst = i420_to_rgb( &i420, output.bound(), output.order == RgbOrder::Bgra, matrix, ); Ok(()) } } } /// One DMA-BUF of NV12 or P010 planes at display size, with film grain applied when the picture has it. #[cfg(target_os = "linux")] pub fn export_dmabuf(&self) -> Result { match &self.source { Source::Vk(picture) => picture.export(), Source::Va(frame) => Ok(dmabuf_from_prime(frame.export_prime()?)?), } } } /// The GPU ring of one decode session: a token per slot, held by every picture still using the slot. pub(crate) struct Ring { tokens: Vec>, } impl Ring { pub(crate) fn new(len: u32) -> Ring { Ring { tokens: (0..len).map(|_| Rc::new(())).collect(), } } /// The first free slot, or a new one from `grow` when every slot is held. pub(crate) fn take(&mut self, grow: impl FnOnce() -> Result) -> Result { let index = match self .tokens .iter() .position(|token| Rc::strong_count(token) == 1) { Some(index) => index, None => { let index = grow()? as usize; if index != self.tokens.len() { return Err(Error::config("output ring out of step with the decoder")); } self.tokens.push(Rc::new(())); index } }; Ok(Slot { index: index as u32, _held: self.tokens[index].clone(), }) } } /// A ring slot in use. The slot is free again once every copy of this handle is dropped. #[derive(Clone)] pub(crate) struct Slot { index: u32, _held: Rc<()>, } impl Slot { pub(crate) fn index(&self) -> u32 { self.index } } /// The decode session's output images, shared with every picture decoded in it. #[derive(Clone)] pub(crate) enum Surfaces { H264(Rc>), H265(Rc>), Av1(Rc>), Vp9(Rc>), } impl Surfaces { fn nv12(&self, slot: u32, width: u32, height: u32) -> Result<(Vec, Vec)> { Ok(match self { Surfaces::H264(s) => s.borrow_mut().read_output(slot, width, height)?, Surfaces::H265(s) => s.borrow_mut().read_output(slot, width, height)?, Surfaces::Av1(s) => s.borrow_mut().read_output(slot, width, height)?, Surfaces::Vp9(s) => s.borrow_mut().read_output(slot, width, height)?, }) } fn rgb( &self, slot: u32, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], dst: &mut Vec, ) -> Result<()> { match self { Surfaces::H264(s) => s .borrow_mut() .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?, Surfaces::H265(s) => s .borrow_mut() .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?, Surfaces::Av1(s) => s .borrow_mut() .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?, Surfaces::Vp9(s) => s .borrow_mut() .read_output_rgb(slot, crop, out, bgra, coeffs, dst)?, } Ok(()) } #[cfg(target_os = "linux")] fn export(&self, slot: u32, width: u32, height: u32) -> Result { Ok(match self { Surfaces::H264(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?, Surfaces::H265(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?, Surfaces::Av1(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?, Surfaces::Vp9(s) => s.borrow_mut().read_output_dmabuf(slot, width, height)?, }) } } /// A picture in a ring slot: its display size, bit depth, matrix and, for AV1, the film grain to apply when it is shown. #[derive(Clone)] pub(crate) struct VkPicture { surfaces: Surfaces, slot: Slot, width: u32, height: u32, bit_depth: u8, matrix: Matrix, grain: Option, ring: Option>>, grained: Rc>>, } #[derive(Clone)] struct Grain { params: FilmGrainParams, seq: SequenceHeader, } impl VkPicture { pub(crate) fn new( surfaces: Surfaces, slot: Slot, (width, height): (u32, u32), bit_depth: u8, matrix: Matrix, ) -> VkPicture { VkPicture { surfaces, slot, width, height, bit_depth, matrix, grain: None, ring: None, grained: Rc::new(RefCell::new(None)), } } pub(crate) fn with_ring(mut self, ring: Rc>) -> VkPicture { self.ring = Some(ring); self } /// This picture as it is shown with `grain`: unchanged when the frame applies none. pub(crate) fn with_grain(&self, params: &FilmGrainParams, seq: &SequenceHeader) -> VkPicture { let mut shown = self.clone(); if params.apply_grain { shown.grained = Rc::new(RefCell::new(None)); shown.grain = Some(Grain { params: params.clone(), seq: seq.clone(), }); } shown } fn read(&self) -> Result<(Vec, Vec)> { self.surfaces.nv12( self.slot.index, self.width.next_multiple_of(2), self.height.next_multiple_of(2), ) } fn i420(&self) -> Result { let (y, uv) = self.read()?; let frame = semi_planar_to_i420( self.bit_depth, &y, &uv, self.width.next_multiple_of(2) as usize, (0, 0), (self.width, self.height), )?; Ok(match &self.grain { Some(g) => synthesize(frame, &g.params, &g.seq), None => frame, }) } fn i420_16(&self) -> Result { let (y, uv) = self.read()?; let frame = semi_planar_to_i420_16( self.bit_depth, &y, &uv, self.width.next_multiple_of(2) as usize, (0, 0), (self.width, self.height), )?; Ok(match &self.grain { Some(g) => synthesize16(frame, &g.params, &g.seq), None => frame, }) } fn rgb(&self, output: &RgbOutput, dst: &mut RgbPicture) -> Result<()> { let bgra = output.order == RgbOrder::Bgra; if self.grain.is_some() { if self.bit_depth != 8 { return Err(Error::unsupported( "Vulkan AV1 film grain", "RGB of 10-bit output", )); } *dst = i420_to_rgb(&self.i420()?, output.bound(), bgra, self.matrix); return Ok(()); } let (w, h) = rgb_size(self.width, self.height, output.bound()); self.surfaces.rgb( self.slot.index, (0, 0, self.width, self.height), (w, h), bgra, yuv_to_rgb(self.matrix).words(), &mut dst.data, )?; dst.width = w; dst.height = h; dst.stride = w * 4; Ok(()) } #[cfg(target_os = "linux")] fn export(&self) -> Result { match &self.grain { None => Ok(self .surfaces .export(self.slot.index, self.width, self.height)? .into()), Some(grain) => self.export_grained(grain), } } #[cfg(target_os = "linux")] fn export_grained(&self, grain: &Grain) -> Result { let (Surfaces::Av1(session), Some(ring)) = (&self.surfaces, &self.ring) else { return Err(Error::unsupported( "Vulkan DMA-BUF export", "film grain outside AV1 or without an output ring", )); }; let mut grained = self.grained.borrow_mut(); let slot = match grained.take() { Some(slot) => slot, None => self.grain_slot(session, ring, grain)?, }; let export = session.borrow_mut().read_output_dmabuf( slot.index(), self.width, self.height, ); *grained = Some(slot); Ok(export?.into()) } #[cfg(target_os = "linux")] fn grain_slot( &self, session: &Rc>, ring: &Rc>, grain: &Grain, ) -> Result { let (width, height) = (self.width, self.height); let (y, uv) = self.read()?; let (y, uv) = if self.bit_depth == 8 { let frame = semi_planar_to_i420(8, &y, &uv, width as usize, (0, 0), (width, height))?; let frame = synthesize(frame, &grain.params, &grain.seq); let luma = width as usize * height as usize; let (mut y, mut uv) = (vec![0; luma], vec![0; luma / 2]); i420_to_nv12(&frame, &mut y, width as usize, &mut uv, width as usize); (y, uv) } else { let frame = semi_planar_to_i420_16(self.bit_depth, &y, &uv, width as usize, (0, 0), (width, height))?; i420_16_to_p010(&synthesize16(frame, &grain.params, &grain.seq)) }; let slot = ring .borrow_mut() .take(|| Ok(session.borrow_mut().add_ring_slot()?))?; session .borrow_mut() .upload_output(slot.index(), (width, height), &y, &uv)?; Ok(slot) } } #[cfg(target_os = "linux")] fn default_matrix(height: u32) -> Matrix { ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix } #[cfg(target_os = "linux")] fn dmabuf_from_prime(surface: ec_va::PrimeSurface) -> Result { let planes: Vec<(u32, u32, u32)> = surface .layers .iter() .flat_map(|layer| layer.planes.iter().copied()) .collect(); let [y, uv] = planes.as_slice() else { return Err(Error::config("exported surface is not a two-plane 4:2:0 picture")); }; let plane = |&(object, offset, pitch): &(u32, u32, u32)| ec_vk::DmaBufPlane { fd: object as usize, offset, pitch, }; let modifier = surface.objects.first().map_or(0, |o| o.modifier); Ok(DmaBufPicture { fds: surface.objects.into_iter().map(|o| o.fd).collect(), fourcc: surface.fourcc, modifier, width: surface.width, height: surface.height, planes: [plane(y), plane(uv)], }) }