From 3b589359980a58935051ec17dc09f9eb11aadeaf Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Wed, 25 Nov 2026 19:40:24 +0300 Subject: [PATCH] ec-hw: export film-grained AV1 pictures as DMA-BUF Grain is applied on the CPU on the first export and the grained NV12/P010 goes into a separate exportable ring slot, so the reference slot stays ungrained. The picture holds that slot until it drops. The staging buffer for the upload is created on first use. --- crates/ec-hw/examples/hw_decode.rs | 2 + crates/ec-hw/src/output.rs | 79 +++++++++++++++++++--- crates/ec-hw/src/picture.rs | 12 ++++ crates/ec-hw/src/vkdec_av1.rs | 12 ++-- shims/vk-video-ffi/src/av1_decode.rs | 12 ++++ shims/vk-video-ffi/src/session.rs | 97 ++++++++++++++++++++++++++++ 6 files changed, 200 insertions(+), 14 deletions(-) diff --git a/crates/ec-hw/examples/hw_decode.rs b/crates/ec-hw/examples/hw_decode.rs index a5e27963..7489c0cb 100644 --- a/crates/ec-hw/examples/hw_decode.rs +++ b/crates/ec-hw/examples/hw_decode.rs @@ -127,6 +127,8 @@ fn mixed_cases(dir: &Path) { 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); + let grain = fs::read(dir.join("grain.ivf")).expect("read grain.ivf"); + mixed_case("grain.ivf", Codec::Av1, &ivf_units(&grain), false, &gpu); } fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) { diff --git a/crates/ec-hw/src/output.rs b/crates/ec-hw/src/output.rs index 1374b4af..c285afc7 100644 --- a/crates/ec-hw/src/output.rs +++ b/crates/ec-hw/src/output.rs @@ -16,8 +16,8 @@ use ec_vk::{ 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, + Colour, I420, I420_16, RgbPicture, i420_16_to_p010, i420_to_rgb, i420_to_nv12, rgb_size, + semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb, }; use crate::vkdec_av1::{synthesize, synthesize16}; #[cfg(target_os = "linux")] @@ -109,7 +109,7 @@ impl HwPicture { } } - /// One DMA-BUF of NV12 or P010 planes at display size. Not for a picture with film grain. + /// One DMA-BUF of NV12 or P010 planes at display size, with film grain applied when the picture has it. #[cfg(target_os = "linux")] pub fn export_dmabuf(&self) -> Result { match &self.source { @@ -232,6 +232,8 @@ pub(crate) struct VkPicture { bit_depth: u8, matrix: Matrix, grain: Option, + ring: Option>>, + grained: Rc>>, } #[derive(Clone)] @@ -256,13 +258,21 @@ impl VkPicture { bit_depth, matrix, grain: None, + ring: None, + grained: Rc::new(RefCell::new(None)), } } + pub(crate) fn with_ring(mut self, ring: Rc>) -> VkPicture { + self.ring = Some(ring); + self + } + /// This picture as it is shown with `grain`: unchanged when the frame applies none. pub(crate) fn with_grain(&self, params: &FilmGrainParams, seq: &SequenceHeader) -> VkPicture { let mut shown = self.clone(); if params.apply_grain { + shown.grained = Rc::new(RefCell::new(None)); shown.grain = Some(Grain { params: params.clone(), seq: seq.clone(), @@ -336,16 +346,65 @@ impl VkPicture { #[cfg(target_os = "linux")] fn export(&self) -> Result { - if self.grain.is_some() { + match &self.grain { + None => Ok(self + .surfaces + .export(self.slot.index, self.width, self.height)? + .into()), + Some(grain) => self.export_grained(grain), + } + } + + #[cfg(target_os = "linux")] + fn export_grained(&self, grain: &Grain) -> Result { + let (Surfaces::Av1(session), Some(ring)) = (&self.surfaces, &self.ring) else { return Err(Error::unsupported( "Vulkan DMA-BUF export", - "a picture with film grain", + "film grain outside AV1 or without an output ring", )); - } - Ok(self - .surfaces - .export(self.slot.index, self.width, self.height)? - .into()) + }; + let mut grained = self.grained.borrow_mut(); + let slot = match grained.take() { + Some(slot) => slot, + None => self.grain_slot(session, ring, grain)?, + }; + let export = session.borrow_mut().read_output_dmabuf( + slot.index(), + self.width, + self.height, + ); + *grained = Some(slot); + Ok(export?.into()) + } + + #[cfg(target_os = "linux")] + fn grain_slot( + &self, + session: &Rc>, + ring: &Rc>, + grain: &Grain, + ) -> Result { + let (width, height) = (self.width, self.height); + let (y, uv) = self.read()?; + let (y, uv) = if self.bit_depth == 8 { + let frame = semi_planar_to_i420(8, &y, &uv, width as usize, (0, 0), (width, height))?; + let frame = synthesize(frame, &grain.params, &grain.seq); + let luma = width as usize * height as usize; + let (mut y, mut uv) = (vec![0; luma], vec![0; luma / 2]); + i420_to_nv12(&frame, &mut y, width as usize, &mut uv, width as usize); + (y, uv) + } else { + let frame = + semi_planar_to_i420_16(self.bit_depth, &y, &uv, width as usize, (0, 0), (width, height))?; + i420_16_to_p010(&synthesize16(frame, &grain.params, &grain.seq)) + }; + let slot = ring + .borrow_mut() + .take(|| Ok(session.borrow_mut().add_ring_slot()?))?; + session + .borrow_mut() + .upload_output(slot.index(), (width, height), &y, &uv)?; + Ok(slot) } } diff --git a/crates/ec-hw/src/picture.rs b/crates/ec-hw/src/picture.rs index f8d600dd..c3ceffc4 100644 --- a/crates/ec-hw/src/picture.rs +++ b/crates/ec-hw/src/picture.rs @@ -408,6 +408,18 @@ pub(crate) fn check_plane( } } +pub(crate) fn i420_16_to_p010(src: &I420_16) -> (Vec, Vec) { + let le = |v: &u16| (v << 6).to_le_bytes(); + let y = src.y.iter().flat_map(le).collect(); + let uv = src + .u + .iter() + .zip(&src.v) + .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten()) + .collect(); + (y, uv) +} + /// Interleave I420 chroma into an NV12 buffer, for the encoder input path. pub fn i420_to_nv12( src: &I420, diff --git a/crates/ec-hw/src/vkdec_av1.rs b/crates/ec-hw/src/vkdec_av1.rs index 12c864a0..4482ee9a 100644 --- a/crates/ec-hw/src/vkdec_av1.rs +++ b/crates/ec-hw/src/vkdec_av1.rs @@ -28,7 +28,7 @@ const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1; struct Session { av1: Rc>, - ring: Ring, + ring: Rc>, bit_depth: u8, width: u32, height: u32, @@ -178,7 +178,10 @@ impl VkAv1Decoder { if !(header.show_frame || header.refresh_frame_flags != 0) { return Ok(()); } - let slot = session.ring.take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?; + let slot = session + .ring + .borrow_mut() + .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; @@ -188,7 +191,8 @@ impl VkAv1Decoder { (width, height), session.bit_depth, matrix, - ); + ) + .with_ring(session.ring.clone()); let state = Av1RefSlot { slot: setup_slot, frame_type: av1_frame_type(header.frame_type), @@ -237,7 +241,7 @@ impl VkAv1Decoder { let ring = Ring::new(av1.ring_len()); Session { av1: Rc::new(RefCell::new(av1)), - ring, + ring: Rc::new(RefCell::new(ring)), bit_depth, width, height, diff --git a/shims/vk-video-ffi/src/av1_decode.rs b/shims/vk-video-ffi/src/av1_decode.rs index 7445eac6..cb34f992 100644 --- a/shims/vk-video-ffi/src/av1_decode.rs +++ b/shims/vk-video-ffi/src/av1_decode.rs @@ -872,6 +872,18 @@ impl Av1DecodeSession { self.dec.read_nv12(slot as usize, width, height) } + /// Writes the top-left width x height NV12 or P010 planes into ring slot `slot`, for its DMA-BUF. + #[cfg(target_os = "linux")] + pub fn upload_output( + &mut self, + slot: u32, + (width, height): (u32, u32), + y: &[u8], + uv: &[u8], + ) -> Result<(), Error> { + self.dec.upload(slot as usize, (width, height), y, uv) + } + /// 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( diff --git a/shims/vk-video-ffi/src/session.rs b/shims/vk-video-ffi/src/session.rs index 7df1a819..4b4f162f 100644 --- a/shims/vk-video-ffi/src/session.rs +++ b/shims/vk-video-ffi/src/session.rs @@ -1368,6 +1368,7 @@ pub(crate) struct Decoder { pub(crate) output: Image, pub(crate) bitstream: Buffer, readback: Buffer, + upload: Option, planes: Buffer, rgb_out: Buffer, rgb: Option, @@ -1411,6 +1412,7 @@ impl Decoder { output: Default::default(), bitstream: Default::default(), readback: Default::default(), + upload: None, planes: Default::default(), rgb_out: Default::default(), rgb: None, @@ -1832,6 +1834,98 @@ impl Decoder { }) } + #[cfg(target_os = "linux")] + pub(crate) fn upload( + &mut self, + slot: usize, + (width, height): (u32, u32), + y: &[u8], + uv: &[u8], + ) -> Result<(), Error> { + self.check_size((width, height))?; + self.flush_store()?; + let target = self.slot_image(slot)?; + let bytes = bytes_per_sample(self.vs.format); + let luma = width as usize * height as usize * bytes; + if y.len() != luma || uv.len() != luma / 2 { + return Err(Error::Invalid("upload plane size".into())); + } + if self.upload.is_none() { + let size = self.max_extent.width as u64 * self.max_extent.height as u64 * 3 / 2 * bytes as u64; + self.upload = Some(self.vs.buffer( + size, + vk::BufferUsageFlags::TRANSFER_SRC, + &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT], + None, + )?); + } + let staging = self + .upload + .as_ref() + .ok_or_else(|| Error::Invalid("upload buffer missing".into()))?; + let ptr = staging + .ptr + .ok_or_else(|| Error::Invalid("upload buffer not mapped".into()))?; + unsafe { + std::ptr::copy_nonoverlapping(y.as_ptr(), ptr, luma); + std::ptr::copy_nonoverlapping(uv.as_ptr(), ptr.add(luma), luma / 2); + } + let gpu = self.vs.gpu.clone(); + let d = gpu.device(); + let cb = self.graphics.cb; + let owner = ring_owner(&self.graphics); + let copies = [ + copy_region(0, PLANE_0, width, height), + copy_region(luma as u64, PLANE_1, width / 2, height / 2), + ]; + self.graphics.begin()?; + unsafe { + 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_buffer_to_image( + cb, + staging.buffer, + target, + vk::ImageLayout::TRANSFER_DST_OPTIMAL, + &copies, + ); + 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, + ), + ); + } + self.graphics.end()?; + self.graphics.submit() + } + pub(crate) fn ring_len(&self) -> u32 { self.ring.len() as u32 } @@ -1955,6 +2049,9 @@ impl Drop for Decoder { } self.bitstream.destroy(d); self.readback.destroy(d); + if let Some(upload) = &self.upload { + upload.destroy(d); + } self.planes.destroy(d); self.rgb_out.destroy(d); if let Some(rgb) = &self.rgb {