forge
Explore
Log in

Don't you dare go Hollow

ec-hw: export film-grained AV1 pictures as DMA-BUF

Browse files at this commit

3b589359980a58935051ec17dc09f9eb11aadeafAhmet Kaan GümüşParent: 445bf8f
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.rsmodified+2 -0
@@ -127,6 +127,8 @@ fn mixed_cases(dir: &Path) {
127127 let gpu = ec_vk::Gpu::open().expect("Vulkan device");
128128 mixed_case("bf1280.h264", Codec::H264, &h264_units(&h264), false, &gpu);
129129 mixed_case("ten.hevc", Codec::H265, &nal_units(&ten), true, &gpu);
130+ let grain = fs::read(dir.join("grain.ivf")).expect("read grain.ivf");
131+ mixed_case("grain.ivf", Codec::Av1, &ivf_units(&grain), false, &gpu);
130132 }
131133
132134 fn mixed_case(label: &str, codec: Codec, units: &[&[u8]], ten: bool, gpu: &ec_vk::Gpu) {
crates/ec-hw/src/output.rsmodified+69 -10
@@ -16,8 +16,8 @@ use ec_vk::{
1616 use crate::error::{Error, Result};
1717 use crate::hw::{RgbOrder, RgbOutput};
1818 use crate::picture::{
19- Colour, I420, I420_16, RgbPicture, i420_to_rgb, rgb_size, semi_planar_to_i420,
20- semi_planar_to_i420_16, yuv_to_rgb,
19+ Colour, I420, I420_16, RgbPicture, i420_16_to_p010, i420_to_rgb, i420_to_nv12, rgb_size,
20+ semi_planar_to_i420, semi_planar_to_i420_16, yuv_to_rgb,
2121 };
2222 use crate::vkdec_av1::{synthesize, synthesize16};
2323 #[cfg(target_os = "linux")]
@@ -109,7 +109,7 @@ impl HwPicture {
109109 }
110110 }
111111
112- /// One DMA-BUF of NV12 or P010 planes at display size. Not for a picture with film grain.
112+ /// One DMA-BUF of NV12 or P010 planes at display size, with film grain applied when the picture has it.
113113 #[cfg(target_os = "linux")]
114114 pub fn export_dmabuf(&self) -> Result<DmaBufPicture> {
115115 match &self.source {
@@ -232,6 +232,8 @@ pub(crate) struct VkPicture {
232232 bit_depth: u8,
233233 matrix: Matrix,
234234 grain: Option<Grain>,
235+ ring: Option<Rc<RefCell<Ring>>>,
236+ grained: Rc<RefCell<Option<Slot>>>,
235237 }
236238
237239 #[derive(Clone)]
@@ -256,13 +258,21 @@ impl VkPicture {
256258 bit_depth,
257259 matrix,
258260 grain: None,
261+ ring: None,
262+ grained: Rc::new(RefCell::new(None)),
259263 }
260264 }
261265
266+ pub(crate) fn with_ring(mut self, ring: Rc<RefCell<Ring>>) -> VkPicture {
267+ self.ring = Some(ring);
268+ self
269+ }
270+
262271 /// This picture as it is shown with `grain`: unchanged when the frame applies none.
263272 pub(crate) fn with_grain(&self, params: &FilmGrainParams, seq: &SequenceHeader) -> VkPicture {
264273 let mut shown = self.clone();
265274 if params.apply_grain {
275+ shown.grained = Rc::new(RefCell::new(None));
266276 shown.grain = Some(Grain {
267277 params: params.clone(),
268278 seq: seq.clone(),
@@ -336,16 +346,65 @@ impl VkPicture {
336346
337347 #[cfg(target_os = "linux")]
338348 fn export(&self) -> Result<DmaBufPicture> {
339- if self.grain.is_some() {
349+ match &self.grain {
350+ None => Ok(self
351+ .surfaces
352+ .export(self.slot.index, self.width, self.height)?
353+ .into()),
354+ Some(grain) => self.export_grained(grain),
355+ }
356+ }
357+
358+ #[cfg(target_os = "linux")]
359+ fn export_grained(&self, grain: &Grain) -> Result<DmaBufPicture> {
360+ let (Surfaces::Av1(session), Some(ring)) = (&self.surfaces, &self.ring) else {
340361 return Err(Error::unsupported(
341362 "Vulkan DMA-BUF export",
342- "a picture with film grain",
363+ "film grain outside AV1 or without an output ring",
343364 ));
344- }
345- Ok(self
346- .surfaces
347- .export(self.slot.index, self.width, self.height)?
348- .into())
365+ };
366+ let mut grained = self.grained.borrow_mut();
367+ let slot = match grained.take() {
368+ Some(slot) => slot,
369+ None => self.grain_slot(session, ring, grain)?,
370+ };
371+ let export = session.borrow_mut().read_output_dmabuf(
372+ slot.index(),
373+ self.width,
374+ self.height,
375+ );
376+ *grained = Some(slot);
377+ Ok(export?.into())
378+ }
379+
380+ #[cfg(target_os = "linux")]
381+ fn grain_slot(
382+ &self,
383+ session: &Rc<RefCell<Av1DecodeSession>>,
384+ ring: &Rc<RefCell<Ring>>,
385+ grain: &Grain,
386+ ) -> Result<Slot> {
387+ let (width, height) = (self.width, self.height);
388+ let (y, uv) = self.read()?;
389+ let (y, uv) = if self.bit_depth == 8 {
390+ let frame = semi_planar_to_i420(8, &y, &uv, width as usize, (0, 0), (width, height))?;
391+ let frame = synthesize(frame, &grain.params, &grain.seq);
392+ let luma = width as usize * height as usize;
393+ let (mut y, mut uv) = (vec![0; luma], vec![0; luma / 2]);
394+ i420_to_nv12(&frame, &mut y, width as usize, &mut uv, width as usize);
395+ (y, uv)
396+ } else {
397+ let frame =
398+ semi_planar_to_i420_16(self.bit_depth, &y, &uv, width as usize, (0, 0), (width, height))?;
399+ i420_16_to_p010(&synthesize16(frame, &grain.params, &grain.seq))
400+ };
401+ let slot = ring
402+ .borrow_mut()
403+ .take(|| Ok(session.borrow_mut().add_ring_slot()?))?;
404+ session
405+ .borrow_mut()
406+ .upload_output(slot.index(), (width, height), &y, &uv)?;
407+ Ok(slot)
349408 }
350409 }
351410
crates/ec-hw/src/picture.rsmodified+12 -0
@@ -408,6 +408,18 @@ pub(crate) fn check_plane(
408408 }
409409 }
410410
411+pub(crate) fn i420_16_to_p010(src: &I420_16) -> (Vec<u8>, Vec<u8>) {
412+ let le = |v: &u16| (v << 6).to_le_bytes();
413+ let y = src.y.iter().flat_map(le).collect();
414+ let uv = src
415+ .u
416+ .iter()
417+ .zip(&src.v)
418+ .flat_map(|(u, v)| [le(u), le(v)].into_iter().flatten())
419+ .collect();
420+ (y, uv)
421+}
422+
411423 /// Interleave I420 chroma into an NV12 buffer, for the encoder input path.
412424 pub fn i420_to_nv12(
413425 src: &I420,
crates/ec-hw/src/vkdec_av1.rsmodified+8 -4
@@ -28,7 +28,7 @@ const DPB_SLOTS: u32 = NUM_REF_FRAMES as u32 + 1;
2828
2929 struct Session {
3030 av1: Rc<RefCell<Av1DecodeSession>>,
31- ring: Ring,
31+ ring: Rc<RefCell<Ring>>,
3232 bit_depth: u8,
3333 width: u32,
3434 height: u32,
@@ -178,7 +178,10 @@ impl VkAv1Decoder {
178178 if !(header.show_frame || header.refresh_frame_flags != 0) {
179179 return Ok(());
180180 }
181- let slot = session.ring.take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?;
181+ let slot = session
182+ .ring
183+ .borrow_mut()
184+ .take(|| Ok(session.av1.borrow_mut().add_ring_slot()?))?;
182185 session.av1.borrow_mut().store_output(slot.index(), (0, 0, width, height))?;
183186 let codes = Tags::from_codes(u64::from(seq.color_config.matrix_coefficients), 0, 0);
184187 let matrix = ColorDescription::resolve(Tags::default(), codes, height).matrix;
@@ -188,7 +191,8 @@ impl VkAv1Decoder {
188191 (width, height),
189192 session.bit_depth,
190193 matrix,
191- );
194+ )
195+ .with_ring(session.ring.clone());
192196 let state = Av1RefSlot {
193197 slot: setup_slot,
194198 frame_type: av1_frame_type(header.frame_type),
@@ -237,7 +241,7 @@ impl VkAv1Decoder {
237241 let ring = Ring::new(av1.ring_len());
238242 Session {
239243 av1: Rc::new(RefCell::new(av1)),
240- ring,
244+ ring: Rc::new(RefCell::new(ring)),
241245 bit_depth,
242246 width,
243247 height,
shims/vk-video-ffi/src/av1_decode.rsmodified+12 -0
@@ -872,6 +872,18 @@ impl Av1DecodeSession {
872872 self.dec.read_nv12(slot as usize, width, height)
873873 }
874874
875+ /// Writes the top-left width x height NV12 or P010 planes into ring slot `slot`, for its DMA-BUF.
876+ #[cfg(target_os = "linux")]
877+ pub fn upload_output(
878+ &mut self,
879+ slot: u32,
880+ (width, height): (u32, u32),
881+ y: &[u8],
882+ uv: &[u8],
883+ ) -> Result<(), Error> {
884+ self.dec.upload(slot as usize, (width, height), y, uv)
885+ }
886+
875887 /// Exports the crop window `(x, y, width, height)` of the last decoded picture as one DMA-BUF of NV12 or P010 planes.
876888 #[cfg(target_os = "linux")]
877889 pub fn read_output_dmabuf(
shims/vk-video-ffi/src/session.rsmodified+97 -0
@@ -1368,6 +1368,7 @@ pub(crate) struct Decoder {
13681368 pub(crate) output: Image,
13691369 pub(crate) bitstream: Buffer,
13701370 readback: Buffer,
1371+ upload: Option<Buffer>,
13711372 planes: Buffer,
13721373 rgb_out: Buffer,
13731374 rgb: Option<RgbPass>,
@@ -1411,6 +1412,7 @@ impl Decoder {
14111412 output: Default::default(),
14121413 bitstream: Default::default(),
14131414 readback: Default::default(),
1415+ upload: None,
14141416 planes: Default::default(),
14151417 rgb_out: Default::default(),
14161418 rgb: None,
@@ -1832,6 +1834,98 @@ impl Decoder {
18321834 })
18331835 }
18341836
1837+ #[cfg(target_os = "linux")]
1838+ pub(crate) fn upload(
1839+ &mut self,
1840+ slot: usize,
1841+ (width, height): (u32, u32),
1842+ y: &[u8],
1843+ uv: &[u8],
1844+ ) -> Result<(), Error> {
1845+ self.check_size((width, height))?;
1846+ self.flush_store()?;
1847+ let target = self.slot_image(slot)?;
1848+ let bytes = bytes_per_sample(self.vs.format);
1849+ let luma = width as usize * height as usize * bytes;
1850+ if y.len() != luma || uv.len() != luma / 2 {
1851+ return Err(Error::Invalid("upload plane size".into()));
1852+ }
1853+ if self.upload.is_none() {
1854+ let size = self.max_extent.width as u64 * self.max_extent.height as u64 * 3 / 2 * bytes as u64;
1855+ self.upload = Some(self.vs.buffer(
1856+ size,
1857+ vk::BufferUsageFlags::TRANSFER_SRC,
1858+ &[vk::MemoryPropertyFlags::HOST_VISIBLE | vk::MemoryPropertyFlags::HOST_COHERENT],
1859+ None,
1860+ )?);
1861+ }
1862+ let staging = self
1863+ .upload
1864+ .as_ref()
1865+ .ok_or_else(|| Error::Invalid("upload buffer missing".into()))?;
1866+ let ptr = staging
1867+ .ptr
1868+ .ok_or_else(|| Error::Invalid("upload buffer not mapped".into()))?;
1869+ unsafe {
1870+ std::ptr::copy_nonoverlapping(y.as_ptr(), ptr, luma);
1871+ std::ptr::copy_nonoverlapping(uv.as_ptr(), ptr.add(luma), luma / 2);
1872+ }
1873+ let gpu = self.vs.gpu.clone();
1874+ let d = gpu.device();
1875+ let cb = self.graphics.cb;
1876+ let owner = ring_owner(&self.graphics);
1877+ let copies = [
1878+ copy_region(0, PLANE_0, width, height),
1879+ copy_region(luma as u64, PLANE_1, width / 2, height / 2),
1880+ ];
1881+ self.graphics.begin()?;
1882+ unsafe {
1883+ transfer(
1884+ d,
1885+ cb,
1886+ target,
1887+ (
1888+ vk::ImageLayout::GENERAL,
1889+ vk::PipelineStageFlags2::NONE,
1890+ vk::AccessFlags2::NONE,
1891+ EXTERNAL_FAMILY,
1892+ ),
1893+ (
1894+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1895+ vk::PipelineStageFlags2::COPY,
1896+ vk::AccessFlags2::TRANSFER_WRITE,
1897+ owner,
1898+ ),
1899+ );
1900+ d.cmd_copy_buffer_to_image(
1901+ cb,
1902+ staging.buffer,
1903+ target,
1904+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1905+ &copies,
1906+ );
1907+ transfer(
1908+ d,
1909+ cb,
1910+ target,
1911+ (
1912+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1913+ vk::PipelineStageFlags2::COPY,
1914+ vk::AccessFlags2::TRANSFER_WRITE,
1915+ owner,
1916+ ),
1917+ (
1918+ vk::ImageLayout::GENERAL,
1919+ vk::PipelineStageFlags2::NONE,
1920+ vk::AccessFlags2::NONE,
1921+ EXTERNAL_FAMILY,
1922+ ),
1923+ );
1924+ }
1925+ self.graphics.end()?;
1926+ self.graphics.submit()
1927+ }
1928+
18351929 pub(crate) fn ring_len(&self) -> u32 {
18361930 self.ring.len() as u32
18371931 }
@@ -1955,6 +2049,9 @@ impl Drop for Decoder {
19552049 }
19562050 self.bitstream.destroy(d);
19572051 self.readback.destroy(d);
2052+ if let Some(upload) = &self.upload {
2053+ upload.destroy(d);
2054+ }
19582055 self.planes.destroy(d);
19592056 self.rgb_out.destroy(d);
19602057 if let Some(rgb) = &self.rgb {