forge
Explore
Log in

Don't you dare go Hollow

vk: NV12 and P010 DMA-BUF encode input (1 or 2 objects), per-session import cache

Browse files at this commit

7996a95ea11be826cbf75d789126e030354292d2Ahmet Kaan GümüşParent: a9418fa
DmaBuf now lists fds, planes {fd, offset, pitch}, width, height, modifier
and a DmaBufFormat (Bgrx, Rgbx, Nv12, P010). NV12/P010 import as a
multi-planar DRM modifier image (DISJOINT with one object per plane) and
copy plane by plane into the encoder source. Imports are cached per
session (16 entries, LRU) keyed by fstat dev/inode, layout, modifier,
size and format; dmabuf_imports() reports the import count.

ec-hw gains DmaBufYuvFrame and encode_dmabuf_yuv (Vulkan only). The RGB
DmaBufFrame API is unchanged. dmabuf_smoke covers NV12 (H.264, H.265,
AV1) and P010 (H.265, AV1) byte-identical to host upload, plus the cache
case.
crates/ec-hw/src/hw.rsmodified+64 -15
@@ -4,7 +4,7 @@
44 use std::os::fd::BorrowedFd;
55
66 #[cfg(target_os = "linux")]
7-use ec_vk::DmaBuf;
7+use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane};
88
99 use std::cell::RefCell;
1010
@@ -219,6 +219,24 @@ pub struct RgbFrame<'a> {
219219 pub order: RgbOrder,
220220 }
221221
222+/// A two-plane DMA-BUF of NV12 or P010 pixels, one or two objects (one per plane).
223+#[cfg(target_os = "linux")]
224+#[derive(Debug, Clone, Copy)]
225+pub struct DmaBufYuvFrame<'a> {
226+ /// DMA-BUF file descriptors, duplicated by the encoder.
227+ pub fds: &'a [BorrowedFd<'a>],
228+ /// Y then UV plane.
229+ pub planes: [DmaBufPlane; 2],
230+ /// Width in pixels, even; equal to the encoder width.
231+ pub width: u32,
232+ /// Height in pixels, even; equal to the encoder height.
233+ pub height: u32,
234+ /// DRM format modifier.
235+ pub modifier: u64,
236+ /// NV12 or P010.
237+ pub format: DmaBufFormat,
238+}
239+
222240 /// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled.
223241 #[cfg(target_os = "linux")]
224242 #[derive(Debug, Clone, Copy)]
@@ -353,22 +371,13 @@ impl VkEncoder {
353371 #[cfg(target_os = "linux")]
354372 fn encode_dmabuf(
355373 &mut self,
356- frame: &DmaBufFrame,
374+ src: &DmaBuf,
357375 force_keyframe: bool,
358376 ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {
359- let src = DmaBuf {
360- fd: frame.fd,
361- width: frame.width,
362- height: frame.height,
363- stride: frame.stride,
364- offset: frame.offset,
365- modifier: frame.modifier,
366- bgr: frame.order == RgbOrder::Bgra,
367- };
368377 match self {
369- VkEncoder::H264(e) => e.encode_dmabuf(&src, force_keyframe),
370- VkEncoder::H265(e) => e.encode_dmabuf(&src, force_keyframe),
371- VkEncoder::Av1(e) => e.encode_dmabuf(&src, force_keyframe),
378+ VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe),
379+ VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe),
380+ VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe),
372381 }
373382 }
374383 }
@@ -502,10 +511,50 @@ impl HwEncoder {
502511 frame: &DmaBufFrame,
503512 meta: FrameMetadata,
504513 ) -> Result<CodedFrame> {
514+ let planes = [DmaBufPlane {
515+ fd: 0,
516+ offset: frame.offset,
517+ pitch: frame.stride,
518+ }];
519+ let src = DmaBuf {
520+ fds: std::slice::from_ref(&frame.fd),
521+ planes: &planes,
522+ width: frame.width,
523+ height: frame.height,
524+ modifier: frame.modifier,
525+ format: if frame.order == RgbOrder::Bgra {
526+ DmaBufFormat::Bgrx
527+ } else {
528+ DmaBufFormat::Rgbx
529+ },
530+ };
531+ self.encode_dma(&src, meta)
532+ }
533+
534+ /// Encode one NV12 or P010 DMA-BUF frame of the encoder size. Vulkan only; VA-API has its own PRIME path.
535+ #[cfg(target_os = "linux")]
536+ pub fn encode_dmabuf_yuv(
537+ &mut self,
538+ frame: &DmaBufYuvFrame,
539+ meta: FrameMetadata,
540+ ) -> Result<CodedFrame> {
541+ let src = DmaBuf {
542+ fds: frame.fds,
543+ planes: &frame.planes,
544+ width: frame.width,
545+ height: frame.height,
546+ modifier: frame.modifier,
547+ format: frame.format,
548+ };
549+ self.encode_dma(&src, meta)
550+ }
551+
552+ #[cfg(target_os = "linux")]
553+ fn encode_dma(&mut self, src: &DmaBuf, meta: FrameMetadata) -> Result<CodedFrame> {
505554 match &mut self.inner {
506555 EncInner::Vk(enc) => {
507556 vk_session_alive(self.born_epoch)?;
508- let coded = enc.encode_dmabuf(frame, meta.force_keyframe)?;
557+ let coded = enc.encode_dmabuf(src, meta.force_keyframe)?;
509558 Ok(CodedFrame {
510559 data: coded.data,
511560 timestamp: meta.timestamp,
crates/ec-hw/src/lib.rsmodified+3 -1
@@ -86,7 +86,9 @@ pub use dec::{Decoder, StreamInfo};
8686 pub use enc::Encoder;
8787 pub use error::{Error, Result};
8888 #[cfg(target_os = "linux")]
89-pub use hw::DmaBufFrame;
89+pub use ec_vk::{DmaBufFormat, DmaBufPlane};
90+#[cfg(target_os = "linux")]
91+pub use hw::{DmaBufFrame, DmaBufYuvFrame};
9092 pub use hw::{
9193 Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,
9294 capabilities,
crates/ec-vk/src/lib.rsmodified+1 -1
@@ -10,7 +10,7 @@ mod h265;
1010 pub use av1::{Av1Encoder, Av1EncoderConfig};
1111 pub use h265::{H265Encoder, H265EncoderConfig};
1212 #[cfg(target_os = "linux")]
13-pub use vk_video_ffi::DmaBuf;
13+pub use vk_video_ffi::{DmaBuf, DmaBufFormat, DmaBufPlane};
1414 pub use vk_video_ffi::{
1515 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
1616 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+316 -92
@@ -1,9 +1,9 @@
11 use std::os::fd::{AsFd, FromRawFd, OwnedFd};
22
33 use vk_video_ffi::{
4- Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, Error, Gpu, H264EncodeConfig,
5- H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, H265EncodeSession, H265Picture,
6- H265Ref, RateControl,
4+ Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane,
5+ Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig,
6+ H265EncodeSession, H265Picture, H265Ref, RateControl,
77 };
88 use vulkanalia::prelude::v1_3::*;
99 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
@@ -14,24 +14,74 @@ const FRAMES: usize = 10;
1414 const FPS: (u32, u32) = (30, 1);
1515 const RATE: RateControl = RateControl::ConstantQp { qp: 28 };
1616 const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM;
17+const NV12: vk::Format = vk::Format::G8_B8R8_2PLANE_420_UNORM;
18+const P010: vk::Format = vk::Format::G10X6_B10X6R10X6_2PLANE_420_UNORM_3PACK16;
1719
1820 struct Export {
1921 image: vk::Image,
2022 memory: vk::DeviceMemory,
2123 fd: OwnedFd,
2224 modifier: u64,
23- offset: u32,
24- stride: u32,
25+ planes: Vec<DmaBufPlane>,
26+}
27+
28+impl Export {
29+ fn destroy(&self, d: &Device) {
30+ unsafe {
31+ d.destroy_image(self.image, None);
32+ d.free_memory(self.memory, None);
33+ }
34+ }
35+}
36+
37+struct Pattern {
38+ bits: u8,
39+ y: Vec<u16>,
40+ uv: Vec<u16>,
41+}
42+
43+impl Pattern {
44+ fn new(bits: u8) -> Self {
45+ let max = (1u32 << bits) - 1;
46+ let y = (0..W * H)
47+ .map(|i| {
48+ let (x, row) = (i % W, i / W);
49+ ((x * max / (W - 1) + row * max / (H - 1)) / 2) as u16
50+ })
51+ .collect();
52+ let uv = (0..W * H / 2)
53+ .map(|i| ((i * 7) % (max + 1)) as u16)
54+ .collect();
55+ Pattern { bits, y, uv }
56+ }
57+
58+ fn y8(&self) -> Vec<u8> {
59+ self.y.iter().map(|&v| v as u8).collect()
60+ }
61+
62+ fn uv8(&self) -> Vec<u8> {
63+ self.uv.iter().map(|&v| v as u8).collect()
64+ }
65+
66+ fn device(&self) -> Vec<u8> {
67+ let samples = self.y.iter().chain(&self.uv);
68+ if self.bits == 8 {
69+ samples.map(|&v| v as u8).collect()
70+ } else {
71+ samples.flat_map(|&v| (v << 6).to_le_bytes()).collect()
72+ }
73+ }
2574 }
2675
2776 trait Encode: Sized {
28- fn open(gpu: &Gpu, size: (u32, u32)) -> Result<Self, Error>;
77+ fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error>;
2978 fn rgb(&mut self, host: &[u8], frame: usize) -> Result<Vec<u8>, Error>;
79+ fn planar(&mut self, pattern: &Pattern, frame: usize) -> Result<Vec<u8>, Error>;
3080 fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result<Vec<u8>, Error>;
3181 }
3282
3383 impl Encode for H264EncodeSession {
34- fn open(gpu: &Gpu, size: (u32, u32)) -> Result<Self, Error> {
84+ fn open(gpu: &Gpu, size: (u32, u32), _bits: u8) -> Result<Self, Error> {
3585 let cfg = H264EncodeConfig {
3686 width: size.0,
3787 height: size.1,
@@ -43,46 +93,42 @@ impl Encode for H264EncodeSession {
4393 }
4494
4595 fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {
46- let pic = H264Picture {
47- idr: i == 0,
48- idr_pic_id: 0,
49- frame_num: i as u32,
50- poc: 2 * i as i32,
51- slot: (i % 2) as u32,
52- reference: (i > 0).then(|| H264Ref {
53- slot: ((i - 1) % 2) as u32,
54- frame_num: (i - 1) as u32,
55- poc: 2 * (i - 1) as i32,
56- }),
57- };
96+ let pic = h264_picture(i);
5897 self.encode_rgb(host, W, H, W * 4, true, &pic)
5998 }
6099
100+ fn planar(&mut self, pattern: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
101+ self.encode(&pattern.y8(), &pattern.uv8(), &h264_picture(i))
102+ }
103+
61104 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
62- let pic = H264Picture {
63- idr: i == 0,
64- idr_pic_id: 0,
65- frame_num: i as u32,
66- poc: 2 * i as i32,
67- slot: (i % 2) as u32,
68- reference: (i > 0).then(|| H264Ref {
69- slot: ((i - 1) % 2) as u32,
70- frame_num: (i - 1) as u32,
71- poc: 2 * (i - 1) as i32,
72- }),
73- };
74- self.encode_dmabuf(src, &pic)
105+ self.encode_dmabuf(src, &h264_picture(i))
106+ }
107+}
108+
109+fn h264_picture(i: usize) -> H264Picture {
110+ H264Picture {
111+ idr: i == 0,
112+ idr_pic_id: 0,
113+ frame_num: i as u32,
114+ poc: 2 * i as i32,
115+ slot: (i % 2) as u32,
116+ reference: (i > 0).then(|| H264Ref {
117+ slot: ((i - 1) % 2) as u32,
118+ frame_num: (i - 1) as u32,
119+ poc: 2 * (i - 1) as i32,
120+ }),
75121 }
76122 }
77123
78124 impl Encode for H265EncodeSession {
79- fn open(gpu: &Gpu, size: (u32, u32)) -> Result<Self, Error> {
125+ fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error> {
80126 let cfg = H265EncodeConfig {
81127 width: size.0,
82128 height: size.1,
83129 fps: FPS,
84130 rate: RATE,
85- bit_depth: 8,
131+ bit_depth: bits,
86132 };
87133 H265EncodeSession::new(gpu, &cfg)
88134 }
@@ -92,6 +138,15 @@ impl Encode for H265EncodeSession {
92138 self.encode_rgb(host, W, H, W * 4, true, &pic)
93139 }
94140
141+ fn planar(&mut self, p: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
142+ let pic = h265_picture(i);
143+ if p.bits == 8 {
144+ self.encode(&p.y8(), &p.uv8(), &pic)
145+ } else {
146+ self.encode_16(&p.y, &p.uv, &pic)
147+ }
148+ }
149+
95150 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
96151 self.encode_dmabuf(src, &h265_picture(i))
97152 }
@@ -110,13 +165,13 @@ fn h265_picture(i: usize) -> H265Picture {
110165 }
111166
112167 impl Encode for Av1EncodeSession {
113- fn open(gpu: &Gpu, size: (u32, u32)) -> Result<Self, Error> {
168+ fn open(gpu: &Gpu, size: (u32, u32), bits: u8) -> Result<Self, Error> {
114169 let cfg = Av1EncodeConfig {
115170 width: size.0,
116171 height: size.1,
117172 fps: FPS,
118173 rate: RATE,
119- bit_depth: 8,
174+ bit_depth: bits,
120175 };
121176 Av1EncodeSession::new(gpu, &cfg)
122177 }
@@ -126,6 +181,15 @@ impl Encode for Av1EncodeSession {
126181 self.encode_rgb(host, W, H, W * 4, true, &pic)
127182 }
128183
184+ fn planar(&mut self, p: &Pattern, i: usize) -> Result<Vec<u8>, Error> {
185+ let pic = av1_picture(i);
186+ if p.bits == 8 {
187+ self.encode(&p.y8(), &p.uv8(), &pic)
188+ } else {
189+ self.encode_16(&p.y, &p.uv, &pic)
190+ }
191+ }
192+
129193 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
130194 self.encode_dmabuf(src, &av1_picture(i))
131195 }
@@ -175,12 +239,17 @@ fn memory_index(
175239 .expect("memory type")
176240 }
177241
178-fn pick_modifier(instance: &Instance, physical: vk::PhysicalDevice) -> u64 {
242+fn pick_modifier(
243+ instance: &Instance,
244+ physical: vk::PhysicalDevice,
245+ format: vk::Format,
246+ planes: u32,
247+) -> Option<u64> {
179248 let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build();
180249 let mut props = vk::FormatProperties2::builder()
181250 .push_next(&mut list)
182251 .build();
183- unsafe { instance.get_physical_device_format_properties2(physical, FORMAT, &mut props) };
252+ unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) };
184253 let count = list.drm_format_modifier_count as usize;
185254
186255 let mut entries: Vec<vk::DrmFormatModifierPropertiesEXT> = (0..count)
@@ -192,18 +261,17 @@ fn pick_modifier(instance: &Instance, physical: vk::PhysicalDevice) -> u64 {
192261 let mut props = vk::FormatProperties2::builder()
193262 .push_next(&mut list)
194263 .build();
195- unsafe { instance.get_physical_device_format_properties2(physical, FORMAT, &mut props) };
264+ unsafe { instance.get_physical_device_format_properties2(physical, format, &mut props) };
196265
197266 let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST;
198267 entries
199268 .iter()
200269 .find(|e| {
201270 e.drm_format_modifier != 0
202- && e.drm_format_modifier_plane_count == 1
271+ && e.drm_format_modifier_plane_count == planes
203272 && e.drm_format_modifier_tiling_features.contains(want)
204273 })
205274 .map(|e| e.drm_format_modifier)
206- .expect("tiled single-plane modifier")
207275 }
208276
209277 fn export(
@@ -212,8 +280,11 @@ fn export(
212280 d: &Device,
213281 queue: vk::Queue,
214282 family: u32,
283+ format: vk::Format,
215284 modifier: u64,
216285 host: &[u8],
286+ regions: &[(vk::ImageAspectFlags, u64, u32, u32)],
287+ memory_planes: usize,
217288 ) -> Export {
218289 let modifiers = [modifier];
219290 let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()
@@ -224,7 +295,7 @@ fn export(
224295 .build();
225296 let info = vk::ImageCreateInfo::builder()
226297 .image_type(vk::ImageType::_2D)
227- .format(FORMAT)
298+ .format(format)
228299 .extent(vk::Extent3D {
229300 width: W,
230301 height: H,
@@ -270,12 +341,26 @@ fn export(
270341 .build();
271342 let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd");
272343 let fd = unsafe { OwnedFd::from_raw_fd(fd) };
273- let sub = vk::ImageSubresource {
274- aspect_mask: vk::ImageAspectFlags::MEMORY_PLANE_0_EXT,
275- mip_level: 0,
276- array_layer: 0,
277- };
278- let layout = unsafe { d.get_image_subresource_layout(image, &sub) };
344+ let memory_aspects = [
345+ vk::ImageAspectFlags::MEMORY_PLANE_0_EXT,
346+ vk::ImageAspectFlags::MEMORY_PLANE_1_EXT,
347+ ];
348+ let planes = memory_aspects[..memory_planes]
349+ .iter()
350+ .map(|&aspect_mask| {
351+ let sub = vk::ImageSubresource {
352+ aspect_mask,
353+ mip_level: 0,
354+ array_layer: 0,
355+ };
356+ let layout = unsafe { d.get_image_subresource_layout(image, &sub) };
357+ DmaBufPlane {
358+ fd: 0,
359+ offset: layout.offset as u32,
360+ pitch: layout.row_pitch as u32,
361+ }
362+ })
363+ .collect();
279364
280365 let bytes = host.len() as u64;
281366 let buf_info = vk::BufferCreateInfo::builder()
@@ -312,34 +397,44 @@ fn export(
312397 .level(vk::CommandBufferLevel::PRIMARY)
313398 .command_buffer_count(1);
314399 let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0];
315- let range = vk::ImageSubresourceRange {
316- aspect_mask: vk::ImageAspectFlags::COLOR,
317- base_mip_level: 0,
318- level_count: 1,
319- base_array_layer: 0,
320- layer_count: 1,
321- };
322- let to_dst = vk::ImageMemoryBarrier::builder()
323- .old_layout(vk::ImageLayout::UNDEFINED)
324- .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
325- .src_access_mask(vk::AccessFlags::empty())
326- .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
327- .image(image)
328- .subresource_range(range)
329- .build();
330- let copy = vk::BufferImageCopy::builder()
331- .image_subresource(vk::ImageSubresourceLayers {
332- aspect_mask: vk::ImageAspectFlags::COLOR,
333- mip_level: 0,
334- base_array_layer: 0,
335- layer_count: 1,
400+ let to_dst: Vec<vk::ImageMemoryBarrier> = regions
401+ .iter()
402+ .map(|&(aspect, ..)| {
403+ vk::ImageMemoryBarrier::builder()
404+ .old_layout(vk::ImageLayout::UNDEFINED)
405+ .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
406+ .src_access_mask(vk::AccessFlags::empty())
407+ .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
408+ .image(image)
409+ .subresource_range(vk::ImageSubresourceRange {
410+ aspect_mask: aspect,
411+ base_mip_level: 0,
412+ level_count: 1,
413+ base_array_layer: 0,
414+ layer_count: 1,
415+ })
416+ .build()
336417 })
337- .image_extent(vk::Extent3D {
338- width: W,
339- height: H,
340- depth: 1,
418+ .collect();
419+ let copies: Vec<vk::BufferImageCopy> = regions
420+ .iter()
421+ .map(|&(aspect, offset, width, height)| {
422+ vk::BufferImageCopy::builder()
423+ .buffer_offset(offset)
424+ .image_subresource(vk::ImageSubresourceLayers {
425+ aspect_mask: aspect,
426+ mip_level: 0,
427+ base_array_layer: 0,
428+ layer_count: 1,
429+ })
430+ .image_extent(vk::Extent3D {
431+ width,
432+ height,
433+ depth: 1,
434+ })
435+ .build()
341436 })
342- .build();
437+ .collect();
343438 let begin =
344439 vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
345440 unsafe {
@@ -351,14 +446,14 @@ fn export(
351446 vk::DependencyFlags::empty(),
352447 &[] as &[vk::MemoryBarrier],
353448 &[] as &[vk::BufferMemoryBarrier],
354- &[to_dst],
449+ &to_dst,
355450 );
356451 d.cmd_copy_buffer_to_image(
357452 cb,
358453 staging,
359454 image,
360455 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
361- &[copy],
456+ &copies,
362457 );
363458 d.end_command_buffer(cb).expect("end");
364459 let cbs = [cb];
@@ -376,24 +471,53 @@ fn export(
376471 memory,
377472 fd,
378473 modifier,
379- offset: layout.offset as u32,
380- stride: layout.row_pitch as u32,
474+ planes,
381475 }
382476 }
383477
478+fn export_planar(
479+ instance: &Instance,
480+ physical: vk::PhysicalDevice,
481+ d: &Device,
482+ queue: vk::Queue,
483+ family: u32,
484+ format: vk::Format,
485+ modifier: u64,
486+ pattern: &Pattern,
487+) -> Export {
488+ let bps = if pattern.bits == 8 { 1 } else { 2 };
489+ let luma = (W * H * bps) as u64;
490+ let regions = [
491+ (vk::ImageAspectFlags::PLANE_0, 0, W, H),
492+ (vk::ImageAspectFlags::PLANE_1, luma, W / 2, H / 2),
493+ ];
494+ export(
495+ instance,
496+ physical,
497+ d,
498+ queue,
499+ family,
500+ format,
501+ modifier,
502+ &pattern.device(),
503+ &regions,
504+ 2,
505+ )
506+}
507+
384508 fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) {
385509 let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))];
386510 for (export, size) in cases {
387- let mut a = S::open(gpu, size).expect("encoder");
388- let mut b = S::open(gpu, size).expect("encoder");
511+ let mut a = S::open(gpu, size, 8).expect("encoder");
512+ let mut b = S::open(gpu, size, 8).expect("encoder");
513+ let fds = [export.fd.as_fd()];
389514 let src = DmaBuf {
390- fd: export.fd.as_fd(),
515+ fds: &fds,
516+ planes: &export.planes,
391517 width: W,
392518 height: H,
393- stride: export.stride,
394- offset: export.offset,
395519 modifier: export.modifier,
396- bgr: true,
520+ format: DmaBufFormat::Bgrx,
397521 };
398522 let mut left = Vec::new();
399523 let mut right = Vec::new();
@@ -413,6 +537,39 @@ fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &E
413537 }
414538 }
415539
540+fn run_planar<S: Encode>(gpu: &Gpu, name: &str, pattern: &Pattern, exports: &[&Export]) {
541+ let format = if pattern.bits == 8 {
542+ DmaBufFormat::Nv12
543+ } else {
544+ DmaBufFormat::P010
545+ };
546+ for export in exports {
547+ let mut a = S::open(gpu, (W, H), pattern.bits).expect("encoder");
548+ let mut b = S::open(gpu, (W, H), pattern.bits).expect("encoder");
549+ let fds = [export.fd.as_fd()];
550+ let src = DmaBuf {
551+ fds: &fds,
552+ planes: &export.planes,
553+ width: W,
554+ height: H,
555+ modifier: export.modifier,
556+ format,
557+ };
558+ let mut left = Vec::new();
559+ let mut right = Vec::new();
560+ for i in 0..FRAMES {
561+ left.extend(a.planar(pattern, i).expect("encode"));
562+ right.extend(b.dma(&src, i).expect("encode_dmabuf"));
563+ }
564+ let verdict = if left == right {
565+ "identical"
566+ } else {
567+ "DIFFERENT"
568+ };
569+ println!("{name} {:#x} {W}x{H} {verdict}", export.modifier);
570+ }
571+}
572+
416573 fn main() {
417574 let gpu = Gpu::open().expect("open GPU");
418575 let (instance, physical, d) = gpu.vulkan();
@@ -422,16 +579,83 @@ fn main() {
422579 .expect("graphics family") as u32;
423580 let queue = unsafe { d.get_device_queue(family, 0) };
424581 let host = gradient();
425- let linear = export(instance, physical, d, queue, family, 0, &host);
426- let modifier = pick_modifier(instance, physical);
427- let tiled = export(instance, physical, d, queue, family, modifier, &host);
582+ let rgb_regions = [(vk::ImageAspectFlags::COLOR, 0, W, H)];
583+ let linear = export(
584+ instance,
585+ physical,
586+ d,
587+ queue,
588+ family,
589+ FORMAT,
590+ 0,
591+ &host,
592+ &rgb_regions,
593+ 1,
594+ );
595+ let modifier =
596+ pick_modifier(instance, physical, FORMAT, 1).expect("tiled single-plane modifier");
597+ let tiled = export(
598+ instance,
599+ physical,
600+ d,
601+ queue,
602+ family,
603+ FORMAT,
604+ modifier,
605+ &host,
606+ &rgb_regions,
607+ 1,
608+ );
428609 run::<H264EncodeSession>(&gpu, "h264", &host, &linear, &tiled);
429610 run::<H265EncodeSession>(&gpu, "h265", &host, &linear, &tiled);
430611 run::<Av1EncodeSession>(&gpu, "av1", &host, &linear, &tiled);
431- for e in [linear, tiled] {
432- unsafe {
433- d.destroy_image(e.image, None);
434- d.free_memory(e.memory, None);
435- }
612+
613+ let nv12 = Pattern::new(8);
614+ let p010 = Pattern::new(10);
615+ let mut exports = vec![linear, tiled];
616+ let nv12_linear = export_planar(instance, physical, d, queue, family, NV12, 0, &nv12);
617+ let nv12_tiled = pick_modifier(instance, physical, NV12, 2)
618+ .map(|m| export_planar(instance, physical, d, queue, family, NV12, m, &nv12));
619+ let p010_linear = export_planar(instance, physical, d, queue, family, P010, 0, &p010);
620+ let p010_tiled = pick_modifier(instance, physical, P010, 2)
621+ .map(|m| export_planar(instance, physical, d, queue, family, P010, m, &p010));
622+ let nv12_set: Vec<&Export> = [Some(&nv12_linear), nv12_tiled.as_ref()]
623+ .into_iter()
624+ .flatten()
625+ .collect();
626+ let p010_set: Vec<&Export> = [Some(&p010_linear), p010_tiled.as_ref()]
627+ .into_iter()
628+ .flatten()
629+ .collect();
630+ run_planar::<H264EncodeSession>(&gpu, "h264 nv12", &nv12, &nv12_set);
631+ run_planar::<H265EncodeSession>(&gpu, "h265 nv12", &nv12, &nv12_set);
632+ run_planar::<H265EncodeSession>(&gpu, "h265 p010", &p010, &p010_set);
633+ run_planar::<Av1EncodeSession>(&gpu, "av1 nv12", &nv12, &nv12_set);
634+ run_planar::<Av1EncodeSession>(&gpu, "av1 p010", &p010, &p010_set);
635+
636+ let mut cache = <H265EncodeSession as Encode>::open(&gpu, (W, H), 8).expect("encoder");
637+ let fds = [nv12_linear.fd.as_fd()];
638+ let src = DmaBuf {
639+ fds: &fds,
640+ planes: &nv12_linear.planes,
641+ width: W,
642+ height: H,
643+ modifier: nv12_linear.modifier,
644+ format: DmaBufFormat::Nv12,
645+ };
646+ for i in 0..FRAMES {
647+ cache.dma(&src, i).expect("encode_dmabuf");
648+ }
649+ println!(
650+ "cache h265 nv12 {FRAMES} frames same fd imports {}",
651+ cache.dmabuf_imports()
652+ );
653+
654+ exports.extend(nv12_tiled);
655+ exports.push(nv12_linear);
656+ exports.extend(p010_tiled);
657+ exports.push(p010_linear);
658+ for e in &exports {
659+ e.destroy(d);
436660 }
437661 }
shims/vk-video-ffi/src/av1_encode.rsmodified+7 -1
@@ -275,7 +275,7 @@ impl Av1EncodeSession {
275275 })?;
276276 self.encode_uploaded(pic)
277277 }
278- /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
278+ /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
279279 #[cfg(target_os = "linux")]
280280 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
281281 self.check(pic)?;
@@ -283,6 +283,12 @@ impl Av1EncodeSession {
283283 self.encode_uploaded(pic)
284284 }
285285
286+ /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once.
287+ #[cfg(target_os = "linux")]
288+ pub fn dmabuf_imports(&self) -> usize {
289+ self.enc.import_count()
290+ }
291+
286292 fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
287293 let extent = self.enc.extent;
288294
shims/vk-video-ffi/src/dmabuf.rsmodified+342 -40
@@ -1,27 +1,62 @@
11 use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd};
2+use std::os::unix::fs::MetadataExt;
23
34 use vulkanalia::prelude::v1_3::*;
45 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
56
6-use crate::session::{memory_type, vk};
7+use crate::session::{NV12, P010, memory_type, vk};
78 use crate::{Error, Gpu};
89
9-/// Single-plane 4-bytes-per-pixel DMA-BUF, linear or DRM format modifier tiled.
10+const CACHE_SIZE: usize = 16;
11+
12+/// Pixel format of a DMA-BUF.
13+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14+pub enum DmaBufFormat {
15+ /// 8-bit BGRx, one plane.
16+ Bgrx,
17+ /// 8-bit RGBx, one plane.
18+ Rgbx,
19+ /// 8-bit NV12, planes Y and interleaved UV.
20+ Nv12,
21+ /// 10-bit P010, planes Y and interleaved UV.
22+ P010,
23+}
24+
25+impl DmaBufFormat {
26+ fn planes(self) -> usize {
27+ match self {
28+ DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => 1,
29+ DmaBufFormat::Nv12 | DmaBufFormat::P010 => 2,
30+ }
31+ }
32+}
33+
34+/// One plane: index into `DmaBuf::fds`, byte offset and row pitch.
35+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
36+pub struct DmaBufPlane {
37+ /// Index into `DmaBuf::fds`.
38+ pub fd: usize,
39+ /// Byte offset of the plane.
40+ pub offset: u32,
41+ /// Row pitch in bytes.
42+ pub pitch: u32,
43+}
44+
45+/// DMA-BUF image, linear or DRM format modifier tiled, in one or two objects (two objects need one per plane).
46+#[derive(Debug, Clone, Copy)]
1047 pub struct DmaBuf<'a> {
11- /// DMA-BUF file descriptor, duplicated on import.
12- pub fd: BorrowedFd<'a>,
48+ /// DMA-BUF descriptors, duplicated on import.
49+ pub fds: &'a [BorrowedFd<'a>],
50+ /// Planes in format order: one for RGBx, Y then UV for NV12 and P010.
51+ pub planes: &'a [DmaBufPlane],
1352 /// Width in pixels.
1453 pub width: u32,
1554 /// Height in pixels.
1655 pub height: u32,
17- /// Row pitch in bytes.
18- pub stride: u32,
19- /// Byte offset of the plane.
20- pub offset: u32,
2156 /// DRM format modifier.
2257 pub modifier: u64,
23- /// BGRx byte order when true, RGBx otherwise.
24- pub bgr: bool,
58+ /// Pixel format.
59+ pub format: DmaBufFormat,
2560 }
2661
2762 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
@@ -39,35 +74,184 @@ pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
3974 }
4075 }
4176
77+fn validate(src: &DmaBuf) -> Result<(), Error> {
78+ let objects = src.fds.len();
79+ let ok = (1..=2).contains(&objects)
80+ && src.planes.len() == src.format.planes()
81+ && (objects == 1 || src.planes.len() == 2)
82+ && src
83+ .planes
84+ .iter()
85+ .enumerate()
86+ .all(|(i, p)| p.fd < objects && (objects == 1 || p.fd == i))
87+ && src.width > 0
88+ && src.height > 0;
89+ if ok {
90+ Ok(())
91+ } else {
92+ Err(Error::Invalid("DMA-BUF layout".into()))
93+ }
94+}
95+
96+fn aspect_range(aspect: vk::ImageAspectFlags) -> vk::ImageSubresourceRange {
97+ vk::ImageSubresourceRange {
98+ aspect_mask: aspect,
99+ base_mip_level: 0,
100+ level_count: 1,
101+ base_array_layer: 0,
102+ layer_count: 1,
103+ }
104+}
105+
106+pub(crate) fn plane_copy(aspect: vk::ImageAspectFlags, width: u32, height: u32) -> vk::ImageCopy {
107+ let layers = vk::ImageSubresourceLayers {
108+ aspect_mask: aspect,
109+ mip_level: 0,
110+ base_array_layer: 0,
111+ layer_count: 1,
112+ };
113+ vk::ImageCopy::builder()
114+ .src_subresource(layers)
115+ .src_offset(vk::Offset3D { x: 0, y: 0, z: 0 })
116+ .dst_subresource(layers)
117+ .dst_offset(vk::Offset3D { x: 0, y: 0, z: 0 })
118+ .extent(vk::Extent3D {
119+ width,
120+ height,
121+ depth: 1,
122+ })
123+ .build()
124+}
125+
126+pub(crate) fn acquire(
127+ d: &Device,
128+ cb: vk::CommandBuffer,
129+ image: vk::Image,
130+ aspects: &[vk::ImageAspectFlags],
131+ family: u32,
132+) {
133+ let barriers: Vec<vk::ImageMemoryBarrier2> = aspects
134+ .iter()
135+ .map(|&aspect| {
136+ vk::ImageMemoryBarrier2::builder()
137+ .src_stage_mask(vk::PipelineStageFlags2::NONE)
138+ .src_access_mask(vk::AccessFlags2::NONE)
139+ .dst_stage_mask(vk::PipelineStageFlags2::COPY)
140+ .dst_access_mask(vk::AccessFlags2::TRANSFER_READ)
141+ .old_layout(vk::ImageLayout::GENERAL)
142+ .new_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
143+ .src_queue_family_index(vk::QUEUE_FAMILY_FOREIGN_EXT)
144+ .dst_queue_family_index(family)
145+ .image(image)
146+ .subresource_range(aspect_range(aspect))
147+ .build()
148+ })
149+ .collect();
150+ let dep = vk::DependencyInfo::builder().image_memory_barriers(&barriers);
151+ unsafe { d.cmd_pipeline_barrier2(cb, &dep) };
152+}
153+
154+pub(crate) fn release(
155+ d: &Device,
156+ cb: vk::CommandBuffer,
157+ image: vk::Image,
158+ aspects: &[vk::ImageAspectFlags],
159+) {
160+ let barriers: Vec<vk::ImageMemoryBarrier2> = aspects
161+ .iter()
162+ .map(|&aspect| {
163+ vk::ImageMemoryBarrier2::builder()
164+ .src_stage_mask(vk::PipelineStageFlags2::COPY)
165+ .src_access_mask(vk::AccessFlags2::TRANSFER_READ)
166+ .dst_stage_mask(vk::PipelineStageFlags2::NONE)
167+ .dst_access_mask(vk::AccessFlags2::NONE)
168+ .old_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
169+ .new_layout(vk::ImageLayout::GENERAL)
170+ .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
171+ .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
172+ .image(image)
173+ .subresource_range(aspect_range(aspect))
174+ .build()
175+ })
176+ .collect();
177+ let dep = vk::DependencyInfo::builder().image_memory_barriers(&barriers);
178+ unsafe { d.cmd_pipeline_barrier2(cb, &dep) };
179+}
180+
181+#[derive(PartialEq, Eq)]
182+struct Key {
183+ objects: Vec<(u64, u64)>,
184+ planes: Vec<DmaBufPlane>,
185+ modifier: u64,
186+ width: u32,
187+ height: u32,
188+ format: DmaBufFormat,
189+}
190+
191+impl Key {
192+ fn new(src: &DmaBuf) -> Result<Self, Error> {
193+ let mut objects = Vec::with_capacity(src.fds.len());
194+ for fd in src.fds {
195+ let owned = fd
196+ .try_clone_to_owned()
197+ .map_err(|_| Error::Invalid("DMA-BUF descriptor".into()))?;
198+ let meta = std::fs::File::from(owned)
199+ .metadata()
200+ .map_err(|_| Error::Invalid("DMA-BUF descriptor".into()))?;
201+ objects.push((meta.dev(), meta.ino()));
202+ }
203+ Ok(Key {
204+ objects,
205+ planes: src.planes.to_vec(),
206+ modifier: src.modifier,
207+ width: src.width,
208+ height: src.height,
209+ format: src.format,
210+ })
211+ }
212+}
213+
42214 pub(crate) struct Import {
43215 pub(crate) image: vk::Image,
44- memory: vk::DeviceMemory,
216+ memories: Vec<vk::DeviceMemory>,
45217 }
46218
47219 impl Import {
48- pub(crate) fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {
220+ fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {
49221 check(gpu)?;
222+ validate(src)?;
50223 let d = gpu.device();
51- let format = if src.bgr {
52- vk::Format::B8G8R8A8_UNORM
53- } else {
54- vk::Format::R8G8B8A8_UNORM
224+ let format = match src.format {
225+ DmaBufFormat::Bgrx => vk::Format::B8G8R8A8_UNORM,
226+ DmaBufFormat::Rgbx => vk::Format::R8G8B8A8_UNORM,
227+ DmaBufFormat::Nv12 => NV12,
228+ DmaBufFormat::P010 => P010,
55229 };
56- let planes = [vk::SubresourceLayout {
57- offset: src.offset as u64,
58- size: 0,
59- row_pitch: src.stride as u64,
60- array_pitch: 0,
61- depth_pitch: 0,
62- }];
230+ let layouts: Vec<vk::SubresourceLayout> = src
231+ .planes
232+ .iter()
233+ .map(|p| vk::SubresourceLayout {
234+ offset: p.offset as u64,
235+ size: 0,
236+ row_pitch: p.pitch as u64,
237+ array_pitch: 0,
238+ depth_pitch: 0,
239+ })
240+ .collect();
63241 let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder()
64242 .drm_format_modifier(src.modifier)
65- .plane_layouts(&planes)
243+ .plane_layouts(&layouts)
66244 .build();
67245 let mut external = vk::ExternalMemoryImageCreateInfo::builder()
68246 .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
69247 .build();
248+ let flags = if src.fds.len() == 2 {
249+ vk::ImageCreateFlags::DISJOINT
250+ } else {
251+ vk::ImageCreateFlags::empty()
252+ };
70253 let info = vk::ImageCreateInfo::builder()
254+ .flags(flags)
71255 .image_type(vk::ImageType::_2D)
72256 .format(format)
73257 .extent(vk::Extent3D {
@@ -86,8 +270,8 @@ impl Import {
86270 .push_next(&mut explicit)
87271 .build();
88272 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
89- match bind(gpu, image, src.fd) {
90- Ok(memory) => Ok(Import { image, memory }),
273+ match bind(gpu, image, src) {
274+ Ok(memories) => Ok(Import { image, memories }),
91275 Err(e) => {
92276 unsafe { d.destroy_image(image, None) };
93277 Err(e)
@@ -95,17 +279,76 @@ impl Import {
95279 }
96280 }
97281
98- pub(crate) fn destroy(&self, d: &Device) {
282+ fn destroy(&self, d: &Device) {
99283 unsafe {
100284 d.destroy_image(self.image, None);
101- d.free_memory(self.memory, None);
285+ for m in &self.memories {
286+ d.free_memory(*m, None);
287+ }
102288 }
103289 }
104290 }
105291
106-fn bind(gpu: &Gpu, image: vk::Image, fd: BorrowedFd) -> Result<vk::DeviceMemory, Error> {
292+#[derive(Default)]
293+pub(crate) struct ImportCache {
294+ entries: Vec<(Key, Import)>,
295+ pub(crate) count: usize,
296+}
297+
298+impl ImportCache {
299+ pub(crate) fn get(&mut self, gpu: &Gpu, src: &DmaBuf) -> Result<vk::Image, Error> {
300+ validate(src)?;
301+ let key = Key::new(src)?;
302+ match self.entries.iter().position(|(k, _)| *k == key) {
303+ Some(i) => {
304+ let entry = self.entries.remove(i);
305+ self.entries.push(entry);
306+ }
307+ None => {
308+ if self.entries.len() == CACHE_SIZE {
309+ let (_, old) = self.entries.remove(0);
310+ old.destroy(gpu.device());
311+ }
312+ let import = Import::new(gpu, src)?;
313+ self.count += 1;
314+ self.entries.push((key, import));
315+ }
316+ }
317+ self.entries
318+ .last()
319+ .map(|(_, import)| import.image)
320+ .ok_or_else(|| Error::Invalid("DMA-BUF import cache".into()))
321+ }
322+
323+ pub(crate) fn destroy(&self, d: &Device) {
324+ for (_, import) in &self.entries {
325+ import.destroy(d);
326+ }
327+ }
328+}
329+
330+fn allocate(
331+ gpu: &Gpu,
332+ image: vk::Image,
333+ plane: Option<vk::ImageAspectFlags>,
334+ fd: BorrowedFd,
335+) -> Result<vk::DeviceMemory, Error> {
107336 let d = gpu.device();
108- let req = unsafe { d.get_image_memory_requirements(image) };
337+ let req = match plane {
338+ None => unsafe { d.get_image_memory_requirements(image) },
339+ Some(aspect) => {
340+ let mut plane_info = vk::ImagePlaneMemoryRequirementsInfo::builder()
341+ .plane_aspect(aspect)
342+ .build();
343+ let info = vk::ImageMemoryRequirementsInfo2::builder()
344+ .image(image)
345+ .push_next(&mut plane_info)
346+ .build();
347+ let mut out = vk::MemoryRequirements2::default();
348+ unsafe { d.get_image_memory_requirements2(&info, &mut out) };
349+ out.memory_requirements
350+ }
351+ };
109352 let owned = fd
110353 .try_clone_to_owned()
111354 .map_err(|_| Error::Invalid("DMA-BUF descriptor".into()))?;
@@ -132,17 +375,76 @@ fn bind(gpu: &Gpu, image: vk::Image, fd: BorrowedFd) -> Result<vk::DeviceMemory,
132375 let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
133376 .image(image)
134377 .build();
135- let alloc = vk::MemoryAllocateInfo::builder()
136- .allocation_size(req.size)
137- .memory_type_index(index)
138- .push_next(&mut dedicated)
139- .push_next(&mut import)
140- .build();
378+ let alloc = if plane.is_some() {
379+ vk::MemoryAllocateInfo::builder()
380+ .allocation_size(req.size)
381+ .memory_type_index(index)
382+ .push_next(&mut import)
383+ .build()
384+ } else {
385+ vk::MemoryAllocateInfo::builder()
386+ .allocation_size(req.size)
387+ .memory_type_index(index)
388+ .push_next(&mut dedicated)
389+ .push_next(&mut import)
390+ .build()
391+ };
141392 let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
142393 let _ = owned.into_raw_fd();
143- let bound = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") };
144- if bound.is_err() {
145- unsafe { d.free_memory(memory, None) };
394+ Ok(memory)
395+}
396+
397+fn bind(gpu: &Gpu, image: vk::Image, src: &DmaBuf) -> Result<Vec<vk::DeviceMemory>, Error> {
398+ let d = gpu.device();
399+ let free = |memories: &[vk::DeviceMemory]| {
400+ for m in memories {
401+ unsafe { d.free_memory(*m, None) };
402+ }
403+ };
404+ if src.fds.len() == 1 {
405+ let memory = allocate(gpu, image, None, src.fds[0])?;
406+ let bound = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") };
407+ if let Err(e) = bound {
408+ free(&[memory]);
409+ return Err(e);
410+ }
411+ return Ok(vec![memory]);
412+ }
413+ let aspects = [vk::ImageAspectFlags::PLANE_0, vk::ImageAspectFlags::PLANE_1];
414+ let mut memories = Vec::with_capacity(2);
415+ for (fd, aspect) in src.fds.iter().zip(aspects) {
416+ match allocate(gpu, image, Some(aspect), *fd) {
417+ Ok(memory) => memories.push(memory),
418+ Err(e) => {
419+ free(&memories);
420+ return Err(e);
421+ }
422+ }
423+ }
424+ let mut plane_infos: Vec<vk::BindImagePlaneMemoryInfo> = aspects
425+ .iter()
426+ .map(|&plane_aspect| {
427+ vk::BindImagePlaneMemoryInfo::builder()
428+ .plane_aspect(plane_aspect)
429+ .build()
430+ })
431+ .collect();
432+ let binds: Vec<vk::BindImageMemoryInfo> = memories
433+ .iter()
434+ .zip(plane_infos.iter_mut())
435+ .map(|(memory, info)| {
436+ vk::BindImageMemoryInfo::builder()
437+ .image(image)
438+ .memory(*memory)
439+ .memory_offset(0)
440+ .push_next(info)
441+ .build()
442+ })
443+ .collect();
444+ let bound = unsafe { vk(d.bind_image_memory2(&binds), "vkBindImageMemory2") };
445+ if let Err(e) = bound {
446+ free(&memories);
447+ return Err(e);
146448 }
147- bound.map(|_| memory)
449+ Ok(memories)
148450 }
shims/vk-video-ffi/src/h264_encode.rsmodified+7 -1
@@ -287,7 +287,7 @@ impl H264EncodeSession {
287287 self.encode_uploaded(pic)
288288 }
289289
290- /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
290+ /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 of the encoder size.
291291 #[cfg(target_os = "linux")]
292292 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {
293293 self.check(pic)?;
@@ -295,6 +295,12 @@ impl H264EncodeSession {
295295 self.encode_uploaded(pic)
296296 }
297297
298+ /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once.
299+ #[cfg(target_os = "linux")]
300+ pub fn dmabuf_imports(&self) -> usize {
301+ self.enc.import_count()
302+ }
303+
298304 fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {
299305 let extent = self.enc.extent;
300306
shims/vk-video-ffi/src/h265_encode.rsmodified+7 -1
@@ -315,7 +315,7 @@ impl H265EncodeSession {
315315 self.encode_uploaded(pic)
316316 }
317317
318- /// Encodes one picture from a DMA-BUF of BGRx or RGBx pixels, box-downscaled to the encoder size on the GPU.
318+ /// Encodes one picture from a DMA-BUF: BGRx or RGBx box-downscaled to the encoder size, or NV12 or P010 of the encoder size.
319319 #[cfg(target_os = "linux")]
320320 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {
321321 self.check(pic)?;
@@ -323,6 +323,12 @@ impl H265EncodeSession {
323323 self.encode_uploaded(pic)
324324 }
325325
326+ /// Number of DMA-BUF imports made so far; a buffer re-used by fd is imported once.
327+ #[cfg(target_os = "linux")]
328+ pub fn dmabuf_imports(&self) -> usize {
329+ self.enc.import_count()
330+ }
331+
326332 fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {
327333 let extent = self.enc.extent;
328334
shims/vk-video-ffi/src/lib.rsmodified+1 -1
@@ -27,7 +27,7 @@ pub use av1_decode::{
2727 };
2828 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
2929 #[cfg(target_os = "linux")]
30-pub use dmabuf::DmaBuf;
30+pub use dmabuf::{DmaBuf, DmaBufFormat, DmaBufPlane};
3131 pub use vp9_decode::{
3232 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
3333 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
shims/vk-video-ffi/src/rgb_convert.rsmodified+16 -0
@@ -324,6 +324,22 @@ impl RgbConverter {
324324 )
325325 };
326326
327+ let back = vk::ImageMemoryBarrier2::builder()
328+ .src_stage_mask(vk::PipelineStageFlags2::COPY)
329+ .src_access_mask(vk::AccessFlags2::TRANSFER_READ)
330+ .dst_stage_mask(vk::PipelineStageFlags2::NONE)
331+ .dst_access_mask(vk::AccessFlags2::NONE)
332+ .old_layout(vk::ImageLayout::TRANSFER_SRC_OPTIMAL)
333+ .new_layout(vk::ImageLayout::GENERAL)
334+ .src_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
335+ .dst_queue_family_index(vk::QUEUE_FAMILY_IGNORED)
336+ .image(image)
337+ .subresource_range(color_range())
338+ .build();
339+ let backs = [back];
340+ let dep = vk::DependencyInfo::builder().image_memory_barriers(&backs);
341+ unsafe { d.cmd_pipeline_barrier2(cb, &dep) };
342+
327343 let written = vk::BufferMemoryBarrier2::builder()
328344 .src_stage_mask(vk::PipelineStageFlags2::COPY)
329345 .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE)
shims/vk-video-ffi/src/session.rsmodified+95 -11
@@ -5,7 +5,7 @@ use vulkanalia::vk::{
55 };
66
77 #[cfg(target_os = "linux")]
8-use crate::dmabuf::{DmaBuf, Import};
8+use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, plane_copy, release};
99 #[cfg(target_os = "linux")]
1010 use crate::rgb_convert::check_size;
1111 use crate::rgb_convert::{Input, RgbConverter};
@@ -703,6 +703,8 @@ pub(crate) struct Encoder {
703703 pub(crate) src: Image,
704704 staging: Buffer,
705705 rgb: Option<RgbConverter>,
706+ #[cfg(target_os = "linux")]
707+ pub(crate) imports: ImportCache,
706708 pub(crate) bitstream: Buffer,
707709 query: vk::QueryPool,
708710 }
@@ -736,6 +738,8 @@ impl Encoder {
736738 src: Default::default(),
737739 staging: Default::default(),
738740 rgb: None,
741+ #[cfg(target_os = "linux")]
742+ imports: Default::default(),
739743 bitstream: Default::default(),
740744 query: Default::default(),
741745 };
@@ -938,18 +942,96 @@ impl Encoder {
938942
939943 #[cfg(target_os = "linux")]
940944 pub(crate) fn upload_dmabuf(&mut self, src: &DmaBuf) -> Result<(), Error> {
945+ let gpu = self.vs.gpu.clone();
941946 let (width, height) = (src.width as usize, src.height as usize);
942- check_size(self.input, (width, height))?;
947+ match src.format {
948+ DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => check_size(self.input, (width, height))?,
949+ DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.check_planar(src)?,
950+ }
951+ let image = self.imports.get(&gpu, src)?;
952+ match src.format {
953+ DmaBufFormat::Bgrx | DmaBufFormat::Rgbx => self.upload(Input::DmaBuf {
954+ image,
955+ width,
956+ height,
957+ bgr: src.format == DmaBufFormat::Bgrx,
958+ }),
959+ DmaBufFormat::Nv12 | DmaBufFormat::P010 => self.copy_planes(image),
960+ }
961+ }
962+
963+ #[cfg(target_os = "linux")]
964+ fn check_planar(&self, src: &DmaBuf) -> Result<(), Error> {
965+ let ten_bit = src.format == DmaBufFormat::P010;
966+ if ten_bit != (bytes_per_sample(self.vs.format) == 2) {
967+ return Err(Error::Invalid(
968+ "DMA-BUF bit depth differs from the session".into(),
969+ ));
970+ }
971+ if (src.width as usize, src.height as usize) != self.input {
972+ return Err(Error::Invalid("DMA-BUF size differs from the encoder size".into()));
973+ }
974+ Ok(())
975+ }
976+
977+ #[cfg(target_os = "linux")]
978+ fn copy_planes(&mut self, image: vk::Image) -> Result<(), Error> {
943979 let gpu = self.vs.gpu.clone();
944- let import = Import::new(&gpu, src)?;
945- let result = self.upload(Input::DmaBuf {
946- image: import.image,
947- width,
948- height,
949- bgr: src.bgr,
950- });
951- import.destroy(gpu.device());
952- result
980+ let d = gpu.device();
981+ let cb = self.upload.cb;
982+ let (w, h) = (self.input.0 as u32, self.input.1 as u32);
983+ let aspects = [PLANE_0, PLANE_1];
984+ let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];
985+ self.upload.begin()?;
986+ acquire(d, cb, image, &aspects, self.upload.family);
987+ unsafe {
988+ barrier(
989+ d,
990+ cb,
991+ self.src.image,
992+ (
993+ vk::ImageLayout::UNDEFINED,
994+ vk::PipelineStageFlags2::NONE,
995+ vk::AccessFlags2::NONE,
996+ ),
997+ (
998+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
999+ vk::PipelineStageFlags2::COPY,
1000+ vk::AccessFlags2::TRANSFER_WRITE,
1001+ ),
1002+ );
1003+ d.cmd_copy_image(
1004+ cb,
1005+ image,
1006+ vk::ImageLayout::TRANSFER_SRC_OPTIMAL,
1007+ self.src.image,
1008+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1009+ &regions,
1010+ );
1011+ barrier(
1012+ d,
1013+ cb,
1014+ self.src.image,
1015+ (
1016+ vk::ImageLayout::TRANSFER_DST_OPTIMAL,
1017+ vk::PipelineStageFlags2::COPY,
1018+ vk::AccessFlags2::TRANSFER_WRITE,
1019+ ),
1020+ (
1021+ vk::ImageLayout::VIDEO_ENCODE_SRC_KHR,
1022+ vk::PipelineStageFlags2::ALL_COMMANDS,
1023+ vk::AccessFlags2::NONE,
1024+ ),
1025+ );
1026+ }
1027+ release(d, cb, image, &aspects);
1028+ self.upload.end()?;
1029+ self.upload.submit()
1030+ }
1031+
1032+ #[cfg(target_os = "linux")]
1033+ pub(crate) fn import_count(&self) -> usize {
1034+ self.imports.count
9531035 }
9541036
9551037 /// Records one encode with its rate control chains, submits it and returns the coded bytes.
@@ -1057,6 +1139,8 @@ impl Drop for Encoder {
10571139 for img in self.dpb.iter().chain(std::iter::once(&self.src)) {
10581140 img.destroy(d);
10591141 }
1142+ #[cfg(target_os = "linux")]
1143+ self.imports.destroy(d);
10601144 if let Some(rgb) = &self.rgb {
10611145 rgb.destroy(d);
10621146 }