diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 17074eaf..a5e27963 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -5,7 +5,10 @@ //! cargo run -p ec-hw --example hw_decode -- //! ``` +use std::collections::HashSet; use std::fs; +use std::os::fd::AsRawFd; +use std::os::unix::fs::MetadataExt; use std::path::{Path, PathBuf}; use std::process::Command; @@ -112,9 +115,64 @@ fn main() { own_av1(&dir); vp9_cases(&dir); dmabuf_cases(&dir); + mixed_cases(&dir); seek_case(&dir); } +const MIXED_PASSES: usize = 2; + +fn mixed_cases(dir: &Path) { + let h264 = fs::read(dir.join("bf1280.h264")).expect("read bf1280"); + let ten = fs::read(dir.join("ten.hevc")).expect("read ten.hevc"); + let gpu = ec_vk::Gpu::open().expect("Vulkan device"); + mixed_case("bf1280.h264", Codec::H264, &h264_units(&h264), false, &gpu); + mixed_case("ten.hevc", Codec::H265, &nal_units(&ten), true, &gpu); +} + +fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) { + let mut reference = if ten { + HwDecoder::open_16(codec) + } else { + HwDecoder::open(codec) + } + .expect("open decoder"); + let expected = decoded_planes(&mut reference, units, ten); + + let mut decoder = HwDecoder::open(codec).expect("open mixed decoder"); + assert_eq!(decoder.backend(), Backend::Vk, "{label}: mixed must decode on Vulkan"); + let mut exports = 0usize; + let mut inodes = HashSet::new(); + for _ in 0..MIXED_PASSES { + decoder.reset(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode mixed"); + } + decoder.flush().expect("flush mixed"); + let mut index = 0usize; + while let Some(picture) = decoder.next_picture().expect("next picture") { + let planes = if ten && index % 2 == 0 { + p010_planes(&picture.to_i420_16().expect("to_i420_16")) + } else { + let dmabuf = picture.export_dmabuf().expect("export DMA-BUF"); + for fd in &dmabuf.fds { + let path = format!("/proc/self/fd/{}", fd.as_raw_fd()); + inodes.insert(fs::metadata(path).expect("fd inode").ino()); + } + exports += 1; + read_back(gpu, dmabuf) + }; + assert!(planes == expected[index], "{label}: picture {index} differs"); + index += 1; + } + assert_eq!(index, expected.len(), "{label}: picture count"); + } + assert!(inodes.len() < exports, "{label}: DMA-BUF slots are not reused"); + println!( + "{label} mixed: {exports} DMA-BUF exports, {} distinct fd inodes, all pictures match", + inodes.len(), + ); +} + fn dmabuf_cases(dir: &Path) { let h264 = fs::read(dir.join("bf1280.h264")).expect("read bf1280"); dmabuf_case("bf1280.h264", Codec::H264, &h264_units(&h264), false); diff --git a/crates/ec-hw/src/hevc_dpb.rs b/crates/ec-hw/src/hevc_dpb.rs index 4f3de5f4..28644e90 100644 --- a/crates/ec-hw/src/hevc_dpb.rs +++ b/crates/ec-hw/src/hevc_dpb.rs @@ -22,6 +22,7 @@ pub(crate) enum Mark { pub(crate) struct StoredPicture { pub(crate) surface: S, pub(crate) poc: i32, + #[cfg_attr(not(target_os = "linux"), allow(dead_code))] pub(crate) timestamp: i64, pub(crate) mark: Mark, /// Still to be handed to the caller. diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index a99e5e84..da9b7f30 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -10,11 +10,10 @@ use std::cell::RefCell; use std::collections::VecDeque; use crate::error::{Error, Result}; -use crate::picture::{Decoded, I420, I420_16, RgbPicture}; +use crate::output::HwPicture; +use crate::picture::{I420, I420_16, RgbPicture}; #[cfg(target_os = "linux")] -use crate::picture::{DmaBufPicture, i420_to_rgb}; -#[cfg(target_os = "linux")] -use ec_core::color::{ColorDescription, Matrix, Tags}; +use crate::picture::DmaBufPicture; use crate::rate::{RateFeedback, hrd_buffer_ms}; use crate::types::{ Codec, CodedFrame, EncCodec, EncoderConfig, FrameMetadata, H264Profile, RateControlMode, @@ -51,6 +50,10 @@ pub enum Direction { /// Profile of a [`Capability`], 4:2:0 only. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CodecProfile { + /// H.264 Constrained Baseline, 8-bit. + H264ConstrainedBaseline, + /// H.264 Main, 8-bit. + H264Main, /// H.264 High, 8-bit. H264High, /// H.265 Main, 8-bit. @@ -63,6 +66,8 @@ pub enum CodecProfile { Av1Main10, /// VP9 Profile 0, 8-bit. Vp9Profile0, + /// VP9 Profile 2, 10-bit. + Vp9Profile2, } /// One codec, profile, direction and backend this machine offers. @@ -212,10 +217,12 @@ fn va_capabilities(out: &mut Vec) { impl CodecProfile { fn codec(self) -> Codec { match self { - CodecProfile::H264High => Codec::H264, + CodecProfile::H264ConstrainedBaseline + | CodecProfile::H264Main + | CodecProfile::H264High => Codec::H264, CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, - CodecProfile::Vp9Profile0 => Codec::Vp9, + CodecProfile::Vp9Profile0 | CodecProfile::Vp9Profile2 => Codec::Vp9, } } } @@ -225,10 +232,13 @@ fn va_profiles(profile: ec_va::Profile, rt_formats: u32) -> Vec { let yuv420 = ec_va::va::VA_RT_FORMAT_YUV420; let yuv420_10 = ec_va::va::VA_RT_FORMAT_YUV420_10; match profile { + ec_va::Profile::H264ConstrainedBaseline => vec![CodecProfile::H264ConstrainedBaseline], + ec_va::Profile::H264Main => vec![CodecProfile::H264Main], ec_va::Profile::H264High => vec![CodecProfile::H264High], ec_va::Profile::HEVCMain => vec![CodecProfile::H265Main], ec_va::Profile::HEVCMain10 => vec![CodecProfile::H265Main10], ec_va::Profile::VP9Profile0 => vec![CodecProfile::Vp9Profile0], + ec_va::Profile::VP9Profile2 if rt_formats & yuv420_10 != 0 => vec![CodecProfile::Vp9Profile2], ec_va::Profile::AV1Profile0 => [ (yuv420, CodecProfile::Av1Main), (yuv420_10, CodecProfile::Av1Main10), @@ -249,6 +259,9 @@ fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, + ec_vk::CodecProfile::Vp9Profile2 => CodecProfile::Vp9Profile2, + ec_vk::CodecProfile::H264ConstrainedBaseline => CodecProfile::H264ConstrainedBaseline, + ec_vk::CodecProfile::H264Main => CodecProfile::H264Main, } } @@ -948,7 +961,7 @@ impl VkDecoder { } } - fn next_frame(&mut self) -> Option<(i64, Decoded)> { + fn next_frame(&mut self) -> Option { match self { VkDecoder::H264(d) => d.next_frame(), VkDecoder::H265(d) => d.next_frame(), @@ -993,56 +1006,47 @@ pub struct RgbOutput { pub max_width: Option, } -#[derive(Debug, Clone, Copy, PartialEq, Eq)] -pub(crate) enum Mode { - I420, - I420_16, - Rgb(RgbOutput), - #[cfg(target_os = "linux")] - DmaBuf, -} - /// A hardware decoder on whichever backend opened. pub struct HwDecoder { inner: DecInner, born_epoch: u64, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] codec: Codec, - mode: Mode, + rgb: Option, #[cfg_attr(not(target_os = "linux"), allow(dead_code))] replay: Option, i64)>>, } impl HwDecoder { - /// Open a decoder for `codec` that hands out I420. Every codec tries Vulkan Video first, then VA-API (Linux). + /// Open a decoder for `codec`. Every codec tries Vulkan Video first, then VA-API (Linux). pub fn open(codec: Codec) -> Result { - HwDecoder::open_mode(codec, Mode::I420) + HwDecoder::open_with(codec, None) } - /// Open a decoder for `codec` that hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. + /// Open a decoder for `codec` whose [`HwDecoder::next_rgb`] hands out packed RGB, converted on the GPU by Vulkan and on the CPU by VA-API. pub fn open_rgb(codec: Codec, output: RgbOutput) -> Result { - HwDecoder::open_mode(codec, Mode::Rgb(output)) + HwDecoder::open_with(codec, Some(output)) } - /// Open a decoder for `codec` that hands out 10-bit I420 ([`HwDecoder::next_frame_16`]). 8-bit streams are widened to 10 bits. + /// Same as [`HwDecoder::open`]: every picture can be asked for 10-bit I420 with [`HwPicture::to_i420_16`]. pub fn open_16(codec: Codec) -> Result { - HwDecoder::open_mode(codec, Mode::I420_16) + HwDecoder::open(codec) } - /// Open a decoder for `codec` that hands out each picture as DMA-BUF file descriptors ([`HwDecoder::next_dmabuf`]). Linux only. + /// Same as [`HwDecoder::open`]: every picture can be asked for DMA-BUF file descriptors with [`HwPicture::export_dmabuf`]. Linux only. #[cfg(target_os = "linux")] pub fn open_dmabuf(codec: Codec) -> Result { - HwDecoder::open_mode(codec, Mode::DmaBuf) + HwDecoder::open(codec) } - fn open_mode(codec: Codec, mode: Mode) -> Result { + fn open_with(codec: Codec, rgb: Option) -> Result { let mut reasons = Vec::new(); let born_epoch = crate::reset::gpu_reset_epoch(); let vk = vk_grace().and_then(|()| match codec { - Codec::H264 => VkH264Decoder::new(mode).map(VkDecoder::H264), - Codec::H265 => VkH265Decoder::new(mode).map(VkDecoder::H265), - Codec::Av1 => VkAv1Decoder::new(mode).map(VkDecoder::Av1), - Codec::Vp9 => VkVp9Decoder::new(mode).map(VkDecoder::Vp9), + Codec::H264 => VkH264Decoder::new().map(VkDecoder::H264), + Codec::H265 => VkH265Decoder::new().map(VkDecoder::H265), + Codec::Av1 => VkAv1Decoder::new().map(VkDecoder::Av1), + Codec::Vp9 => VkVp9Decoder::new().map(VkDecoder::Vp9), }); match vk { Ok(inner) => { @@ -1050,7 +1054,7 @@ impl HwDecoder { inner: DecInner::Vk(inner), born_epoch, codec, - mode, + rgb, replay: Some(Vec::new()), }); } @@ -1064,7 +1068,7 @@ impl HwDecoder { inner: DecInner::Va(inner), born_epoch, codec, - mode, + rgb, replay: None, }); } @@ -1115,93 +1119,59 @@ impl HwDecoder { result } - /// The next picture in display order, as 8-bit I420 with its timestamp. An error on a decoder opened with [`HwDecoder::open_rgb`] or [`HwDecoder::open_16`]. + /// The next picture in display order, held in its decode slot until dropped. Convert it with the `to_*` methods of [`HwPicture`]. + pub fn next_picture(&mut self) -> Result> { + self.pull() + } + + /// The next picture in display order, as 8-bit I420 with its timestamp. pub fn next_frame(&mut self) -> Result> { - if self.mode != Mode::I420 { - return Err(Error::config( - "next_frame on a decoder not opened as 8-bit I420", - )); - } match self.pull()? { None => Ok(None), - Some((ts, Decoded::I420(frame))) => Ok(Some((ts, frame))), - Some(_) => Err(Error::config("non-I420 picture from an I420 decoder")), + Some(picture) => Ok(Some((picture.timestamp, picture.to_i420()?))), } } - /// The next picture in display order, as 10-bit I420 with its timestamp. An error on a decoder not opened with [`HwDecoder::open_16`]. + /// The next picture in display order, as 10-bit I420 with its timestamp. pub fn next_frame_16(&mut self) -> Result> { - if self.mode != Mode::I420_16 { - return Err(Error::config( - "next_frame_16 on a decoder not opened with open_16", - )); - } match self.pull()? { None => Ok(None), - Some((ts, Decoded::I420_16(frame))) => Ok(Some((ts, frame))), - Some(_) => Err(Error::config("non-16-bit picture from a 16-bit decoder")), + Some(picture) => Ok(Some((picture.timestamp, picture.to_i420_16()?))), } } - /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. An error on a decoder not opened with [`HwDecoder::open_dmabuf`]. + /// The next picture in display order, as DMA-BUF file descriptors with its timestamp. Linux only. #[cfg(target_os = "linux")] pub fn next_dmabuf(&mut self) -> Result> { - if self.mode != Mode::DmaBuf { - return Err(Error::config( - "next_dmabuf on a decoder not opened with open_dmabuf", - )); - } match self.pull()? { None => Ok(None), - Some((ts, Decoded::DmaBuf(picture))) => Ok(Some((ts, picture))), - Some(_) => Err(Error::config("non-DMA-BUF picture from a DMA-BUF decoder")), + Some(picture) => Ok(Some((picture.timestamp, picture.export_dmabuf()?))), } } /// The next picture in display order, as packed RGB with its timestamp. An error on a decoder not opened with [`HwDecoder::open_rgb`]. pub fn next_rgb(&mut self) -> Result> { - if !matches!(self.mode, Mode::Rgb(_)) { - return Err(Error::config( - "next_rgb on a decoder not opened with open_rgb", - )); - } + let output = self + .rgb + .ok_or_else(|| Error::config("next_rgb on a decoder not opened with open_rgb"))?; match self.pull()? { None => Ok(None), - Some((ts, Decoded::Rgb(picture))) => Ok(Some((ts, picture))), - Some(_) => Err(Error::config("non-RGB picture from an RGB decoder")), + Some(picture) => Ok(Some((picture.timestamp, picture.to_rgb(&output)?))), } } - fn pull(&mut self) -> Result> { + fn pull(&mut self) -> Result> { match &mut self.inner { DecInner::Vk(d) => { vk_session_alive(self.born_epoch)?; - let frame = d.next_frame(); - if frame.is_some() { + let picture = d.next_frame(); + if picture.is_some() { self.replay = None; } - Ok(frame) + Ok(picture) } #[cfg(target_os = "linux")] - DecInner::Va(d) => match d.next_frame() { - Some(frame) => { - let decoded = match self.mode { - Mode::I420 => Decoded::I420(frame.to_i420()?), - Mode::I420_16 => Decoded::I420_16(frame.to_i420_16()?), - Mode::Rgb(output) => { - let i420 = frame.to_i420()?; - let matrix = frame - .colour - .map(|c| c.description.matrix) - .unwrap_or_else(|| default_matrix(i420.height)); - Decoded::Rgb(va_rgb(&i420, output, matrix)) - } - Mode::DmaBuf => Decoded::DmaBuf(dmabuf_from_prime(frame.export_prime()?)?), - }; - Ok(Some((frame.timestamp, decoded))) - } - None => Ok(None), - }, + DecInner::Va(d) => Ok(d.next_frame().map(HwPicture::va)), } } @@ -1225,47 +1195,6 @@ impl HwDecoder { } } -#[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)| 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)], - }) -} - -#[cfg(target_os = "linux")] -fn default_matrix(height: u32) -> Matrix { - ColorDescription::resolve(Tags::default(), Tags::default(), height).matrix -} - -#[cfg(target_os = "linux")] -fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture { - i420_to_rgb( - frame, - output.max_width, - output.order == RgbOrder::Bgra, - matrix, - ) -} - #[cfg(target_os = "linux")] fn open_va_decoder(codec: Codec) -> Result { let display = ec_va::open()?; diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index eccb604d..0e38e90c 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -70,6 +70,7 @@ pub(crate) mod hevc_dpb; pub mod hw; #[cfg(target_os = "linux")] pub mod frame; +pub(crate) mod output; pub mod picture; #[cfg(target_os = "linux")] pub mod params; @@ -96,6 +97,7 @@ pub use hw::{ }; #[cfg(target_os = "linux")] pub use frame::Frame; +pub use output::HwPicture; pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420}; #[cfg(target_os = "linux")] pub use picture::DmaBufPicture; diff --git a/crates/ec-hw/src/output.rs b/crates/ec-hw/src/output.rs new file mode 100644 index 00000000..1374b4af --- /dev/null +++ b/crates/ec-hw/src/output.rs @@ -0,0 +1,381 @@ +//! 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_to_rgb, 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 { + match &self.source { + Source::Vk(picture) => picture.rgb(output), + #[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)); + Ok(i420_to_rgb( + &i420, + output.max_width, + output.order == RgbOrder::Bgra, + matrix, + )) + } + } + } + + /// One DMA-BUF of NV12 or P010 planes at display size. Not for a picture with film grain. + #[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], + ) -> Result> { + Ok(match self { + Surfaces::H264(s) => s + .borrow_mut() + .read_output_rgb(slot, crop, out, bgra, coeffs)?, + Surfaces::H265(s) => s + .borrow_mut() + .read_output_rgb(slot, crop, out, bgra, coeffs)?, + Surfaces::Av1(s) => s + .borrow_mut() + .read_output_rgb(slot, crop, out, bgra, coeffs)?, + Surfaces::Vp9(s) => s + .borrow_mut() + .read_output_rgb(slot, crop, out, bgra, coeffs)?, + }) + } + + #[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, +} + +#[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, + } + } + + /// 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.grain = Some(Grain { + params: params.clone(), + seq: seq.clone(), + }); + } + shown + } + + fn read(&self) -> Result<(Vec, Vec)> { + self.surfaces.nv12(self.slot.index, self.width, self.height) + } + + fn i420(&self) -> Result { + let (y, uv) = self.read()?; + let frame = semi_planar_to_i420( + self.bit_depth, + &y, + &uv, + self.width 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 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) -> 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", + )); + } + return Ok(i420_to_rgb( + &self.i420()?, + output.max_width, + bgra, + self.matrix, + )); + } + let (w, h) = rgb_size(self.width, self.height, output.max_width); + let data = self.surfaces.rgb( + self.slot.index, + (0, 0, self.width, self.height), + (w, h), + bgra, + yuv_to_rgb(self.matrix).words(), + )?; + Ok(RgbPicture::new(data, w, h)) + } + + #[cfg(target_os = "linux")] + fn export(&self) -> Result { + if self.grain.is_some() { + return Err(Error::unsupported( + "Vulkan DMA-BUF export", + "a picture with film grain", + )); + } + Ok(self + .surfaces + .export(self.slot.index, self.width, self.height)? + .into()) + } +} + +#[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)], + }) +} diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index d6cb866b..f8d600dd 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -114,30 +114,6 @@ impl DmaBufPicture { } } -/// One decoded picture in the decoder's output form. -#[derive(Debug)] -pub(crate) enum Decoded { - I420(I420), - I420_16(I420_16), - Rgb(RgbPicture), - #[cfg(target_os = "linux")] - DmaBuf(DmaBufPicture), -} - -impl Decoded { - pub(crate) fn try_clone(&self) -> Result { - Ok(match self { - Decoded::I420(frame) => Decoded::I420(frame.clone()), - Decoded::I420_16(frame) => Decoded::I420_16(frame.clone()), - Decoded::Rgb(picture) => Decoded::Rgb(picture.clone()), - #[cfg(target_os = "linux")] - Decoded::DmaBuf(picture) => Decoded::DmaBuf(picture.try_clone().map_err(|e| { - Error::config(format!("duplicating a DMA-BUF picture: {e}")) - })?), - }) - } -} - /// 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 { diff --git a/crates/ec-hw/src/vkdec264.rs b/crates/ec-hw/src/vkdec264.rs index 3ceab5bc..3fb288f9 100644 --- a/crates/ec-hw/src/vkdec264.rs +++ b/crates/ec-hw/src/vkdec264.rs @@ -1,6 +1,8 @@ //! H.264 decoding over Vulkan Video: the shared DPB over DPB slot indices. +use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; use ec_h264_syntax::{ @@ -15,10 +17,7 @@ use ec_vk::{ use crate::dpb264::{self, Mark, PicInfo, Poc}; use crate::error::{Error, Result}; use crate::h264_common::{peek_pps_id, vui_colour_tags}; -use crate::hw::{Mode, RgbOrder}; -use crate::picture::{ - Decoded, I420, RgbPicture, nv12_to_i420, rgb_size, semi_planar_to_i420_16, yuv_to_rgb, -}; +use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; use ec_core::color::{ColorDescription, Tags}; const MAX_SLOTS: u32 = 17; @@ -27,7 +26,8 @@ type Dpb = dpb264::Dpb; type Picture = dpb264::Picture; struct Session { - h264: H264DecodeSession, + h264: Rc>, + ring: Ring, max_width: u32, max_height: u32, slots: u32, @@ -48,7 +48,7 @@ struct Current { struct Side { fields: [i32; 2], - output: Option<(i64, Decoded)>, + output: Option, } /// H.264 Vulkan Video decoder: DPB bookkeeping in Rust, pictures decoded into slots. @@ -61,13 +61,12 @@ pub(crate) struct VkH264Decoder { dpb: Dpb, pics: HashMap, current: Option, - ready: VecDeque<(i64, Decoded)>, + ready: VecDeque, rbsp: Vec, - mode: Mode, } impl VkH264Decoder { - pub(crate) fn new(mode: Mode) -> Result { + pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.264 decode", "no Vulkan device"))?; Ok(VkH264Decoder { @@ -81,7 +80,6 @@ impl VkH264Decoder { current: None, ready: VecDeque::new(), rbsp: Vec::new(), - mode, }) } @@ -124,7 +122,7 @@ impl VkH264Decoder { self.finish_picture() } - pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { + pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } @@ -253,8 +251,10 @@ impl VkH264Decoder { profile_idc: sps.profile_idc, }, )?; + let ring = Ring::new(h264.ring_len()); self.session = Some(Session { - h264, + h264: Rc::new(RefCell::new(h264)), + ring, max_width, max_height, slots, @@ -270,7 +270,7 @@ impl VkH264Decoder { .session .as_mut() .ok_or_else(|| Error::config("H.264 parameters before any SPS"))?; - session.h264.set_parameters(&sps, &pps)?; + session.h264.borrow_mut().set_parameters(&sps, &pps)?; self.params_dirty = false; Ok(()) } @@ -323,7 +323,8 @@ impl VkH264Decoder { .session .as_mut() .ok_or_else(|| Error::config("H.264 picture before any SPS"))?; - session.h264.decode(&H264DecodePicture { + let slot = session.ring.take(|| Ok(session.h264.borrow_mut().add_ring_slot()?))?; + session.h264.borrow_mut().decode(&H264DecodePicture { sps_id: current.sps_id, pps_id: current.pps_id, idr: current.info.is_idr, @@ -335,53 +336,23 @@ impl VkH264Decoder { refs: &refs, slices: &slices, })?; - let out = match self.mode { - Mode::I420 => { - let (y, uv) = session - .h264 - .read_output(sps.coded_width, sps.coded_height)?; - Decoded::I420(crop(&sps, &y, &uv)) - } - Mode::I420_16 => { - let (y, uv) = session - .h264 - .read_output(sps.coded_width, sps.coded_height)?; - let (left, _, top, _) = sps.crop; - Decoded::I420_16(semi_planar_to_i420_16( - 8, - &y, - &uv, - sps.coded_width as usize, - (left as usize, top as usize), - (sps.width, sps.height), - )?) - } - #[cfg(target_os = "linux")] - Mode::DmaBuf => { - let (left, _, top, _) = sps.crop; - let export = session.h264.read_output_dmabuf(( - left, - top, - sps.width, - sps.height, - ))?; - Decoded::DmaBuf(export.into()) - } - Mode::Rgb(rgb) => { - let (left, _, top, _) = sps.crop; - let matrix = - ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height) - .matrix; - let (w, h) = rgb_size(sps.width, sps.height, rgb.max_width); - let data = session.h264.read_output_rgb( - (left, top, sps.width, sps.height), - (w, h), - rgb.order == RgbOrder::Bgra, - yuv_to_rgb(matrix).words(), - )?; - Decoded::Rgb(RgbPicture::new(data, w, h)) - } - }; + let (left, _, top, _) = sps.crop; + session + .h264 + .borrow_mut() + .store_output(slot.index(), (left, top, sps.width, sps.height))?; + let matrix = + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), sps.height).matrix; + let out = HwPicture::vk( + current.timestamp, + VkPicture::new( + Surfaces::H264(session.h264.clone()), + slot, + (sps.width, sps.height), + 8, + matrix, + ), + ); let picture = Picture { id: current.id, @@ -403,7 +374,7 @@ impl VkH264Decoder { current.id, Side { fields, - output: Some((current.timestamp, out)), + output: Some(out), }, ); self.dpb @@ -415,8 +386,8 @@ impl VkH264Decoder { fn bump(&mut self, flush: bool) { while let Some(idx) = self.dpb.next_output(flush) { let id = self.dpb.frames[idx].id; - if let Some((ts, frame)) = self.pics.get_mut(&id).and_then(|s| s.output.take()) { - self.ready.push_back((ts, frame)); + if let Some(frame) = self.pics.get_mut(&id).and_then(|s| s.output.take()) { + self.ready.push_back(frame); } self.dpb.released(idx); } @@ -429,20 +400,6 @@ fn field_pocs(poc: i32, delta_bottom: i32) -> [i32; 2] { [poc - delta_bottom.min(0), poc + delta_bottom.max(0)] } -fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> I420 { - let (left, _, top, _) = sps.crop; - let (left, top) = (left as usize, top as usize); - let pitch = sps.coded_width as usize; - nv12_to_i420( - &y[top * pitch + left..], - pitch, - &uv[(top / 2) * pitch + left..], - pitch, - sps.width as usize, - sps.height as usize, - ) -} - fn lists(l: &ec_h264_syntax::ScalingLists) -> ScalingLists { let mut out = ScalingLists { l4x4: [[0; 16]; 6], diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index 3159b91a..e5e715d0 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -1,6 +1,8 @@ //! H.265 decoding over Vulkan Video: the shared HEVC DPB over DPB slot indices. +use std::cell::RefCell; use std::collections::{HashMap, VecDeque}; +use std::rc::Rc; use ec_h265_syntax::{ AnnexBNal, NalUnitType, Pps, ScalingList, ShortTermRefPicSet, SliceHeader, Sps, Vps, @@ -18,16 +20,13 @@ use crate::hevc_dpb::{ }; use ec_core::color::{ColorDescription, Tags}; -use crate::hw::{Mode, RgbOrder}; -use crate::picture::{ - Decoded, I420, I420_16, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, - yuv_to_rgb, -}; +use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; const MAX_SLOTS: u32 = 17; struct Session { - h265: H265DecodeSession, + h265: Rc>, + ring: Ring, bit_depth: u8, max_width: u32, max_height: u32, @@ -60,15 +59,14 @@ pub(crate) struct VkH265Decoder { sps_map: Vec>, pps_map: Vec>, dpb: Dpb, - outputs: HashMap, + outputs: HashMap, current: Option, - ready: VecDeque<(i64, Decoded)>, + ready: VecDeque, no_rasl_output: bool, - mode: Mode, } impl VkH265Decoder { - pub(crate) fn new(mode: Mode) -> Result { + pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video H.265 decode", "no Vulkan device"))?; Ok(VkH265Decoder { @@ -83,7 +81,6 @@ impl VkH265Decoder { current: None, ready: VecDeque::new(), no_rasl_output: false, - mode, }) } @@ -120,7 +117,7 @@ impl VkH265Decoder { self.finish_picture() } - pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { + pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } @@ -264,8 +261,10 @@ impl VkH265Decoder { bit_depth, }, )?; + let ring = Ring::new(h265.ring_len()); self.session = Some(Session { - h265, + h265: Rc::new(RefCell::new(h265)), + ring, bit_depth, max_width, max_height, @@ -293,7 +292,7 @@ impl VkH265Decoder { .session .as_mut() .ok_or_else(|| Error::config("H.265 parameters before any SPS"))?; - session.h265.set_parameters(&vps, &sps, &pps)?; + session.h265.borrow_mut().set_parameters(&vps, &sps, &pps)?; self.params_dirty = false; Ok(()) } @@ -335,7 +334,7 @@ impl VkH265Decoder { .session .as_mut() .ok_or_else(|| Error::config("H.265 picture before any SPS"))?; - session.h265.decode(&H265DecodePicture { + session.h265.borrow_mut().decode(&H265DecodePicture { vps_id: sps.vps_id, sps_id: current.sps_id, pps_id: current.pps_id, @@ -354,47 +353,24 @@ impl VkH265Decoder { slices: &slices, })?; if current.output { - let frame = match self.mode { - Mode::I420 => { - let (y, uv) = session.h265.read_output( - sps.pic_width_in_luma_samples, - sps.pic_height_in_luma_samples, - )?; - Decoded::I420(crop(&sps, &y, &uv)?) - } - Mode::I420_16 => { - let (y, uv) = session.h265.read_output( - sps.pic_width_in_luma_samples, - sps.pic_height_in_luma_samples, - )?; - Decoded::I420_16(crop16(&sps, &y, &uv)?) - } - #[cfg(target_os = "linux")] - Mode::DmaBuf => { - let (width, height) = sps.display_size(); - let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); - let export = session - .h265 - .read_output_dmabuf((origin.0, origin.1, width, height))?; - Decoded::DmaBuf(export.into()) - } - Mode::Rgb(rgb) => { - let (width, height) = sps.display_size(); - let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); - let matrix = - ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height) - .matrix; - let (w, h) = rgb_size(width, height, rgb.max_width); - let data = session.h265.read_output_rgb( - (origin.0, origin.1, width, height), - (w, h), - rgb.order == RgbOrder::Bgra, - yuv_to_rgb(matrix).words(), - )?; - Decoded::Rgb(RgbPicture::new(data, w, h)) - } - }; - self.outputs.insert(current.slot, frame); + let slot = session.ring.take(|| Ok(session.h265.borrow_mut().add_ring_slot()?))?; + let (width, height) = sps.display_size(); + let origin = (2 * sps.conf_win.left as u32, 2 * sps.conf_win.top as u32); + session.h265.borrow_mut().store_output( + slot.index(), + (origin.0, origin.1, width, height), + )?; + let matrix = + ColorDescription::resolve(Tags::default(), vui_colour_tags(&sps), height).matrix; + let picture = VkPicture::new( + Surfaces::H265(session.h265.clone()), + slot, + (width, height), + (8 + sps.bit_depth_luma_minus8) as u8, + matrix, + ); + self.outputs + .insert(current.slot, HwPicture::vk(current.timestamp, picture)); } self.dpb.pictures.push(hevc_dpb::StoredPicture { @@ -420,7 +396,7 @@ impl VkH265Decoder { while let Some(idx) = self.dpb.next_output(flush) { let pic = &self.dpb.pictures[idx]; if let Some(frame) = self.outputs.remove(&pic.surface) { - self.ready.push_back((pic.timestamp, frame)); + self.ready.push_back(frame); } self.dpb.released(idx); } @@ -435,34 +411,6 @@ fn store(slot: &mut Option, value: T) -> bool { true } -fn crop(sps: &Sps, y: &[u8], uv: &[u8]) -> Result { - semi_planar_to_i420( - (8 + sps.bit_depth_luma_minus8) as u8, - y, - uv, - sps.pic_width_in_luma_samples as usize, - ( - 2 * sps.conf_win.left as usize, - 2 * sps.conf_win.top as usize, - ), - sps.display_size(), - ) -} - -fn crop16(sps: &Sps, y: &[u8], uv: &[u8]) -> Result { - semi_planar_to_i420_16( - (8 + sps.bit_depth_luma_minus8) as u8, - y, - uv, - sps.pic_width_in_luma_samples as usize, - ( - 2 * sps.conf_win.left as usize, - 2 * sps.conf_win.top as usize, - ), - sps.display_size(), - ) -} - fn ptl(p: &ec_h265_syntax::ProfileTierLevel) -> H265ProfileTierLevel { H265ProfileTierLevel { tier_flag: p.tier_flag, diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index 2305e392..12c864a0 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -1,5 +1,6 @@ //! AV1 decoding over Vulkan Video: the reference slots over DPB slot indices. +use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; @@ -20,16 +21,14 @@ use crate::ref_slots::RefSlots; use crate::error::{Error, Result}; use ec_core::color::{ColorDescription, Tags}; -use crate::hw::{Mode, RgbOrder}; -use crate::picture::{ - Decoded, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420, - semi_planar_to_i420_16, yuv_to_rgb, -}; +use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; +use crate::picture::{I420, I420_16}; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; struct Session { - av1: Av1DecodeSession, + av1: Rc>, + ring: Ring, bit_depth: u8, width: u32, height: u32, @@ -38,7 +37,7 @@ struct Session { struct Reference { state: Av1RefSlot, - picture: Decoded, + picture: VkPicture, } /// AV1 Vulkan Video decoder: reference bookkeeping in Rust, frames decoded into DPB slots. @@ -47,12 +46,11 @@ pub(crate) struct VkAv1Decoder { parser: Av1Parser, session: Option, refs: RefSlots>, - ready: VecDeque<(i64, Decoded)>, - mode: Mode, + ready: VecDeque, } impl VkAv1Decoder { - pub(crate) fn new(mode: Mode) -> Result { + pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video AV1 decode", "no Vulkan device"))?; Ok(VkAv1Decoder { @@ -61,7 +59,6 @@ impl VkAv1Decoder { session: None, refs: RefSlots::new(), ready: VecDeque::new(), - mode, }) } @@ -90,7 +87,7 @@ impl VkAv1Decoder { Ok(()) } - pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { + pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } @@ -118,16 +115,8 @@ impl VkAv1Decoder { .parser .sequence_header() .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; - if header.film_grain.apply_grain { - grain_supported(seq, self.mode)?; - } - let shown = present( - self.mode, - reference.picture.try_clone()?, - &header.film_grain, - seq, - )?; - self.ready.push_back((timestamp, shown)); + let shown = reference.picture.with_grain(&header.film_grain, seq); + self.ready.push_back(HwPicture::vk(timestamp, shown)); if header.frame_type == FrameType::Key { self.refs.refresh(u8::MAX, Some(reference)); } @@ -146,7 +135,7 @@ impl VkAv1Decoder { .sequence_header() .cloned() .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; - check_supported(&seq, header, self.mode)?; + check_supported(&seq, header)?; let (width, height) = (header.upscaled_width, header.frame_height); self.ensure_session(&seq, width, height)?; @@ -184,57 +173,22 @@ impl VkAv1Decoder { .session .as_mut() .ok_or_else(|| Error::config("AV1 picture before any session"))?; - session.av1.decode(&picture)?; + session.av1.borrow_mut().decode(&picture)?; if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } - let mode = self.mode; - let readback = match mode { - Mode::Rgb(_) if seq.color_config.bit_depth == 8 => Mode::I420, - other => other, - }; - let decoded = match readback { - Mode::I420 => { - let (y, uv) = session.av1.read_output(width, height)?; - Decoded::I420(semi_planar_to_i420( - session.bit_depth, - &y, - &uv, - width as usize, - (0, 0), - (width, height), - )?) - } - Mode::I420_16 => { - let (y, uv) = session.av1.read_output(width, height)?; - Decoded::I420_16(semi_planar_to_i420_16( - session.bit_depth, - &y, - &uv, - width as usize, - (0, 0), - (width, height), - )?) - } - #[cfg(target_os = "linux")] - Mode::DmaBuf => { - let export = session.av1.read_output_dmabuf((0, 0, width, height))?; - Decoded::DmaBuf(export.into()) - } - Mode::Rgb(rgb) => { - let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); - let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; - let (w, h) = rgb_size(width, height, rgb.max_width); - let data = session.av1.read_output_rgb( - (0, 0, width, height), - (w, h), - rgb.order == RgbOrder::Bgra, - yuv_to_rgb(matrix).words(), - )?; - Decoded::Rgb(RgbPicture::new(data, w, h)) - } - }; + let slot = session.ring.take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?; + session.av1.borrow_mut().store_output(slot.index(), (0, 0, width, height))?; + let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; + let decoded = VkPicture::new( + Surfaces::Av1(session.av1.clone()), + slot, + (width, height), + session.bit_depth, + matrix, + ); let state = Av1RefSlot { slot: setup_slot, frame_type: av1_frame_type(header.frame_type), @@ -245,8 +199,8 @@ impl VkAv1Decoder { segmentation_enabled: header.segmentation.enabled, }; if header.show_frame { - let shown = present(mode, decoded.try_clone()?, &header.film_grain, &seq)?; - self.ready.push_back((timestamp, shown)); + let shown = decoded.with_grain(&header.film_grain, &seq); + self.ready.push_back(HwPicture::vk(timestamp, shown)); } if header.refresh_frame_flags != 0 { let reference = Rc::new(Reference { @@ -280,8 +234,10 @@ impl VkAv1Decoder { bit_depth, }, )?; + let ring = Ring::new(av1.ring_len()); Session { - av1, + av1: Rc::new(RefCell::new(av1)), + ring, bit_depth, width, height, @@ -290,7 +246,10 @@ impl VkAv1Decoder { } }; if session.sequence.as_ref() != Some(seq) { - session.av1.set_sequence_header(&av1_sequence(seq))?; + session + .av1 + .borrow_mut() + .set_sequence_header(&av1_sequence(seq))?; session.sequence = Some(seq.clone()); } self.session = Some(session); @@ -304,7 +263,7 @@ impl VkAv1Decoder { } } -fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Result<()> { +fn check_supported(seq: &SequenceHeader, header: &FrameHeader) -> Result<()> { let c = &seq.color_config; if seq.seq_profile != 0 || !matches!(c.bit_depth, 8 | 10) @@ -320,64 +279,10 @@ fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Re if header.upscaled_width % 2 != 0 || header.frame_height % 2 != 0 { return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size")); } - if header.film_grain.apply_grain { - grain_supported(seq, mode)?; - } Ok(()) } -fn grain_supported(seq: &SequenceHeader, mode: Mode) -> Result<()> { - let eight = seq.color_config.bit_depth == 8; - let supported = match mode { - Mode::I420 | Mode::Rgb(_) => eight, - Mode::I420_16 => true, - #[cfg(target_os = "linux")] - Mode::DmaBuf => false, - }; - if supported { - Ok(()) - } else { - Err(Error::unsupported( - "Vulkan AV1 film grain", - "not for this output format", - )) - } -} - -fn present( - mode: Mode, - picture: Decoded, - grain: &FilmGrainParams, - seq: &SequenceHeader, -) -> Result { - let picture = grained(picture, grain, seq); - Ok(match (mode, picture) { - (Mode::Rgb(rgb), Decoded::I420(frame)) => { - let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0); - let matrix = ColorDescription::resolve(Tags::default(), codes, frame.height).matrix; - Decoded::Rgb(i420_to_rgb( - &frame, - rgb.max_width, - rgb.order == RgbOrder::Bgra, - matrix, - )) - } - (_, other) => other, - }) -} - -fn grained(picture: Decoded, grain: &FilmGrainParams, seq: &SequenceHeader) -> Decoded { - if !grain.apply_grain { - return picture; - } - match picture { - Decoded::I420(frame) => Decoded::I420(synthesize(frame, grain, seq)), - Decoded::I420_16(frame) => Decoded::I420_16(synthesize16(frame, grain, seq)), - other => other, - } -} - -fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 { +pub(crate) fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420_16 { let bit_depth = u32::from(seq.color_config.bit_depth); let shift = if bit_depth == 8 { 2 } else { 0 }; let narrow = |p: &[u16]| p.iter().map(|&s| s >> shift).collect::>(); @@ -405,7 +310,7 @@ fn synthesize16(frame: I420_16, grain: &FilmGrainParams, seq: &SequenceHeader) - } } -fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 { +pub(crate) fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 { let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::>(); let clean = Picture { width: frame.width as usize, diff --git a/crates/ec-hw/src/vkdec_vp9.rs b/crates/ec-hw/src/vkdec_vp9.rs index 896825fd..ff25a7e4 100644 --- a/crates/ec-hw/src/vkdec_vp9.rs +++ b/crates/ec-hw/src/vkdec_vp9.rs @@ -1,5 +1,6 @@ //! VP9 decoding over Vulkan Video: the reference slots over DPB slot indices. +use std::cell::RefCell; use std::collections::VecDeque; use std::rc::Rc; @@ -14,16 +15,14 @@ use ec_vp9_syntax::{ }; use crate::error::{Error, Result}; -use crate::hw::{Mode, RgbOrder}; -use crate::picture::{ - Decoded, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb, -}; +use crate::output::{HwPicture, Ring, Surfaces, VkPicture}; use crate::ref_slots::RefSlots; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; struct Session { - vp9: Vp9DecodeSession, + vp9: Rc>, + ring: Ring, bit_depth: u8, width: u32, height: u32, @@ -31,7 +30,7 @@ struct Session { struct Reference { slot: u32, - picture: Decoded, + picture: VkPicture, } /// What the next frame needs from the one before it (spec 7.2, UsePrevFrameMvs). @@ -50,12 +49,11 @@ pub(crate) struct VkVp9Decoder { session: Option, refs: RefSlots>, previous: Option, - ready: VecDeque<(i64, Decoded)>, - mode: Mode, + ready: VecDeque, } impl VkVp9Decoder { - pub(crate) fn new(mode: Mode) -> Result { + pub(crate) fn new() -> Result { let gpu = crate::hw::vk_gpu() .ok_or_else(|| Error::unsupported("Vulkan Video VP9 decode", "no Vulkan device"))?; Ok(VkVp9Decoder { @@ -65,7 +63,6 @@ impl VkVp9Decoder { refs: RefSlots::new(), previous: None, ready: VecDeque::new(), - mode, }) } @@ -79,7 +76,7 @@ impl VkVp9Decoder { Ok(()) } - pub(crate) fn next_frame(&mut self) -> Option<(i64, Decoded)> { + pub(crate) fn next_frame(&mut self) -> Option { self.ready.pop_front() } @@ -106,7 +103,8 @@ impl VkVp9Decoder { "VP9 show_existing_frame names an empty reference slot", )) })?; - self.ready.push_back((timestamp, reference.picture.try_clone()?)); + self.ready + .push_back(HwPicture::vk(timestamp, reference.picture.clone())); if let Some(previous) = self.previous.as_mut() { previous.show_frame = true; } @@ -152,7 +150,8 @@ impl VkVp9Decoder { .session .as_mut() .ok_or_else(|| Error::config("VP9 picture before any session"))?; - session.vp9.decode(&picture)?; + let slot = session.ring.take(|| Ok(session.vp9.borrow_mut().add_ring_slot()?))?; + session.vp9.borrow_mut().decode(&picture)?; self.previous = Some(PreviousFrame { width: header.width, height: header.height, @@ -164,53 +163,19 @@ impl VkVp9Decoder { return Ok(()); } let (width, height) = (header.width, header.height); - let decoded = match self.mode { - Mode::I420 => { - let (y, uv) = session.vp9.read_output(width, height)?; - Decoded::I420(semi_planar_to_i420( - session.bit_depth, - &y, - &uv, - width as usize, - (0, 0), - (width, height), - )?) - } - Mode::I420_16 => { - let (y, uv) = session.vp9.read_output(width, height)?; - Decoded::I420_16(semi_planar_to_i420_16( - session.bit_depth, - &y, - &uv, - width as usize, - (0, 0), - (width, height), - )?) - } - #[cfg(target_os = "linux")] - Mode::DmaBuf => { - let export = session.vp9.read_output_dmabuf((0, 0, width, height))?; - Decoded::DmaBuf(export.into()) - } - Mode::Rgb(rgb) => { - let codes = Tags::from_codes( - u64::from(header.color_space.h273().map_or(2, |c| c.2)), - 0, - 0, - ); - let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; - let (w, h) = rgb_size(width, height, rgb.max_width); - let data = session.vp9.read_output_rgb( - (0, 0, width, height), - (w, h), - rgb.order == RgbOrder::Bgra, - yuv_to_rgb(matrix).words(), - )?; - Decoded::Rgb(RgbPicture::new(data, w, h)) - } - }; + let codes = Tags::from_codes(u64::from(header.color_space.h273().map_or(2, |c| c.2)), 0, 0); + let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix; + session.vp9.borrow_mut().store_output(slot.index(), (0, 0, width, height))?; + let decoded = VkPicture::new( + Surfaces::Vp9(session.vp9.clone()), + slot, + (width, height), + session.bit_depth, + matrix, + ); if header.show_frame { - self.ready.push_back((timestamp, decoded.try_clone()?)); + self.ready + .push_back(HwPicture::vk(timestamp, decoded.clone())); } if header.refresh_frame_flags != 0 { let reference = Rc::new(Reference { @@ -247,8 +212,10 @@ impl VkVp9Decoder { bit_depth: header.bit_depth, }, )?; + let ring = Ring::new(vp9.ring_len()); self.session = Some(Session { - vp9, + vp9: Rc::new(RefCell::new(vp9)), + ring, bit_depth: header.bit_depth, width, height, diff --git a/shims/vk-video-ffi/examples/av1_decode_smoke.rs b/shims/vk-video-ffi/examples/av1_decode_smoke.rs index 308ff78a..fb448bc7 100644 --- a/shims/vk-video-ffi/examples/av1_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/av1_decode_smoke.rs @@ -301,7 +301,8 @@ fn main() { tile_sizes: &sizes, }; session.decode(&pic).expect("decode"); - let (y, uv) = session.read_output(w, h).expect("read output"); + session.store_output(0, (0, 0, w, h)).expect("store"); + let (y, uv) = session.read_output(0, w, h).expect("read slot"); let reference = fs::read(&reference).expect("read reference"); let luma = (w * h) as usize; diff --git a/shims/vk-video-ffi/examples/h264_decode_smoke.rs b/shims/vk-video-ffi/examples/h264_decode_smoke.rs index c8c59620..e4beebc4 100644 --- a/shims/vk-video-ffi/examples/h264_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/h264_decode_smoke.rs @@ -159,7 +159,8 @@ fn main() { slices: &slices, }; session.decode(&pic).expect("decode"); - let (y, uv) = session.read_output(w, h).expect("read slot"); + session.store_output(0, (0, 0, w, h)).expect("store"); + let (y, uv) = session.read_output(0, w, h).expect("read slot"); let mut pgm = format!("P5\n{w} {h}\n255\n").into_bytes(); pgm.extend_from_slice(&y); diff --git a/shims/vk-video-ffi/examples/h265_decode_smoke.rs b/shims/vk-video-ffi/examples/h265_decode_smoke.rs index c438c7fd..53c7ff78 100644 --- a/shims/vk-video-ffi/examples/h265_decode_smoke.rs +++ b/shims/vk-video-ffi/examples/h265_decode_smoke.rs @@ -258,7 +258,8 @@ fn main() { slices: &slices, }; session.decode(&pic).expect("decode"); - let (y, uv) = session.read_output(w, h).expect("read slot"); + session.store_output(0, (0, 0, w, h)).expect("store"); + let (y, uv) = session.read_output(0, w, h).expect("read slot"); let ref_data = fs::read(&reference).expect("read reference"); let luma = (w * h) as usize; diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs index e3f5c196..7445eac6 100644 --- a/shims/vk-video-ffi/src/av1_decode.rs +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -853,28 +853,46 @@ impl Av1DecodeSession { } /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). - pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { - self.dec.read_nv12(width, height) + pub fn ring_len(&self) -> u32 { + self.dec.ring_len() + } + + /// Adds one slot to the output ring and returns its index; every slot is then in use or held. + pub fn add_ring_slot(&mut self) -> Result { + self.dec.add_ring_slot() + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again. + pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> { + self.dec.store(slot as usize, crop) + } + + /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV). + pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + self.dec.read_nv12(slot as usize, width, height) } /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes. #[cfg(target_os = "linux")] pub fn read_output_dmabuf( &mut self, - crop: (u32, u32, u32, u32), + slot: u32, + width: u32, + height: u32, ) -> Result { - self.dec.export(crop) + self.dec.export(slot as usize, (width, height)) } /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. pub fn read_output_rgb( &mut self, + slot: u32, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], ) -> Result, Error> { - self.dec.read_rgb(crop, out, bgra, coeffs) + self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs) } } diff --git a/shims/vk-video-ffi/src/dmabuf.rs b/shims/vk-video-ffi/src/dmabuf.rs index c0e5523d..5ca84032 100644 --- a/shims/vk-video-ffi/src/dmabuf.rs +++ b/shims/vk-video-ffi/src/dmabuf.rs @@ -7,7 +7,7 @@ use vulkanalia::vk::{ ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands, }; -use crate::session::{Lane, NV12, P010, PLANE_0, PLANE_1, color_range, memory_type, vk}; +use crate::session::{EXTERNAL_FAMILY, Lane, NV12, P010, PLANE_0, PLANE_1, memory_type, transfer, vk}; use std::os::fd::AsFd; use crate::{Error, Gpu}; @@ -477,46 +477,26 @@ fn export_modifiers(gpu: &Gpu, format: vk::Format) -> Vec { list.iter() .filter(|m| { m.drm_format_modifier_tiling_features - .contains(vk::FormatFeatureFlags::TRANSFER_DST) + .contains(vk::FormatFeatureFlags::TRANSFER_DST | vk::FormatFeatureFlags::TRANSFER_SRC) }) .map(|m| m.drm_format_modifier) .collect() } -fn transfer( - d: &Device, - cb: vk::CommandBuffer, - image: vk::Image, - from: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32), - to: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32), -) { - let barrier = vk::ImageMemoryBarrier2::builder() - .src_stage_mask(from.1) - .src_access_mask(from.2) - .dst_stage_mask(to.1) - .dst_access_mask(to.2) - .old_layout(from.0) - .new_layout(to.0) - .src_queue_family_index(from.3) - .dst_queue_family_index(to.3) - .image(image) - .subresource_range(color_range()) - .build(); - let barriers = [barrier]; - let info = vk::DependencyInfo::builder() - .image_memory_barriers(&barriers) - .build(); - unsafe { d.cmd_pipeline_barrier2(cb, &info) }; +/// A ring slot's DMA-BUF: the one memory object, exported once, and its plane layout. +pub(crate) struct Export { + pub(crate) fd: OwnedFd, + pub(crate) modifier: u64, + pub(crate) planes: [DmaBufPlane; 2], } -/// Copies the crop window `(x, y, width, height)` of `src` (decoded NV12 or P010) into a new exportable image on the graphics lane, releases it to the foreign queue and exports it as one DMA-BUF. -pub(crate) fn export( +/// Creates an exportable NV12 or P010 image of `width` x `height` on the lane's family, leaves it released to the foreign queue in GENERAL, and exports its memory once. +pub(crate) fn ring_image( gpu: &Gpu, lane: &Lane, - src: vk::Image, format: vk::Format, - (x, y, width, height): (u32, u32, u32, u32), -) -> Result { + (width, height): (u32, u32), +) -> Result<(vk::Image, vk::DeviceMemory, Export), Error> { check(gpu)?; let d = gpu.device(); let modifiers = export_modifiers(gpu, format); @@ -543,7 +523,7 @@ pub(crate) fn export( } else { vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT }) - .usage(vk::ImageUsageFlags::TRANSFER_DST) + .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST) .sharing_mode(vk::SharingMode::EXCLUSIVE) .initial_layout(vk::ImageLayout::UNDEFINED) .push_next(&mut external); @@ -553,98 +533,16 @@ pub(crate) fn export( info.push_next(&mut list).build() }; let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? }; - let exported = export_image(gpu, lane, src, image, (x, y, width, height), linear); - unsafe { d.destroy_image(image, None) }; - exported.map(|(fd, modifier, planes)| DmaBufExport { - fd, - modifier, - planes, - width, - height, - p010: format == crate::session::P010, - }) -} - -fn export_image( - gpu: &Gpu, - lane: &Lane, - src: vk::Image, - image: vk::Image, - (x, y, width, height): (u32, u32, u32, u32), - linear: bool, -) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> { - let d = gpu.device(); - let req = unsafe { d.get_image_memory_requirements(image) }; - let index = memory_type(gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?; - let mut export = vk::ExportMemoryAllocateInfo::builder() - .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) - .build(); - let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder() - .image(image) - .build(); - let alloc = vk::MemoryAllocateInfo::builder() - .allocation_size(req.size) - .memory_type_index(index) - .push_next(&mut dedicated) - .push_next(&mut export) - .build(); - let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? }; - if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } { - unsafe { d.free_memory(memory, None) }; - return Err(e); - } - let result = copy_and_export(gpu, lane, src, image, memory, (x, y, width, height), linear); - unsafe { d.free_memory(memory, None) }; - result -} - -fn copy_and_export( - gpu: &Gpu, - lane: &Lane, - src: vk::Image, - image: vk::Image, - memory: vk::DeviceMemory, - (x, y, width, height): (u32, u32, u32, u32), - linear: bool, -) -> Result<(OwnedFd, u64, [DmaBufPlane; 2]), Error> { - let d = gpu.device(); + let memory = match bind_exported(gpu, image) { + Ok(memory) => memory, + Err(e) => { + unsafe { d.destroy_image(image, None) }; + return Err(e); + } + }; let cb = lane.cb; - let decode = ( - vk::ImageLayout::VIDEO_DECODE_DST_KHR, - vk::PipelineStageFlags2::ALL_COMMANDS, - vk::AccessFlags2::NONE, - vk::QUEUE_FAMILY_IGNORED, - ); - let copy_src = ( - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - vk::PipelineStageFlags2::COPY, - vk::AccessFlags2::TRANSFER_READ, - vk::QUEUE_FAMILY_IGNORED, - ); - let copy_dst = ( - vk::ImageLayout::TRANSFER_DST_OPTIMAL, - vk::PipelineStageFlags2::COPY, - vk::AccessFlags2::TRANSFER_WRITE, - vk::QUEUE_FAMILY_IGNORED, - ); - let planes_regions = [ - plane_copy(PLANE_0, (x, y), (width, height)), - plane_copy(PLANE_1, (x / 2, y / 2), (width / 2, height / 2)), - ]; lane.begin()?; - unsafe { - transfer( - d, - cb, - src, - decode, - ( - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - vk::PipelineStageFlags2::COPY, - vk::AccessFlags2::TRANSFER_READ, - vk::QUEUE_FAMILY_IGNORED, - ), - ); + { transfer( d, cb, @@ -655,15 +553,12 @@ fn copy_and_export( vk::AccessFlags2::NONE, vk::QUEUE_FAMILY_IGNORED, ), - copy_dst, - ); - d.cmd_copy_image( - cb, - src, - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - image, - vk::ImageLayout::TRANSFER_DST_OPTIMAL, - &planes_regions, + ( + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_WRITE, + vk::QUEUE_FAMILY_IGNORED, + ), ); transfer( d, @@ -679,10 +574,9 @@ fn copy_and_export( vk::ImageLayout::GENERAL, vk::PipelineStageFlags2::NONE, vk::AccessFlags2::NONE, - QUEUE_FAMILY_FOREIGN, + EXTERNAL_FAMILY, ), ); - transfer(d, cb, src, copy_src, decode); } lane.end()?; lane.submit()?; @@ -703,37 +597,34 @@ fn copy_and_export( layout(gpu, image, linear, 0)?, layout(gpu, image, linear, 1)?, ]; - Ok((fd, modifier, planes)) + Ok((image, memory, Export { fd, modifier, planes })) } -pub(crate) fn plane_copy( - aspect: vk::ImageAspectFlags, - origin: (u32, u32), - (width, height): (u32, u32), -) -> vk::ImageCopy { - let layers = vk::ImageSubresourceLayers { - aspect_mask: aspect, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }; - vk::ImageCopy { - src_subresource: layers, - src_offset: vk::Offset3D { - x: origin.0 as i32, - y: origin.1 as i32, - z: 0, - }, - dst_subresource: layers, - dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 }, - extent: vk::Extent3D { - width, - height, - depth: 1, - }, +fn bind_exported(gpu: &Gpu, image: vk::Image) -> Result { + let d = gpu.device(); + let req = unsafe { d.get_image_memory_requirements(image) }; + let index = memory_type(gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?; + let mut export = vk::ExportMemoryAllocateInfo::builder() + .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .build(); + let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder() + .image(image) + .build(); + let alloc = vk::MemoryAllocateInfo::builder() + .allocation_size(req.size) + .memory_type_index(index) + .push_next(&mut dedicated) + .push_next(&mut export) + .build(); + let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? }; + if let Err(e) = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") } { + unsafe { d.free_memory(memory, None) }; + return Err(e); } + Ok(memory) } + fn export_fd(gpu: &Gpu, memory: vk::DeviceMemory) -> Result { let info = vk::MemoryGetFdInfoKHR::builder() .memory(memory) diff --git a/shims/vk-video-ffi/src/h264_decode.rs b/shims/vk-video-ffi/src/h264_decode.rs index 3b35c8fb..29c835c6 100644 --- a/shims/vk-video-ffi/src/h264_decode.rs +++ b/shims/vk-video-ffi/src/h264_decode.rs @@ -457,28 +457,46 @@ impl H264DecodeSession { } /// Copies the top-left width x height of the last decoded picture out as NV12 planes (Y, interleaved UV). - pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { - self.dec.read_nv12(width, height) + pub fn ring_len(&self) -> u32 { + self.dec.ring_len() + } + + /// Adds one slot to the output ring and returns its index; every slot is then in use or held. + pub fn add_ring_slot(&mut self) -> Result { + self.dec.add_ring_slot() + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again. + pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> { + self.dec.store(slot as usize, crop) + } + + /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV). + pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + self.dec.read_nv12(slot as usize, width, height) } /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes. #[cfg(target_os = "linux")] pub fn read_output_dmabuf( &mut self, - crop: (u32, u32, u32, u32), + slot: u32, + width: u32, + height: u32, ) -> Result { - self.dec.export(crop) + self.dec.export(slot as usize, (width, height)) } /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. pub fn read_output_rgb( &mut self, + slot: u32, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], ) -> Result, Error> { - self.dec.read_rgb(crop, out, bgra, coeffs) + self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs) } } diff --git a/shims/vk-video-ffi/src/h265_decode.rs b/shims/vk-video-ffi/src/h265_decode.rs index 7d5de9ef..1d7dc6fb 100644 --- a/shims/vk-video-ffi/src/h265_decode.rs +++ b/shims/vk-video-ffi/src/h265_decode.rs @@ -694,28 +694,46 @@ impl H265DecodeSession { } /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). - pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { - self.dec.read_nv12(width, height) + pub fn ring_len(&self) -> u32 { + self.dec.ring_len() + } + + /// Adds one slot to the output ring and returns its index; every slot is then in use or held. + pub fn add_ring_slot(&mut self) -> Result { + self.dec.add_ring_slot() + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again. + pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> { + self.dec.store(slot as usize, crop) + } + + /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV). + pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + self.dec.read_nv12(slot as usize, width, height) } /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes. #[cfg(target_os = "linux")] pub fn read_output_dmabuf( &mut self, - crop: (u32, u32, u32, u32), + slot: u32, + width: u32, + height: u32, ) -> Result { - self.dec.export(crop) + self.dec.export(slot as usize, (width, height)) } /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. pub fn read_output_rgb( &mut self, + slot: u32, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], ) -> Result, Error> { - self.dec.read_rgb(crop, out, bgra, coeffs) + self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs) } } diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index e9cc175d..d912291e 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -138,6 +138,10 @@ pub enum Direction { /// Profile a capability is queried for, 4:2:0 only. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum CodecProfile { + /// H.264 Constrained Baseline, 8-bit. + H264ConstrainedBaseline, + /// H.264 Main, 8-bit. + H264Main, /// H.264 High, 8-bit. H264High, /// H.265 Main, 8-bit. @@ -150,6 +154,8 @@ pub enum CodecProfile { Av1Main10, /// VP9 Profile 0, 8-bit. Vp9Profile0, + /// VP9 Profile 2, 10-bit. + Vp9Profile2, } /// Capabilities of one codec, profile and direction. @@ -361,7 +367,10 @@ impl Gpu { /// Capabilities of every codec, profile and direction the device supports. pub fn caps(&self) -> Vec { [ + (Codec::H264, Direction::Encode, CodecProfile::H264Main), (Codec::H264, Direction::Encode, CodecProfile::H264High), + (Codec::H264, Direction::Decode, CodecProfile::H264ConstrainedBaseline), + (Codec::H264, Direction::Decode, CodecProfile::H264Main), (Codec::H264, Direction::Decode, CodecProfile::H264High), (Codec::H265, Direction::Encode, CodecProfile::H265Main), (Codec::H265, Direction::Encode, CodecProfile::H265Main10), @@ -372,6 +381,7 @@ impl Gpu { (Codec::Av1, Direction::Decode, CodecProfile::Av1Main), (Codec::Av1, Direction::Decode, CodecProfile::Av1Main10), (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile0), + (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile2), ] .into_iter() .filter_map(|(codec, direction, profile)| { @@ -423,7 +433,7 @@ impl Gpu { return Err(Error::Unsupported(format!("{codec:?} {direction:?}"))); } let depth = match profile { - CodecProfile::H265Main10 | CodecProfile::Av1Main10 => { + CodecProfile::H265Main10 | CodecProfile::Av1Main10 | CodecProfile::Vp9Profile2 => { vk::VideoComponentBitDepthFlagsKHR::_10 } _ => vk::VideoComponentBitDepthFlagsKHR::_8, @@ -435,14 +445,22 @@ impl Gpu { .luma_bit_depth(depth) .chroma_bit_depth(depth) }; + let h264_idc = match profile { + CodecProfile::H264ConstrainedBaseline => vk::video::STD_VIDEO_H264_PROFILE_IDC_BASELINE, + CodecProfile::H264Main => vk::video::STD_VIDEO_H264_PROFILE_IDC_MAIN, + _ => vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH, + }; + let vp9_profile = match profile { + CodecProfile::Vp9Profile2 => vk::video::STD_VIDEO_VP9_PROFILE_2, + _ => vk::video::STD_VIDEO_VP9_PROFILE_0, + }; let h265_idc = match profile { CodecProfile::H265Main10 => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN_10, _ => vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN, }; match (codec, direction) { (Codec::H264, Direction::Encode) => { - let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH); + let mut h = vk::VideoEncodeH264ProfileInfoKHR::builder().std_profile_idc(h264_idc); let p = base(operation).push_next(&mut h); self.query( codec, @@ -454,7 +472,7 @@ impl Gpu { } (Codec::H264, Direction::Decode) => { let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH) + .std_profile_idc(h264_idc) .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE); let p = base(operation).push_next(&mut h); self.query( @@ -512,8 +530,7 @@ impl Gpu { ) } (Codec::Vp9, _) => { - let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder() - .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0); + let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder().std_profile(vp9_profile); let p = base(operation).push_next(&mut h); self.query( codec, diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 96ad63e2..a9cd1185 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -7,7 +7,7 @@ use vulkanalia::vk::{ }; #[cfg(target_os = "linux")] -use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, plane_copy, release}; +use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, release}; #[cfg(target_os = "linux")] use crate::rgb_convert::check_size; use crate::rgb_convert::{Input, RgbConverter}; @@ -163,6 +163,74 @@ pub(crate) fn color_range() -> vk::ImageSubresourceRange { } } +pub(crate) const EXTERNAL_FAMILY: u32 = if cfg!(target_os = "linux") { + u32::MAX - 1 +} else { + vk::QUEUE_FAMILY_IGNORED +}; + +pub(crate) fn ring_owner(lane: &Lane) -> u32 { + if cfg!(target_os = "linux") { + lane.family + } else { + vk::QUEUE_FAMILY_IGNORED + } +} + +pub(crate) fn transfer( + d: &Device, + cb: vk::CommandBuffer, + image: vk::Image, + from: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32), + to: (vk::ImageLayout, vk::PipelineStageFlags2, vk::AccessFlags2, u32), +) { + let barrier = vk::ImageMemoryBarrier2::builder() + .src_stage_mask(from.1) + .src_access_mask(from.2) + .dst_stage_mask(to.1) + .dst_access_mask(to.2) + .old_layout(from.0) + .new_layout(to.0) + .src_queue_family_index(from.3) + .dst_queue_family_index(to.3) + .image(image) + .subresource_range(color_range()) + .build(); + let barriers = [barrier]; + let info = vk::DependencyInfo::builder() + .image_memory_barriers(&barriers) + .build(); + unsafe { d.cmd_pipeline_barrier2(cb, &info) }; +} + +pub(crate) fn plane_copy( + aspect: vk::ImageAspectFlags, + origin: (u32, u32), + (width, height): (u32, u32), +) -> vk::ImageCopy { + let layers = vk::ImageSubresourceLayers { + aspect_mask: aspect, + mip_level: 0, + base_array_layer: 0, + layer_count: 1, + }; + vk::ImageCopy { + src_subresource: layers, + src_offset: vk::Offset3D { + x: origin.0 as i32, + y: origin.1 as i32, + z: 0, + }, + dst_subresource: layers, + dst_offset: vk::Offset3D { x: 0, y: 0, z: 0 }, + extent: vk::Extent3D { + width, + height, + depth: 1, + }, + } +} + pub(crate) fn copy_region( offset: u64, aspect: vk::ImageAspectFlags, @@ -1304,6 +1372,16 @@ pub(crate) struct Decoder { rgb_out: Buffer, rgb: Option, pub(crate) coded: bool, + ring: Vec, +} + +const RING_EXTRA: u32 = 8; + +struct RingSlot { + image: vk::Image, + memory: vk::DeviceMemory, + #[cfg(target_os = "linux")] + export: crate::dmabuf::Export, } impl Decoder { @@ -1336,6 +1414,7 @@ impl Decoder { rgb_out: Default::default(), rgb: None, coded: false, + ring: Vec::new(), }; let mut list = vk::VideoProfileListInfoKHR::builder() .profiles(std::slice::from_ref(profile)) @@ -1395,6 +1474,11 @@ impl Decoder { (dec.rgb_out.buffer, rgb_size), )?); + for _ in 0..max_dpb_slots + RING_EXTRA { + let slot = dec.ring_slot()?; + dec.ring.push(slot); + } + let d = gpu.device(); let cb = dec.decode.cb; dec.decode.begin()?; @@ -1446,24 +1530,164 @@ impl Decoder { Ok(()) } - /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). + fn ring_slot(&self) -> Result { + let gpu = self.vs.gpu.clone(); + #[cfg(target_os = "linux")] + { + let (image, memory, export) = crate::dmabuf::ring_image( + &gpu, + &self.graphics, + self.vs.format, + (self.max_extent.width, self.max_extent.height), + )?; + Ok(RingSlot { + image, + memory, + export, + }) + } + #[cfg(not(target_os = "linux"))] + { + let d = gpu.device(); + let info = vk::ImageCreateInfo::builder() + .image_type(vk::ImageType::_2D) + .format(self.vs.format) + .extent(vk::Extent3D { + width: self.max_extent.width, + height: self.max_extent.height, + depth: 1, + }) + .mip_levels(1) + .array_layers(1) + .samples(vk::SampleCountFlags::_1) + .tiling(vk::ImageTiling::OPTIMAL) + .usage(vk::ImageUsageFlags::TRANSFER_SRC | vk::ImageUsageFlags::TRANSFER_DST) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED) + .build(); + let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? }; + let req = unsafe { d.get_image_memory_requirements(image) }; + let index = memory_type(&gpu, req.memory_type_bits, vk::MemoryPropertyFlags::DEVICE_LOCAL)?; + let alloc = vk::MemoryAllocateInfo::builder() + .allocation_size(req.size) + .memory_type_index(index) + .build(); + let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? }; + unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory")? }; + self.graphics.begin()?; + init_barrier(d, self.graphics.cb, image, vk::ImageLayout::GENERAL); + self.graphics.end()?; + self.graphics.submit()?; + Ok(RingSlot { image, memory }) + } + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again. + pub(crate) fn store(&mut self, slot: usize, crop: (u32, u32, u32, u32)) -> Result<(), Error> { + self.check_window(crop)?; + let (x, y, width, height) = crop; + let target = self.slot_image(slot)?; + let gpu = self.vs.gpu.clone(); + let d = gpu.device(); + let cb = self.graphics.cb; + let owner = ring_owner(&self.graphics); + let source = self.output.image; + let regions = [ + plane_copy(PLANE_0, (x, y), (width, height)), + plane_copy(PLANE_1, (x / 2, y / 2), (width / 2, height / 2)), + ]; + self.graphics.begin()?; + unsafe { + transfer( + d, + cb, + source, + ( + vk::ImageLayout::VIDEO_DECODE_DST_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + vk::QUEUE_FAMILY_IGNORED, + ), + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + vk::QUEUE_FAMILY_IGNORED, + ), + ); + transfer( + d, + cb, + target, + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + EXTERNAL_FAMILY, + ), + ( + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_WRITE, + owner, + ), + ); + d.cmd_copy_image( + cb, + source, + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + target, + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + ®ions, + ); + transfer( + d, + cb, + target, + ( + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_WRITE, + owner, + ), + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + EXTERNAL_FAMILY, + ), + ); + transfer( + d, + cb, + source, + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + vk::QUEUE_FAMILY_IGNORED, + ), + ( + vk::ImageLayout::VIDEO_DECODE_DST_KHR, + vk::PipelineStageFlags2::ALL_COMMANDS, + vk::AccessFlags2::NONE, + vk::QUEUE_FAMILY_IGNORED, + ), + ); + } + self.graphics.end()?; + self.graphics.submit() + } + + /// Copies the top-left width x height of ring slot `slot` out as NV12 or P010 planes (Y, interleaved UV). pub(crate) fn read_nv12( &mut self, + slot: usize, width: u32, height: u32, ) -> Result<(Vec, Vec), Error> { - if !self.coded { - return Err(Error::Invalid("nothing decoded".into())); - } - if width == 0 - || height == 0 - || width % 2 != 0 - || height % 2 != 0 - || width > self.max_extent.width - || height > self.max_extent.height - { - return Err(Error::Invalid("readback size".into())); - } + self.check_size((width, height))?; + let target = self.slot_image(slot)?; let gpu = self.vs.gpu.clone(); let d = gpu.device(); let bytes = bytes_per_sample(self.vs.format); @@ -1473,40 +1697,28 @@ impl Decoder { copy_region(luma as u64, PLANE_1, width / 2, height / 2), ]; self.graphics.begin()?; - self.copy_to_buffer(d, self.graphics.cb, self.readback.buffer, &copies); + self.slot_to_buffer(d, self.graphics.cb, target, self.readback.buffer, &copies); self.graphics.end()?; self.graphics.submit()?; let bytes = self.readback.bytes(d, luma * 3 / 2)?; Ok((bytes[..luma].to_vec(), bytes[luma..].to_vec())) } - /// Copies the crop window `(x, y, width, height)` of the last decoded picture as packed 4-byte pixels, box-downscaled to `out` and converted to RGB on the GPU with the integer `coeffs` `[ky, rv, gu, gv, bu]`. `bgra` picks the byte order; alpha is 255. + /// Copies the crop window `(x, y, width, height)` of ring slot `slot` as packed 4-byte pixels, box-downscaled to `out` and converted to RGB on the GPU with the integer `coeffs` `[ky, rv, gu, gv, bu]`. `bgra` picks the byte order; alpha is 255. pub(crate) fn read_rgb( &mut self, + slot: usize, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], ) -> Result, Error> { + self.check_window(crop)?; let (x, y, width, height) = crop; - if !self.coded { - return Err(Error::Invalid("nothing decoded".into())); - } - if width == 0 - || height == 0 - || width % 2 != 0 - || height % 2 != 0 - || x % 2 != 0 - || y % 2 != 0 - || x + width > self.max_extent.width - || y + height > self.max_extent.height - || out.0 == 0 - || out.1 == 0 - || out.0 > width - || out.1 > height - { + if out.0 == 0 || out.1 == 0 || out.0 > width || out.1 > height { return Err(Error::Invalid("RGB readback size".into())); } + let target = self.slot_image(slot)?; let pass = self .rgb .as_ref() @@ -1521,7 +1733,7 @@ impl Decoder { copy_rect(luma as u64, PLANE_1, (x / 2, y / 2), (width / 2, height / 2)), ]; self.graphics.begin()?; - self.copy_to_buffer(d, cb, self.planes.buffer, &copies); + self.slot_to_buffer(d, cb, target, self.planes.buffer, &copies); let barrier = vk::BufferMemoryBarrier2::builder() .src_stage_mask(vk::PipelineStageFlags2::COPY) .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE) @@ -1556,13 +1768,45 @@ impl Decoder { Ok(self.rgb_out.bytes(d, len)?.to_vec()) } - /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes. + /// The DMA-BUF of ring slot `slot`, `width` x `height` from its top-left: a second handle on the slot's memory, which the same slot returns every time. #[cfg(target_os = "linux")] pub(crate) fn export( - &mut self, - crop: (u32, u32, u32, u32), + &self, + slot: usize, + (width, height): (u32, u32), ) -> Result { - let (x, y, width, height) = crop; + self.check_size((width, height))?; + let ring = self + .ring + .get(slot) + .ok_or_else(|| Error::Invalid("ring slot out of range".into()))?; + let fd = ring + .export + .fd + .try_clone() + .map_err(|e| Error::Invalid(format!("duplicating DMA-BUF: {e}")))?; + Ok(crate::dmabuf::DmaBufExport { + fd, + modifier: ring.export.modifier, + planes: ring.export.planes, + width, + height, + p010: self.vs.format == P010, + }) + } + + pub(crate) fn ring_len(&self) -> u32 { + self.ring.len() as u32 + } + + /// Adds one slot to the ring when every slot is held, and returns its index. + pub(crate) fn add_ring_slot(&mut self) -> Result { + let slot = self.ring_slot()?; + self.ring.push(slot); + Ok(self.ring.len() as u32 - 1) + } + + fn check_size(&self, (width, height): (u32, u32)) -> Result<(), Error> { if !self.coded { return Err(Error::Invalid("nothing decoded".into())); } @@ -1570,41 +1814,40 @@ impl Decoder { || height == 0 || width % 2 != 0 || height % 2 != 0 - || x % 2 != 0 - || y % 2 != 0 - || x + width > self.max_extent.width - || y + height > self.max_extent.height + || width > self.max_extent.width + || height > self.max_extent.height { - return Err(Error::Invalid("DMA-BUF export size".into())); + return Err(Error::Invalid("picture size".into())); } - let gpu = self.vs.gpu.clone(); - crate::dmabuf::export(&gpu, &self.graphics, self.output.image, self.vs.format, crop) + Ok(()) } - fn copy_to_buffer( + fn check_window(&self, (x, y, width, height): (u32, u32, u32, u32)) -> Result<(), Error> { + self.check_size((width, height))?; + if x % 2 != 0 || y % 2 != 0 || x + width > self.max_extent.width || y + height > self.max_extent.height { + return Err(Error::Invalid("picture window".into())); + } + Ok(()) + } + + fn slot_image(&self, slot: usize) -> Result { + self.ring + .get(slot) + .map(|s| s.image) + .ok_or_else(|| Error::Invalid("ring slot out of range".into())) + } + + fn slot_to_buffer( &self, d: &Device, cb: vk::CommandBuffer, + image: vk::Image, target: vk::Buffer, copies: &[vk::BufferImageCopy], ) { - let image = self.output.image; + let owner = ring_owner(&self.graphics); unsafe { - barrier( - d, - cb, - image, - ( - vk::ImageLayout::VIDEO_DECODE_DST_KHR, - vk::PipelineStageFlags2::ALL_COMMANDS, - vk::AccessFlags2::NONE, - ), - ( - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - vk::PipelineStageFlags2::COPY, - vk::AccessFlags2::TRANSFER_READ, - ), - ); + slot_acquire(d, cb, image, owner); d.cmd_copy_image_to_buffer( cb, image, @@ -1612,25 +1855,51 @@ impl Decoder { target, copies, ); - barrier( - d, - cb, - image, - ( - vk::ImageLayout::TRANSFER_SRC_OPTIMAL, - vk::PipelineStageFlags2::COPY, - vk::AccessFlags2::TRANSFER_READ, - ), - ( - vk::ImageLayout::VIDEO_DECODE_DST_KHR, - vk::PipelineStageFlags2::ALL_COMMANDS, - vk::AccessFlags2::NONE, - ), - ); + slot_release(d, cb, image, owner); } } } +fn slot_acquire(d: &Device, cb: vk::CommandBuffer, image: vk::Image, owner: u32) { + transfer( + d, + cb, + image, + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + EXTERNAL_FAMILY, + ), + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + owner, + ), + ); +} + +fn slot_release(d: &Device, cb: vk::CommandBuffer, image: vk::Image, owner: u32) { + transfer( + d, + cb, + image, + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + owner, + ), + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + EXTERNAL_FAMILY, + ), + ); +} + impl Drop for Decoder { fn drop(&mut self) { let gpu = self.vs.gpu.clone(); @@ -1641,6 +1910,12 @@ impl Drop for Decoder { for img in self.dpb.iter().chain(std::iter::once(&self.output)) { img.destroy(d); } + for slot in &self.ring { + unsafe { + d.destroy_image(slot.image, None); + d.free_memory(slot.memory, None); + } + } self.bitstream.destroy(d); self.readback.destroy(d); self.planes.destroy(d); diff --git a/shims/vk-video-ffi/src/vp9_decode.rs b/shims/vk-video-ffi/src/vp9_decode.rs index 3dee49f2..03392826 100644 --- a/shims/vk-video-ffi/src/vp9_decode.rs +++ b/shims/vk-video-ffi/src/vp9_decode.rs @@ -413,28 +413,46 @@ impl Vp9DecodeSession { } /// Copies the top-left width x height of the last decoded picture out as NV12 or P010 planes (Y, interleaved UV). - pub fn read_output(&mut self, width: u32, height: u32) -> Result<(Vec, Vec), Error> { - self.dec.read_nv12(width, height) + pub fn ring_len(&self) -> u32 { + self.dec.ring_len() + } + + /// Adds one slot to the output ring and returns its index; every slot is then in use or held. + pub fn add_ring_slot(&mut self) -> Result { + self.dec.add_ring_slot() + } + + /// Copies the crop window `(x, y, width, height)` of the last decoded picture into ring slot `slot`, where it stays until that slot is stored into again. + pub fn store_output(&mut self, slot: u32, crop: (u32, u32, u32, u32)) -> Result<(), Error> { + self.dec.store(slot as usize, crop) + } + + /// The top-left width x height of ring slot `slot` as NV12 planes (Y, interleaved UV). + pub fn read_output(&mut self, slot: u32, width: u32, height: u32) -> Result<(Vec, Vec), Error> { + self.dec.read_nv12(slot as usize, width, height) } /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes. #[cfg(target_os = "linux")] pub fn read_output_dmabuf( &mut self, - crop: (u32, u32, u32, u32), + slot: u32, + width: u32, + height: u32, ) -> Result { - self.dec.export(crop) + self.dec.export(slot as usize, (width, height)) } /// Packed 4-byte pixels of the crop window `(x, y, width, height)` of the last decoded picture, box-downscaled to `out`, converted to RGB with integer `coeffs` `[ky, rv, gu, gv, bu]`; `bgra` picks the byte order. pub fn read_output_rgb( &mut self, + slot: u32, crop: (u32, u32, u32, u32), out: (u32, u32), bgra: bool, coeffs: [i32; 5], ) -> Result, Error> { - self.dec.read_rgb(crop, out, bgra, coeffs) + self.dec.read_rgb(slot as usize, crop, out, bgra, coeffs) } }