diff --git a/crates/ec-hw/examples/hw_caps.rs b/crates/ec-hw/examples/hw_caps.rs index e8599e92..555255bb 100644 --- a/crates/ec-hw/examples/hw_caps.rs +++ b/crates/ec-hw/examples/hw_caps.rs @@ -16,8 +16,8 @@ const HEIGHT: u32 = 720; fn main() { for cap in capabilities() { println!( - "{:?} {:?} {:?} max {}x{}", - cap.backend, cap.direction, cap.codec, cap.max_width, cap.max_height + "{:?} {:?} {:?} {:?} max {}x{}", + cap.backend, cap.direction, cap.codec, cap.profile, cap.max_width, cap.max_height ); } for codec in [EncCodec::H264, EncCodec::H265, EncCodec::Av1] { diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index 136c9480..17074eaf 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -9,7 +9,10 @@ use std::fs; use std::path::{Path, PathBuf}; use std::process::Command; -use ec_hw::{Backend, Codec, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, I420, RateControlMode}; +use ec_hw::{ + Backend, Codec, DmaBufPicture, EncCodec, EncoderConfig, FrameMetadata, HwDecoder, HwEncoder, + I420, I420_16, RateControlMode, +}; struct Case { name: &'static str, @@ -108,6 +111,171 @@ fn main() { grain(&dir); own_av1(&dir); vp9_cases(&dir); + dmabuf_cases(&dir); + seek_case(&dir); +} + +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); + let hevc = fs::read(dir.join("h265idr720.hevc")).expect("read h265idr720"); + dmabuf_case("h265idr720.hevc", Codec::H265, &[&hevc[..]], false); + let av1 = fs::read(dir.join("av1aom720.ivf")).expect("read av1aom720"); + dmabuf_case("av1aom720.ivf", Codec::Av1, &ivf_units(&av1), false); + let vp9 = fs::read(dir.join("vp9_720.ivf")).expect("read vp9_720"); + dmabuf_case("vp9_720.ivf", Codec::Vp9, &ivf_units(&vp9), false); + let ten = fs::read(dir.join("ten.hevc")).expect("read ten.hevc"); + dmabuf_case("ten.hevc P010", Codec::H265, &nal_units(&ten), true); +} + +fn dmabuf_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool) { + let mut reference = if ten { + HwDecoder::open_16(codec) + } else { + HwDecoder::open(codec) + } + .expect("open decoder"); + assert_eq!(reference.backend(), Backend::Vk, "{label}: must decode on Vulkan"); + let expected = decoded_planes(&mut reference, units, ten); + + let gpu = ec_vk::Gpu::open().expect("Vulkan device"); + let mut decoder = HwDecoder::open_dmabuf(codec).expect("open DMA-BUF decoder"); + assert_eq!(decoder.backend(), Backend::Vk, "{label}: DMA-BUF must decode on Vulkan"); + let mut got = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode DMA-BUF"); + collect_dmabuf(&mut decoder, &gpu, &mut got); + } + decoder.flush().expect("flush DMA-BUF"); + collect_dmabuf(&mut decoder, &gpu, &mut got); + compare_planes(label, codec, &expected, &got); +} + +fn decoded_planes(decoder: &mut HwDecoder, units: &[&[u8]], ten: bool) -> Vec<(Vec, Vec)> { + let mut out = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode"); + take_planes(decoder, ten, &mut out); + } + decoder.flush().expect("flush"); + take_planes(decoder, ten, &mut out); + out +} + +fn take_planes(decoder: &mut HwDecoder, ten: bool, out: &mut Vec<(Vec, Vec)>) { + if ten { + while let Some((_, frame)) = decoder.next_frame_16().expect("next frame") { + out.push(p010_planes(&frame)); + } + } else { + while let Some((_, frame)) = decoder.next_frame().expect("next frame") { + out.push(nv12_planes(&frame)); + } + } +} + +fn nv12_planes(frame: &I420) -> (Vec, Vec) { + let uv = frame.u.iter().zip(&frame.v).flat_map(|(&u, &v)| [u, v]).collect(); + (frame.y.clone(), uv) +} + +fn p010_planes(frame: &I420_16) -> (Vec, Vec) { + let le = |v: &u16| (v << 6).to_le_bytes(); + let y = frame.y.iter().flat_map(le).collect(); + let uv = frame + .u + .iter() + .zip(&frame.v) + .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten()) + .collect(); + (y, uv) +} + +fn collect_dmabuf(decoder: &mut HwDecoder, gpu: &ec_vk::Gpu, out: &mut Vec<(Vec, Vec)>) { + while let Some((_, picture)) = decoder.next_dmabuf().expect("next DMA-BUF") { + out.push(read_back(gpu, picture)); + } +} + +fn read_back(gpu: &ec_vk::Gpu, picture: DmaBufPicture) -> (Vec, Vec) { + assert!(picture.planes.iter().all(|p| p.fd == 0), "one DMA-BUF object per picture"); + let p010 = picture.fourcc == u32::from_le_bytes(*b"P010"); + let planes = picture.planes; + let fd = picture.fds.into_iter().next().expect("one DMA-BUF object"); + let export = ec_vk::DmaBufExport { + fd, + modifier: picture.modifier, + planes, + width: picture.width, + height: picture.height, + p010, + }; + ec_vk::read_dmabuf(gpu, &export).expect("read back DMA-BUF") +} + +fn compare_planes(label: &str, codec: Codec, expected: &[(Vec, Vec)], got: &[(Vec, Vec)]) { + assert_eq!(got.len(), expected.len(), "{label}: frame count"); + let mut luma_sum = 0.0f64; + let mut luma_len = 0usize; + let mut chroma_diff = 0usize; + for ((ey, euv), (gy, guv)) in expected.iter().zip(got) { + assert_eq!((ey.len(), euv.len()), (gy.len(), guv.len()), "{label}: plane size"); + luma_sum += ey.iter().zip(gy).map(|(&a, &b)| (a as f64 - b as f64).abs()).sum::(); + luma_len += ey.len(); + chroma_diff += euv.iter().zip(guv).filter(|(a, b)| a != b).count(); + } + let mean = luma_sum / luma_len.max(1) as f64; + println!( + "{label} {codec:?} DMA-BUF: decoded {} frames, max mean |diff| Y {mean:.6}, UV mismatched bytes {chroma_diff}", + got.len(), + ); + assert_eq!(chroma_diff, 0, "{label}: UV differs"); + assert_eq!(mean, 0.0, "{label}: Y differs"); +} + +fn seek_case(dir: &Path) { + let stream = fs::read(dir.join("bf1280.h264")).expect("read bf1280"); + let reference = fs::read(dir.join("bf1280.yuv")).expect("read bf1280 reference"); + let units = h264_units(&stream); + let mut decoder = HwDecoder::open(Codec::H264).expect("open decoder"); + assert_eq!(decoder.backend(), Backend::Vk, "seek: must decode on Vulkan"); + let mut before = Vec::new(); + for (pts, unit) in units.iter().take(21).enumerate() { + decoder.decode(unit, pts as i64).expect("decode before seek"); + drain(&mut decoder, &mut before); + } + println!("seek: {} frames before reset", before.len()); + decoder.reset(); + assert!(decoder.decode(units[5], 0).is_err(), "seek: P picture after reset must be an error"); + let mut after = Vec::new(); + for (pts, unit) in units.iter().enumerate() { + decoder.decode(unit, pts as i64).expect("decode from IDR after seek"); + drain(&mut decoder, &mut after); + } + decoder.flush().expect("flush"); + drain(&mut decoder, &mut after); + compare("bf1280 seek", Codec::H264, Backend::Vk, dims("1280x720"), &after, &reference); +} + +fn h264_units(data: &[u8]) -> Vec<&[u8]> { + let mut units = Vec::new(); + let mut start = 0; + let mut seen_slice = false; + for nal in nal_units(data) { + let at = nal.as_ptr() as usize - data.as_ptr() as usize; + let body = if nal[..3] == [0, 0, 1] { 3 } else { 4 }; + let kind = nal[body] & 0x1f; + let slice = matches!(kind, 1 | 5); + let first_slice = slice && nal[body + 1] & 0x80 != 0; + if (first_slice || (matches!(kind, 6..=9) && seen_slice)) && seen_slice { + units.push(&data[start..at]); + start = at; + seen_slice = false; + } + seen_slice |= slice; + } + units.push(&data[start..]); + units } fn vp9_cases(dir: &Path) { diff --git a/crates/ec-hw/src/hw.rs b/crates/ec-hw/src/hw.rs index 0bb83eee..722ed988 100644 --- a/crates/ec-hw/src/hw.rs +++ b/crates/ec-hw/src/hw.rs @@ -12,7 +12,7 @@ use std::collections::VecDeque; use crate::error::{Error, Result}; use crate::picture::{Decoded, I420, I420_16, RgbPicture}; #[cfg(target_os = "linux")] -use crate::picture::{rgb_size, yuv_to_rgb}; +use crate::picture::{DmaBufPicture, i420_to_rgb}; #[cfg(target_os = "linux")] use ec_core::color::{ColorDescription, Matrix, Tags}; use crate::types::{ @@ -46,11 +46,30 @@ pub enum Direction { Decode, } -/// One codec, direction and backend this machine offers. +/// Profile of a [`Capability`], 4:2:0 only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CodecProfile { + /// H.264 High, 8-bit. + H264High, + /// H.265 Main, 8-bit. + H265Main, + /// H.265 Main 10, 10-bit. + H265Main10, + /// AV1 Main, 8-bit. + Av1Main, + /// AV1 Main, 10-bit. + Av1Main10, + /// VP9 Profile 0, 8-bit. + Vp9Profile0, +} + +/// One codec, profile, direction and backend this machine offers. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct Capability { /// Codec. pub codec: Codec, + /// Profile. + pub profile: CodecProfile, /// Direction. pub direction: Direction, /// Largest width in luma samples. @@ -125,6 +144,7 @@ pub fn capabilities() -> Vec { &mut out, Capability { codec, + profile: vk_profile(caps.profile), direction, max_width: caps.max_width, max_height: caps.max_height, @@ -141,7 +161,12 @@ pub fn capabilities() -> Vec { fn push(out: &mut Vec, cap: Capability) { let known = out .iter() - .any(|c| c.codec == cap.codec && c.direction == cap.direction && c.backend == cap.backend); + .any(|c| { + c.codec == cap.codec + && c.profile == cap.profile + && c.direction == cap.direction + && c.backend == cap.backend + }); if !known { out.push(cap); } @@ -156,9 +181,6 @@ fn va_capabilities(out: &mut Vec) { return; }; for entry in &report.entries { - let Some(codec) = va_codec(entry.profile) else { - continue; - }; let direction = match entry.entrypoint { ec_va::Entrypoint::VLD => Direction::Decode, ec_va::Entrypoint::EncSlice | ec_va::Entrypoint::EncSliceLP => Direction::Encode, @@ -168,32 +190,64 @@ fn va_capabilities(out: &mut Vec) { Some(s) => (s.max_width.unwrap_or(4096), s.max_height.unwrap_or(4096)), None => (4096, 4096), }; - push( - out, - Capability { - codec, - direction, - max_width, - max_height, - backend: Backend::Va, - }, - ); + for profile in va_profiles(entry.profile, entry.rt_formats) { + push( + out, + Capability { + codec: profile.codec(), + profile, + direction, + max_width, + max_height, + backend: Backend::Va, + }, + ); + } } } #[cfg(target_os = "linux")] -fn va_codec(profile: ec_va::Profile) -> Option { - Some(match profile { - ec_va::Profile::H264Baseline - | ec_va::Profile::H264ConstrainedBaseline - | ec_va::Profile::H264Main - | ec_va::Profile::H264High - | ec_va::Profile::H264High10 => Codec::H264, - ec_va::Profile::HEVCMain | ec_va::Profile::HEVCMain10 => Codec::H265, - ec_va::Profile::VP9Profile0 => Codec::Vp9, - ec_va::Profile::AV1Profile0 => Codec::Av1, - _ => return None, - }) +impl CodecProfile { + fn codec(self) -> Codec { + match self { + CodecProfile::H264High => Codec::H264, + CodecProfile::H265Main | CodecProfile::H265Main10 => Codec::H265, + CodecProfile::Av1Main | CodecProfile::Av1Main10 => Codec::Av1, + CodecProfile::Vp9Profile0 => Codec::Vp9, + } + } +} + +#[cfg(target_os = "linux")] +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::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::AV1Profile0 => [ + (yuv420, CodecProfile::Av1Main), + (yuv420_10, CodecProfile::Av1Main10), + ] + .into_iter() + .filter(|(bit, _)| rt_formats & bit != 0) + .map(|(_, p)| p) + .collect(), + _ => Vec::new(), + } +} + +fn vk_profile(profile: ec_vk::CodecProfile) -> CodecProfile { + match profile { + ec_vk::CodecProfile::H264High => CodecProfile::H264High, + ec_vk::CodecProfile::H265Main => CodecProfile::H265Main, + ec_vk::CodecProfile::H265Main10 => CodecProfile::H265Main10, + ec_vk::CodecProfile::Av1Main => CodecProfile::Av1Main, + ec_vk::CodecProfile::Av1Main10 => CodecProfile::Av1Main10, + ec_vk::CodecProfile::Vp9Profile0 => CodecProfile::Vp9Profile0, + } } /// Byte order of a packed 32-bit RGB pixel; the X or A byte is ignored. @@ -863,6 +917,15 @@ impl VkDecoder { VkDecoder::Vp9(d) => d.flush(), } } + + fn reset(&mut self) { + match self { + VkDecoder::H264(d) => d.reset(), + VkDecoder::H265(d) => d.reset(), + VkDecoder::Av1(d) => d.reset(), + VkDecoder::Vp9(d) => d.reset(), + } + } } enum DecInner { @@ -887,6 +950,8 @@ pub(crate) enum Mode { I420, I420_16, Rgb(RgbOutput), + #[cfg(target_os = "linux")] + DmaBuf, } /// A hardware decoder on whichever backend opened. @@ -916,6 +981,12 @@ impl HwDecoder { HwDecoder::open_mode(codec, Mode::I420_16) } + /// Open a decoder for `codec` that hands out each picture as DMA-BUF file descriptors ([`HwDecoder::next_dmabuf`]). Linux only. + #[cfg(target_os = "linux")] + pub fn open_dmabuf(codec: Codec) -> Result { + HwDecoder::open_mode(codec, Mode::DmaBuf) + } + fn open_mode(codec: Codec, mode: Mode) -> Result { let mut reasons = Vec::new(); let born_epoch = crate::reset::gpu_reset_epoch(); @@ -1024,6 +1095,21 @@ impl HwDecoder { } } + /// 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`]. + #[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")), + } + } + /// 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(_)) { @@ -1062,6 +1148,7 @@ impl HwDecoder { .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))) } @@ -1070,6 +1157,16 @@ impl HwDecoder { } } + /// Drop every held picture and all reference state so decoding restarts at a sync sample after a seek. Parameter sets and the GPU session survive. After a reset an inter picture whose references were not decoded since is an error, never a guess. + pub fn reset(&mut self) { + match &mut self.inner { + DecInner::Vk(d) => d.reset(), + #[cfg(target_os = "linux")] + DecInner::Va(d) => d.reset(), + } + self.replay = None; + } + /// Emit every picture still held for reordering. pub fn flush(&mut self) -> Result<()> { match &mut self.inner { @@ -1080,6 +1177,32 @@ 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 @@ -1087,17 +1210,12 @@ fn default_matrix(height: u32) -> Matrix { #[cfg(target_os = "linux")] fn va_rgb(frame: &I420, output: RgbOutput, matrix: Matrix) -> RgbPicture { - let (w, h) = rgb_size(frame.width, frame.height, output.max_width); - let data = ec_dsp::rgb::i420_to_packed( - &frame.y, - &frame.u, - &frame.v, - (frame.width as usize, frame.height as usize), - (w as usize, h as usize), + i420_to_rgb( + frame, + output.max_width, output.order == RgbOrder::Bgra, - &yuv_to_rgb(matrix), - ); - RgbPicture::new(data, w, h) + matrix, + ) } #[cfg(target_os = "linux")] diff --git a/crates/ec-hw/src/lib.rs b/crates/ec-hw/src/lib.rs index 9a261ba6..3e10669a 100644 --- a/crates/ec-hw/src/lib.rs +++ b/crates/ec-hw/src/lib.rs @@ -90,14 +90,15 @@ pub use ec_vk::{DmaBufFormat, DmaBufPlane}; #[cfg(target_os = "linux")] pub use hw::{DmaBufFrame, DmaBufYuvFrame}; pub use hw::{ - Backend, Capability, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, RgbOrder, - RgbOutput, - capabilities, + Backend, Capability, CodecProfile, Direction, EncodeInput, HwDecoder, HwEncoder, RgbFrame, + RgbOrder, RgbOutput, capabilities, }; #[cfg(target_os = "linux")] pub use frame::Frame; pub use picture::{Colour, I420, I420_16, RgbPicture, i420_to_nv12, nv12_to_i420}; #[cfg(target_os = "linux")] +pub use picture::DmaBufPicture; +#[cfg(target_os = "linux")] pub use pool::{PooledSurface, SurfacePool}; pub use reset::{gpu_recently_reset, gpu_reset_epoch, report_gpu_reset}; pub use types::{ diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index f27a7538..d6cb866b 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -58,12 +58,84 @@ impl RgbPicture { } } +/// A decoded picture as DMA-BUF file descriptors: NV12 or P010, Y then UV, in an exportable layout. +#[cfg(target_os = "linux")] +#[derive(Debug)] +pub struct DmaBufPicture { + /// The DMA-BUF objects. Each is closed when the picture drops. + pub fds: Vec, + /// DRM fourcc: NV12 or P010. + pub fourcc: u32, + /// DRM format modifier, 0 for linear. + pub modifier: u64, + /// Width in luma samples. + pub width: u32, + /// Height in luma samples. + pub height: u32, + /// Y plane then UV plane. + pub planes: [ec_vk::DmaBufPlane; 2], +} + +#[cfg(target_os = "linux")] +impl From for DmaBufPicture { + fn from(export: ec_vk::DmaBufExport) -> DmaBufPicture { + let fourcc = if export.p010 { + u32::from_le_bytes(*b"P010") + } else { + u32::from_le_bytes(*b"NV12") + }; + DmaBufPicture { + fds: vec![export.fd], + fourcc, + modifier: export.modifier, + width: export.width, + height: export.height, + planes: export.planes, + } + } +} + +#[cfg(target_os = "linux")] +impl DmaBufPicture { + /// A second handle on the same memory, for a picture shown again from a reference. + pub fn try_clone(&self) -> std::io::Result { + Ok(DmaBufPicture { + fds: self + .fds + .iter() + .map(|fd| fd.try_clone()) + .collect::>()?, + fourcc: self.fourcc, + modifier: self.modifier, + width: self.width, + height: self.height, + planes: self.planes, + }) + } +} + /// One decoded picture in the decoder's output form. -#[derive(Debug, Clone, PartialEq, Eq)] +#[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. @@ -74,6 +146,26 @@ pub(crate) fn yuv_to_rgb(matrix: Matrix) -> ec_dsp::rgb::YuvToRgb { } } +/// Packed RGB of an 8-bit I420 picture, scaled to `max_width`, converted on the CPU with the coefficients of `matrix`. +pub(crate) fn i420_to_rgb( + frame: &I420, + max_width: Option, + bgra: bool, + matrix: Matrix, +) -> RgbPicture { + let (w, h) = rgb_size(frame.width, frame.height, max_width); + let data = ec_dsp::rgb::i420_to_packed( + &frame.y, + &frame.u, + &frame.v, + (frame.width as usize, frame.height as usize), + (w as usize, h as usize), + bgra, + &yuv_to_rgb(matrix), + ); + RgbPicture::new(data, w, h) +} + /// Output size of an RGB picture of `width` x `height`: scaled to `max_width` keeping the aspect, height rounded to the nearest even. pub(crate) fn rgb_size(width: u32, height: u32, max_width: Option) -> (u32, u32) { match max_width { diff --git a/crates/ec-hw/src/vkdec264.rs b/crates/ec-hw/src/vkdec264.rs index 34ca8923..3ceab5bc 100644 --- a/crates/ec-hw/src/vkdec264.rs +++ b/crates/ec-hw/src/vkdec264.rs @@ -4,7 +4,8 @@ use std::collections::{HashMap, VecDeque}; use ec_h264_syntax::sps::{ZIGZAG_4X4, ZIGZAG_8X8}; use ec_h264_syntax::{ - AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, Sps, unescape_rbsp, + AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, + unescape_rbsp, }; use ec_vk::{ H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, @@ -127,6 +128,13 @@ impl VkH264Decoder { self.ready.pop_front() } + pub(crate) fn reset(&mut self) { + self.current = None; + self.dpb.clear(); + self.pics.clear(); + self.ready.clear(); + } + pub(crate) fn flush(&mut self) -> Result<()> { self.finish_picture()?; self.bump(true); @@ -179,6 +187,12 @@ impl VkH264Decoder { header: NalHeader, timestamp: i64, ) -> Result<()> { + let inter = !matches!(sh.slice_type, SliceType::I | SliceType::Si); + if inter && !header.is_idr() && self.dpb.frames.iter().all(|p| p.mark == Mark::Unused) { + return Err(Error::Stream(ec_core::Error::corrupt( + "H.264 inter picture with no reference picture since the last IDR or reset", + ))); + } self.ensure_session(sps)?; if self.params_dirty { self.set_parameters()?; @@ -342,6 +356,17 @@ impl VkH264Decoder { (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 = diff --git a/crates/ec-hw/src/vkdec265.rs b/crates/ec-hw/src/vkdec265.rs index 5dbf4731..3159b91a 100644 --- a/crates/ec-hw/src/vkdec265.rs +++ b/crates/ec-hw/src/vkdec265.rs @@ -124,6 +124,15 @@ impl VkH265Decoder { self.ready.pop_front() } + pub(crate) fn reset(&mut self) { + self.current = None; + self.dpb.pictures.clear(); + self.dpb.started = false; + self.dpb.prev_tid0_poc = 0; + self.outputs.clear(); + self.ready.clear(); + } + pub(crate) fn flush(&mut self) -> Result<()> { self.finish_picture()?; self.bump(true); @@ -360,6 +369,15 @@ impl VkH265Decoder { )?; 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); diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index 07947f95..2305e392 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -22,8 +22,8 @@ use ec_core::color::{ColorDescription, Tags}; use crate::hw::{Mode, RgbOrder}; use crate::picture::{ - Decoded, I420, RgbPicture, rgb_size, semi_planar_to_i420, semi_planar_to_i420_16, - yuv_to_rgb, + Decoded, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420, + semi_planar_to_i420_16, yuv_to_rgb, }; const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; @@ -94,6 +94,12 @@ impl VkAv1Decoder { self.ready.pop_front() } + pub(crate) fn reset(&mut self) { + self.parser = Av1Parser::new(); + self.refs = RefSlots::new(); + self.ready.clear(); + } + pub(crate) fn flush(&mut self) -> Result<()> { Ok(()) } @@ -108,16 +114,19 @@ impl VkAv1Decoder { "AV1 show_existing_frame names an empty reference slot", )) })?; - let shown = if header.film_grain.apply_grain { - let seq = self - .parser - .sequence_header() - .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; - grain_supported(seq, !matches!(self.mode, Mode::I420))?; - grained(reference.picture.clone(), &header.film_grain, seq) - } else { - reference.picture.clone() - }; + let seq = self + .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)); if header.frame_type == FrameType::Key { self.refs.refresh(u8::MAX, Some(reference)); @@ -137,7 +146,7 @@ impl VkAv1Decoder { .sequence_header() .cloned() .ok_or_else(|| Error::config("AV1 frame before any sequence header"))?; - check_supported(&seq, header, !matches!(self.mode, Mode::I420))?; + check_supported(&seq, header, self.mode)?; let (width, height) = (header.upscaled_width, header.frame_height); self.ensure_session(&seq, width, height)?; @@ -180,7 +189,12 @@ impl VkAv1Decoder { if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } - let decoded = match self.mode { + 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( @@ -203,6 +217,11 @@ impl VkAv1Decoder { (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; @@ -226,10 +245,8 @@ impl VkAv1Decoder { segmentation_enabled: header.segmentation.enabled, }; if header.show_frame { - self.ready.push_back(( - timestamp, - grained(decoded.clone(), &header.film_grain, &seq), - )); + let shown = present(mode, decoded.try_clone()?, &header.film_grain, &seq)?; + self.ready.push_back((timestamp, shown)); } if header.refresh_frame_flags != 0 { let reference = Rc::new(Reference { @@ -287,7 +304,7 @@ impl VkAv1Decoder { } } -fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Result<()> { +fn check_supported(seq: &SequenceHeader, header: &FrameHeader, mode: Mode) -> Result<()> { let c = &seq.color_config; if seq.seq_profile != 0 || !matches!(c.bit_depth, 8 | 10) @@ -304,28 +321,90 @@ fn check_supported(seq: &SequenceHeader, header: &FrameHeader, rgb: bool) -> Res return Err(Error::unsupported("Vulkan AV1 decode", "odd frame size")); } if header.film_grain.apply_grain { - grain_supported(seq, rgb)?; + grain_supported(seq, mode)?; } Ok(()) } -fn grain_supported(seq: &SequenceHeader, rgb: bool) -> Result<()> { - if rgb || seq.color_config.bit_depth != 8 { - return Err(Error::unsupported( +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", - "only 8-bit I420 output", - )); + "not for this output format", + )) } - Ok(()) +} + +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) if grain.apply_grain => Decoded::I420(synthesize(frame, grain, seq)), + 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 { + 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::>(); + let clean = Picture { + width: frame.width as usize, + height: frame.height as usize, + y: narrow(&frame.y), + u: narrow(&frame.u), + v: narrow(&frame.v), + }; + let out = ec_av1::apply_film_grain( + &clean, + grain, + seq.color_config.matrix_coefficients == 0, + bit_depth, + ); + let widen = |p: &[u16]| p.iter().map(|&s| s << shift).collect::>(); + I420_16 { + y: widen(&out.y), + u: widen(&out.u), + v: widen(&out.v), + width: frame.width, + height: frame.height, + bit_depth: 10, + } +} + fn synthesize(frame: I420, grain: &FilmGrainParams, seq: &SequenceHeader) -> I420 { let wide = |p: &[u8]| p.iter().map(|&s| u16::from(s)).collect::>(); let clean = Picture { diff --git a/crates/ec-hw/src/vkdec_vp9.rs b/crates/ec-hw/src/vkdec_vp9.rs index 9aa13506..896825fd 100644 --- a/crates/ec-hw/src/vkdec_vp9.rs +++ b/crates/ec-hw/src/vkdec_vp9.rs @@ -83,6 +83,13 @@ impl VkVp9Decoder { self.ready.pop_front() } + pub(crate) fn reset(&mut self) { + self.parser = Vp9Parser::new(); + self.refs = RefSlots::new(); + self.previous = None; + self.ready.clear(); + } + pub(crate) fn flush(&mut self) -> Result<()> { Ok(()) } @@ -99,7 +106,7 @@ impl VkVp9Decoder { "VP9 show_existing_frame names an empty reference slot", )) })?; - self.ready.push_back((timestamp, reference.picture.clone())); + self.ready.push_back((timestamp, reference.picture.try_clone()?)); if let Some(previous) = self.previous.as_mut() { previous.show_frame = true; } @@ -180,6 +187,11 @@ impl VkVp9Decoder { (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)), @@ -198,7 +210,7 @@ impl VkVp9Decoder { } }; if header.show_frame { - self.ready.push_back((timestamp, decoded.clone())); + self.ready.push_back((timestamp, decoded.try_clone()?)); } if header.refresh_frame_flags != 0 { let reference = Rc::new(Reference { diff --git a/crates/ec-vk/src/lib.rs b/crates/ec-vk/src/lib.rs index 6eebfff5..a2dc9bbf 100644 --- a/crates/ec-vk/src/lib.rs +++ b/crates/ec-vk/src/lib.rs @@ -12,12 +12,12 @@ mod h265; pub use av1::{Av1Encoder, Av1EncoderConfig}; pub use h265::{H265Encoder, H265EncoderConfig}; #[cfg(target_os = "linux")] -pub use vk_video_ffi::{DmaBuf, DmaBufFormat, DmaBufPlane}; +pub use vk_video_ffi::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, read_dmabuf}; pub use vk_video_ffi::{ Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams, Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter, Av1LoopRestoration, Av1Quantization, Av1RefSlot, Av1Restoration, Av1Segmentation, - Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, Direction, + Av1SequenceHeader, Av1TileInfo, Av1TimingInfo, Av1TxMode, Av1WarpModel, Codec, CodecProfile, Direction, Error, Gpu, H264DecodeConfig, H264DecodePicture, H264DecodeSession, H264Pps, H264RefSlot, H264Sps, H265DecPicBufMgr, H265DecodeConfig, H265DecodePicture, H265DecodeSession, H265LongTermRefPicSps, H265Pcm, H265Pps, H265ProfileTierLevel, H265RefSlot, H265ScalingLists, diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs index cba422c9..e3f5c196 100644 --- a/shims/vk-video-ffi/src/av1_decode.rs +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -857,6 +857,15 @@ impl Av1DecodeSession { self.dec.read_nv12(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), + ) -> Result { + self.dec.export(crop) + } + /// 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, diff --git a/shims/vk-video-ffi/src/dmabuf.rs b/shims/vk-video-ffi/src/dmabuf.rs index 1eb05069..c0e5523d 100644 --- a/shims/vk-video-ffi/src/dmabuf.rs +++ b/shims/vk-video-ffi/src/dmabuf.rs @@ -1,10 +1,14 @@ -use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd}; +use std::ffi::c_int; +use std::os::fd::{AsRawFd, BorrowedFd, FromRawFd, IntoRawFd, OwnedFd}; use std::os::unix::fs::MetadataExt; use vulkanalia::prelude::v1_3::*; -use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands; +use vulkanalia::vk::{ + ExtImageDrmFormatModifierExtensionDeviceCommands, KhrExternalMemoryFdExtensionDeviceCommands, +}; -use crate::session::{NV12, P010, memory_type, vk}; +use crate::session::{Lane, NV12, P010, PLANE_0, PLANE_1, color_range, memory_type, vk}; +use std::os::fd::AsFd; use crate::{Error, Gpu}; const CACHE_SIZE: usize = 16; @@ -59,6 +63,26 @@ pub struct DmaBuf<'a> { pub format: DmaBufFormat, } +/// A decoded picture exported as one DMA-BUF holding NV12 or P010 planes (Y, then interleaved UV). +#[derive(Debug)] +pub struct DmaBufExport { + /// The DMA-BUF; both planes live in it. + pub fd: OwnedFd, + /// DRM format modifier, 0 for linear. + pub modifier: u64, + /// Y then UV plane. + pub planes: [DmaBufPlane; 2], + /// Width in pixels. + pub width: u32, + /// Height in pixels. + pub height: u32, + /// P010 (10 bits in 16-bit words) when true, NV12 otherwise. + pub p010: bool, +} + +const MEMORY_PLANES: [u32; 4] = [0x80, 0x100, 0x200, 0x400]; +const QUEUE_FAMILY_FOREIGN: u32 = u32::MAX - 1; + pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> { let ext = gpu.device().extensions(); let needed = [ @@ -103,26 +127,6 @@ fn aspect_range(aspect: vk::ImageAspectFlags) -> vk::ImageSubresourceRange { } } -pub(crate) fn plane_copy(aspect: vk::ImageAspectFlags, width: u32, height: u32) -> vk::ImageCopy { - let layers = vk::ImageSubresourceLayers { - aspect_mask: aspect, - mip_level: 0, - base_array_layer: 0, - layer_count: 1, - }; - vk::ImageCopy::builder() - .src_subresource(layers) - .src_offset(vk::Offset3D { x: 0, y: 0, z: 0 }) - .dst_subresource(layers) - .dst_offset(vk::Offset3D { x: 0, y: 0, z: 0 }) - .extent(vk::Extent3D { - width, - height, - depth: 1, - }) - .build() -} - pub(crate) fn acquire( d: &Device, cb: vk::CommandBuffer, @@ -456,3 +460,458 @@ fn bind(gpu: &Gpu, image: vk::Image, src: &DmaBuf) -> Result Vec { + let instance = gpu.instance(); + let mut count = vk::DrmFormatModifierPropertiesListEXT::builder().build(); + let mut props = vk::FormatProperties2::builder().push_next(&mut count).build(); + unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) }; + let n = count.drm_format_modifier_count as usize; + let mut list = vec![vk::DrmFormatModifierPropertiesEXT::default(); n]; + let mut full = vk::DrmFormatModifierPropertiesListEXT::builder() + .drm_format_modifier_properties(&mut list) + .build(); + let mut props = vk::FormatProperties2::builder().push_next(&mut full).build(); + unsafe { instance.get_physical_device_format_properties2(gpu.physical(), format, &mut props) }; + list.iter() + .filter(|m| { + m.drm_format_modifier_tiling_features + .contains(vk::FormatFeatureFlags::TRANSFER_DST) + }) + .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) }; +} + +/// 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( + gpu: &Gpu, + lane: &Lane, + src: vk::Image, + format: vk::Format, + (x, y, width, height): (u32, u32, u32, u32), +) -> Result { + check(gpu)?; + let d = gpu.device(); + let modifiers = export_modifiers(gpu, format); + let linear = modifiers.is_empty(); + let mut external = vk::ExternalMemoryImageCreateInfo::builder() + .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .build(); + let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder() + .drm_format_modifiers(&modifiers) + .build(); + let info = vk::ImageCreateInfo::builder() + .image_type(vk::ImageType::_2D) + .format(format) + .extent(vk::Extent3D { + width, + height, + depth: 1, + }) + .mip_levels(1) + .array_layers(1) + .samples(vk::SampleCountFlags::_1) + .tiling(if linear { + vk::ImageTiling::LINEAR + } else { + vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT + }) + .usage(vk::ImageUsageFlags::TRANSFER_DST) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED) + .push_next(&mut external); + let info = if linear { + info.build() + } else { + 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 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, + image, + ( + vk::ImageLayout::UNDEFINED, + vk::PipelineStageFlags2::NONE, + 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, + ); + transfer( + d, + cb, + image, + ( + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_WRITE, + lane.family, + ), + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + QUEUE_FAMILY_FOREIGN, + ), + ); + transfer(d, cb, src, copy_src, decode); + } + lane.end()?; + lane.submit()?; + let fd = export_fd(gpu, memory)?; + let modifier = if linear { + 0 + } else { + let mut props = vk::ImageDrmFormatModifierPropertiesEXT::default(); + unsafe { + vk( + d.get_image_drm_format_modifier_properties_ext(image, &mut props), + "vkGetImageDrmFormatModifierPropertiesEXT", + )? + }; + props.drm_format_modifier + }; + let planes = [ + layout(gpu, image, linear, 0)?, + layout(gpu, image, linear, 1)?, + ]; + Ok((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 export_fd(gpu: &Gpu, memory: vk::DeviceMemory) -> Result { + let info = vk::MemoryGetFdInfoKHR::builder() + .memory(memory) + .handle_type(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .build(); + let fd: c_int = unsafe { + vk( + gpu.device().get_memory_fd_khr(&info), + "vkGetMemoryFdKHR", + )? + }; + Ok(unsafe { OwnedFd::from_raw_fd(fd) }) +} + +fn layout(gpu: &Gpu, image: vk::Image, linear: bool, plane: usize) -> Result { + let aspect = if linear { + [PLANE_0, PLANE_1][plane] + } else { + vk::ImageAspectFlags::from_bits_truncate(MEMORY_PLANES[plane]) + }; + let sub = vk::ImageSubresource { + aspect_mask: aspect, + mip_level: 0, + array_layer: 0, + }; + let l = unsafe { gpu.device().get_image_subresource_layout(image, &sub) }; + Ok(DmaBufPlane { + fd: 0, + offset: l.offset as u32, + pitch: l.row_pitch as u32, + }) +} + +/// Imports an exported picture back on the GPU and reads its NV12 or P010 planes (Y, interleaved UV) into host memory. +pub fn read_dmabuf(gpu: &Gpu, desc: &DmaBufExport) -> Result<(Vec, Vec), Error> { + check(gpu)?; + let d = gpu.device(); + let format = if desc.p010 { + crate::session::P010 + } else { + crate::session::NV12 + }; + let bytes = if desc.p010 { 2 } else { 1 }; + let (w, h) = (desc.width, desc.height); + let layouts = desc.planes.map(|p| vk::SubresourceLayout { + offset: u64::from(p.offset), + size: 0, + row_pitch: u64::from(p.pitch), + array_pitch: 0, + depth_pitch: 0, + }); + let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder() + .drm_format_modifier(desc.modifier) + .plane_layouts(&layouts) + .build(); + let mut external = vk::ExternalMemoryImageCreateInfo::builder() + .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT) + .build(); + let info = vk::ImageCreateInfo::builder() + .image_type(vk::ImageType::_2D) + .format(format) + .extent(vk::Extent3D { + width: w, + height: h, + depth: 1, + }) + .mip_levels(1) + .array_layers(1) + .samples(vk::SampleCountFlags::_1) + .tiling(vk::ImageTiling::DRM_FORMAT_MODIFIER_EXT) + .usage(vk::ImageUsageFlags::TRANSFER_SRC) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .initial_layout(vk::ImageLayout::UNDEFINED) + .push_next(&mut external) + .push_next(&mut explicit) + .build(); + let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? }; + let fds = [desc.fd.as_fd()]; + let src = DmaBuf { + fds: &fds, + planes: &desc.planes, + width: w, + height: h, + modifier: desc.modifier, + format: if desc.p010 { + DmaBufFormat::P010 + } else { + DmaBufFormat::Nv12 + }, + }; + let result = match bind(gpu, image, &src) { + Ok(memories) => { + let out = read_image(gpu, image, (w, h), bytes); + for m in memories { + unsafe { d.free_memory(m, None) }; + } + out + } + Err(e) => Err(e), + }; + unsafe { d.destroy_image(image, None) }; + result +} + +fn read_image( + gpu: &Gpu, + image: vk::Image, + (w, h): (u32, u32), + bytes: u32, +) -> Result<(Vec, Vec), Error> { + let d = gpu.device(); + let luma = w as u64 * h as u64 * u64::from(bytes); + let size = luma * 3 / 2; + let info = vk::BufferCreateInfo::builder() + .size(size) + .usage(vk::BufferUsageFlags::TRANSFER_DST) + .sharing_mode(vk::SharingMode::EXCLUSIVE) + .build(); + let buffer = unsafe { vk(d.create_buffer(&info, None), "vkCreateBuffer")? }; + let req = unsafe { d.get_buffer_memory_requirements(buffer) }; + let flags = vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT; + let index = memory_type(gpu, req.memory_type_bits, flags)?; + let alloc = vk::MemoryAllocateInfo::builder() + .allocation_size(req.size) + .memory_type_index(index) + .build(); + let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? }; + let lane = Lane::new(gpu, gpu.graphics_family().ok_or(Error::NoDevice)?)?; + let out = (|| -> Result<(Vec, Vec), Error> { + unsafe { vk(d.bind_buffer_memory(buffer, memory, 0), "vkBindBufferMemory")? }; + let ptr = unsafe { + vk( + d.map_memory(memory, 0, size, vk::MemoryMapFlags::empty()), + "vkMapMemory", + )? + }; + let copies = [ + crate::session::copy_region(0, PLANE_0, w, h), + crate::session::copy_region(luma, PLANE_1, w / 2, h / 2), + ]; + lane.begin()?; + unsafe { + transfer( + d, + lane.cb, + image, + ( + vk::ImageLayout::GENERAL, + vk::PipelineStageFlags2::NONE, + vk::AccessFlags2::NONE, + QUEUE_FAMILY_FOREIGN, + ), + ( + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + vk::PipelineStageFlags2::COPY, + vk::AccessFlags2::TRANSFER_READ, + lane.family, + ), + ); + d.cmd_copy_image_to_buffer( + lane.cb, + image, + vk::ImageLayout::TRANSFER_SRC_OPTIMAL, + buffer, + &copies, + ); + } + lane.end()?; + lane.submit()?; + let data = unsafe { std::slice::from_raw_parts(ptr as *const u8, size as usize) }; + let split = luma as usize; + let planes = (data[..split].to_vec(), data[split..].to_vec()); + unsafe { d.unmap_memory(memory) }; + Ok(planes) + })(); + unsafe { + d.destroy_buffer(buffer, None); + d.free_memory(memory, None); + } + out +} diff --git a/shims/vk-video-ffi/src/h264_decode.rs b/shims/vk-video-ffi/src/h264_decode.rs index 7fea220b..3b35c8fb 100644 --- a/shims/vk-video-ffi/src/h264_decode.rs +++ b/shims/vk-video-ffi/src/h264_decode.rs @@ -461,6 +461,15 @@ impl H264DecodeSession { self.dec.read_nv12(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), + ) -> Result { + self.dec.export(crop) + } + /// 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, diff --git a/shims/vk-video-ffi/src/h265_decode.rs b/shims/vk-video-ffi/src/h265_decode.rs index 8d44e682..7d5de9ef 100644 --- a/shims/vk-video-ffi/src/h265_decode.rs +++ b/shims/vk-video-ffi/src/h265_decode.rs @@ -698,6 +698,15 @@ impl H265DecodeSession { self.dec.read_nv12(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), + ) -> Result { + self.dec.export(crop) + } + /// 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, diff --git a/shims/vk-video-ffi/src/lib.rs b/shims/vk-video-ffi/src/lib.rs index f7ffcf3c..2e169c43 100644 --- a/shims/vk-video-ffi/src/lib.rs +++ b/shims/vk-video-ffi/src/lib.rs @@ -27,7 +27,7 @@ pub use av1_decode::{ }; pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref}; #[cfg(target_os = "linux")] -pub use dmabuf::{DmaBuf, DmaBufFormat, DmaBufPlane}; +pub use dmabuf::{DmaBuf, DmaBufExport, DmaBufFormat, DmaBufPlane, read_dmabuf}; pub use vp9_decode::{ Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader, Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation, @@ -120,13 +120,32 @@ pub enum Direction { Decode, } -/// Capabilities of one codec and direction, 4:2:0 8-bit. +/// Profile a capability is queried for, 4:2:0 only. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub enum CodecProfile { + /// H.264 High, 8-bit. + H264High, + /// H.265 Main, 8-bit. + H265Main, + /// H.265 Main 10, 10-bit. + H265Main10, + /// AV1 Main, 8-bit. + Av1Main, + /// AV1 Main, 10-bit. + Av1Main10, + /// VP9 Profile 0, 8-bit. + Vp9Profile0, +} + +/// Capabilities of one codec, profile and direction. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub struct CodecCaps { /// Codec. pub codec: Codec, /// Direction. pub direction: Direction, + /// Profile. + pub profile: CodecProfile, /// Maximum coded width. pub max_width: u32, /// Maximum coded height. @@ -324,23 +343,34 @@ impl Gpu { self.inner.graphics } - /// Capabilities of every codec and direction the device supports. + /// Capabilities of every codec, profile and direction the device supports. pub fn caps(&self) -> Vec { [ - (Codec::H264, Direction::Encode), - (Codec::H264, Direction::Decode), - (Codec::H265, Direction::Encode), - (Codec::H265, Direction::Decode), - (Codec::Av1, Direction::Encode), - (Codec::Av1, Direction::Decode), - (Codec::Vp9, Direction::Decode), + (Codec::H264, Direction::Encode, CodecProfile::H264High), + (Codec::H264, Direction::Decode, CodecProfile::H264High), + (Codec::H265, Direction::Encode, CodecProfile::H265Main), + (Codec::H265, Direction::Encode, CodecProfile::H265Main10), + (Codec::H265, Direction::Decode, CodecProfile::H265Main), + (Codec::H265, Direction::Decode, CodecProfile::H265Main10), + (Codec::Av1, Direction::Encode, CodecProfile::Av1Main), + (Codec::Av1, Direction::Encode, CodecProfile::Av1Main10), + (Codec::Av1, Direction::Decode, CodecProfile::Av1Main), + (Codec::Av1, Direction::Decode, CodecProfile::Av1Main10), + (Codec::Vp9, Direction::Decode, CodecProfile::Vp9Profile0), ] .into_iter() - .filter_map(|(codec, direction)| self.codec_caps(codec, direction).ok()) + .filter_map(|(codec, direction, profile)| { + self.codec_caps(codec, direction, profile).ok() + }) .collect() } - fn codec_caps(&self, codec: Codec, direction: Direction) -> Result { + fn codec_caps( + &self, + codec: Codec, + direction: Direction, + profile: CodecProfile, + ) -> Result { let (operation, extension) = match (codec, direction) { (Codec::H264, Direction::Encode) => ( vk::VideoCodecOperationFlagsKHR::ENCODE_H264, @@ -377,21 +407,32 @@ impl Gpu { if !self.inner.device.extensions().contains(&extension.name) { return Err(Error::Unsupported(format!("{codec:?} {direction:?}"))); } - let profile = |operation| { + let depth = match profile { + CodecProfile::H265Main10 | CodecProfile::Av1Main10 => { + vk::VideoComponentBitDepthFlagsKHR::_10 + } + _ => vk::VideoComponentBitDepthFlagsKHR::_8, + }; + let base = |operation| { vk::VideoProfileInfoKHR::builder() .video_codec_operation(operation) .chroma_subsampling(vk::VideoChromaSubsamplingFlagsKHR::_420) - .luma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) - .chroma_bit_depth(vk::VideoComponentBitDepthFlagsKHR::_8) + .luma_bit_depth(depth) + .chroma_bit_depth(depth) + }; + 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 p = profile(operation).push_next(&mut h); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoEncodeH264CapabilitiesKHR::builder(), ) @@ -400,32 +441,33 @@ impl Gpu { let mut h = vk::VideoDecodeH264ProfileInfoKHR::builder() .std_profile_idc(vk::video::STD_VIDEO_H264_PROFILE_IDC_HIGH) .picture_layout(vk::VideoDecodeH264PictureLayoutFlagsKHR::PROGRESSIVE); - let p = profile(operation).push_next(&mut h); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoDecodeH264CapabilitiesKHR::builder(), ) } (Codec::H265, Direction::Encode) => { - let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN); - let p = profile(operation).push_next(&mut h); + let mut h = vk::VideoEncodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoEncodeH265CapabilitiesKHR::builder(), ) } (Codec::H265, Direction::Decode) => { - let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder() - .std_profile_idc(vk::video::STD_VIDEO_H265_PROFILE_IDC_MAIN); - let p = profile(operation).push_next(&mut h); + let mut h = vk::VideoDecodeH265ProfileInfoKHR::builder().std_profile_idc(h265_idc); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoDecodeH265CapabilitiesKHR::builder(), ) @@ -433,10 +475,11 @@ impl Gpu { (Codec::Av1, Direction::Encode) => { let mut h = vk::VideoEncodeAV1ProfileInfoKHR::builder() .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN); - let p = profile(operation).push_next(&mut h); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoEncodeAV1CapabilitiesKHR::builder(), ) @@ -444,10 +487,11 @@ impl Gpu { (Codec::Av1, Direction::Decode) => { let mut h = vk::VideoDecodeAV1ProfileInfoKHR::builder() .std_profile(vk::video::STD_VIDEO_AV1_PROFILE_MAIN); - let p = profile(operation).push_next(&mut h); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoDecodeAV1CapabilitiesKHR::builder(), ) @@ -455,10 +499,11 @@ impl Gpu { (Codec::Vp9, _) => { let mut h = vk::VideoDecodeVP9ProfileInfoKHR::builder() .std_profile(vk::video::STD_VIDEO_VP9_PROFILE_0); - let p = profile(operation).push_next(&mut h); + let p = base(operation).push_next(&mut h); self.query( codec, direction, + profile, &p, &mut vk::VideoDecodeVP9CapabilitiesKHR::builder(), ) @@ -470,6 +515,7 @@ impl Gpu { &self, codec: Codec, direction: Direction, + codec_profile: CodecProfile, profile: &vk::VideoProfileInfoKHR, codec_caps: &mut C, ) -> Result @@ -495,6 +541,7 @@ impl Gpu { Ok(CodecCaps { codec, direction, + profile: codec_profile, max_width: caps.max_coded_extent.width, max_height: caps.max_coded_extent.height, max_dpb_slots: caps.max_dpb_slots, diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 7320de9b..b5de7b75 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -1069,7 +1069,10 @@ impl Encoder { let cb = slot.upload.cb; let (w, h) = (self.input.0 as u32, self.input.1 as u32); let aspects = [PLANE_0, PLANE_1]; - let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)]; + let regions = [ + plane_copy(PLANE_0, (0, 0), (w, h)), + plane_copy(PLANE_1, (0, 0), (w / 2, h / 2)), + ]; slot.upload.begin()?; acquire(d, cb, image, &aspects, slot.upload.family); unsafe { @@ -1554,6 +1557,31 @@ 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. + #[cfg(target_os = "linux")] + pub(crate) fn export( + &mut self, + crop: (u32, u32, u32, u32), + ) -> Result { + 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 + { + return Err(Error::Invalid("DMA-BUF export size".into())); + } + let gpu = self.vs.gpu.clone(); + crate::dmabuf::export(&gpu, &self.graphics, self.output.image, self.vs.format, crop) + } + fn copy_to_buffer( &self, d: &Device, diff --git a/shims/vk-video-ffi/src/vp9_decode.rs b/shims/vk-video-ffi/src/vp9_decode.rs index 77052713..3dee49f2 100644 --- a/shims/vk-video-ffi/src/vp9_decode.rs +++ b/shims/vk-video-ffi/src/vp9_decode.rs @@ -417,6 +417,15 @@ impl Vp9DecodeSession { self.dec.read_nv12(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), + ) -> Result { + self.dec.export(crop) + } + /// 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,