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 @@
4 use std::os::fd::BorrowedFd;4 use std::os::fd::BorrowedFd;
5 5
6 #[cfg(target_os = "linux")]6 #[cfg(target_os = "linux")]
7-use ec_vk::DmaBuf;7+use ec_vk::{DmaBuf, DmaBufFormat, DmaBufPlane};
8 8
9 use std::cell::RefCell;9 use std::cell::RefCell;
10 10
@@ -219,6 +219,24 @@ pub struct RgbFrame<'a> {
219 pub order: RgbOrder,219 pub order: RgbOrder,
220 }220 }
221 221
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+
222 /// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled.240 /// A single-plane DMA-BUF of packed 32-bit RGB pixels, linear or DRM format modifier tiled.
223 #[cfg(target_os = "linux")]241 #[cfg(target_os = "linux")]
224 #[derive(Debug, Clone, Copy)]242 #[derive(Debug, Clone, Copy)]
@@ -353,22 +371,13 @@ impl VkEncoder {
353 #[cfg(target_os = "linux")]371 #[cfg(target_os = "linux")]
354 fn encode_dmabuf(372 fn encode_dmabuf(
355 &mut self,373 &mut self,
356- frame: &DmaBufFrame,374+ src: &DmaBuf,
357 force_keyframe: bool,375 force_keyframe: bool,
358 ) -> std::result::Result<ec_vk::CodedFrame, ec_vk::Error> {376 ) -> 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- };
368 match self {377 match self {
369- VkEncoder::H264(e) => e.encode_dmabuf(&src, force_keyframe),378+ VkEncoder::H264(e) => e.encode_dmabuf(src, force_keyframe),
370- VkEncoder::H265(e) => e.encode_dmabuf(&src, force_keyframe),379+ VkEncoder::H265(e) => e.encode_dmabuf(src, force_keyframe),
371- VkEncoder::Av1(e) => e.encode_dmabuf(&src, force_keyframe),380+ VkEncoder::Av1(e) => e.encode_dmabuf(src, force_keyframe),
372 }381 }
373 }382 }
374 }383 }
@@ -502,10 +511,50 @@ impl HwEncoder {
502 frame: &DmaBufFrame,511 frame: &DmaBufFrame,
503 meta: FrameMetadata,512 meta: FrameMetadata,
504 ) -> Result<CodedFrame> {513 ) -> 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> {
505 match &mut self.inner {554 match &mut self.inner {
506 EncInner::Vk(enc) => {555 EncInner::Vk(enc) => {
507 vk_session_alive(self.born_epoch)?;556 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)?;
509 Ok(CodedFrame {558 Ok(CodedFrame {
510 data: coded.data,559 data: coded.data,
511 timestamp: meta.timestamp,560 timestamp: meta.timestamp,
crates/ec-hw/src/lib.rsmodified+3 -1
@@ -86,7 +86,9 @@ pub use dec::{Decoder, StreamInfo};
86 pub use enc::Encoder;86 pub use enc::Encoder;
87 pub use error::{Error, Result};87 pub use error::{Error, Result};
88 #[cfg(target_os = "linux")]88 #[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};
90 pub use hw::{92 pub use hw::{
91 Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,93 Backend, Capability, Direction, HwDecoder, HwEncoder, RgbFrame, RgbOrder, RgbOutput,
92 capabilities,94 capabilities,
crates/ec-vk/src/lib.rsmodified+1 -1
@@ -10,7 +10,7 @@ mod h265;
10 pub use av1::{Av1Encoder, Av1EncoderConfig};10 pub use av1::{Av1Encoder, Av1EncoderConfig};
11 pub use h265::{H265Encoder, H265EncoderConfig};11 pub use h265::{H265Encoder, H265EncoderConfig};
12 #[cfg(target_os = "linux")]12 #[cfg(target_os = "linux")]
13-pub use vk_video_ffi::DmaBuf;13+pub use vk_video_ffi::{DmaBuf, DmaBufFormat, DmaBufPlane};
14 pub use vk_video_ffi::{14 pub use vk_video_ffi::{
15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,15 Av1Cdef, Av1ColorConfig, Av1DecodeConfig, Av1DecodePicture, Av1DecodeSession, Av1DeltaParams,
16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,16 Av1FrameHeader, Av1FrameType, Av1GlobalMotion, Av1InterpolationFilter, Av1LoopFilter,
shims/vk-video-ffi/examples/dmabuf_smoke.rsmodified+316 -92
@@ -1,9 +1,9 @@
1 use std::os::fd::{AsFd, FromRawFd, OwnedFd};1 use std::os::fd::{AsFd, FromRawFd, OwnedFd};
2 2
3 use vk_video_ffi::{3 use vk_video_ffi::{
4- Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, Error, Gpu, H264EncodeConfig,4+ Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref, DmaBuf, DmaBufFormat, DmaBufPlane,
5- H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig, H265EncodeSession, H265Picture,5+ Error, Gpu, H264EncodeConfig, H264EncodeSession, H264Picture, H264Ref, H265EncodeConfig,
6- H265Ref, RateControl,6+ H265EncodeSession, H265Picture, H265Ref, RateControl,
7 };7 };
8 use vulkanalia::prelude::v1_3::*;8 use vulkanalia::prelude::v1_3::*;
9 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;9 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
@@ -14,24 +14,74 @@ const FRAMES: usize = 10;
14 const FPS: (u32, u32) = (30, 1);14 const FPS: (u32, u32) = (30, 1);
15 const RATE: RateControl = RateControl::ConstantQp { qp: 28 };15 const RATE: RateControl = RateControl::ConstantQp { qp: 28 };
16 const FORMAT: vk::Format = vk::Format::B8G8R8A8_UNORM;16 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;
17 19
18 struct Export {20 struct Export {
19 image: vk::Image,21 image: vk::Image,
20 memory: vk::DeviceMemory,22 memory: vk::DeviceMemory,
21 fd: OwnedFd,23 fd: OwnedFd,
22 modifier: u64,24 modifier: u64,
23- offset: u32,25+ planes: Vec<DmaBufPlane>,
24- stride: u32,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+ }
25 }74 }
26 75
27 trait Encode: Sized {76 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>;
29 fn rgb(&mut self, host: &[u8], frame: usize) -> Result<Vec<u8>, Error>;78 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>;
30 fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result<Vec<u8>, Error>;80 fn dma(&mut self, src: &DmaBuf, frame: usize) -> Result<Vec<u8>, Error>;
31 }81 }
32 82
33 impl Encode for H264EncodeSession {83 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> {
35 let cfg = H264EncodeConfig {85 let cfg = H264EncodeConfig {
36 width: size.0,86 width: size.0,
37 height: size.1,87 height: size.1,
@@ -43,46 +93,42 @@ impl Encode for H264EncodeSession {
43 }93 }
44 94
45 fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {95 fn rgb(&mut self, host: &[u8], i: usize) -> Result<Vec<u8>, Error> {
46- let pic = H264Picture {96+ let pic = h264_picture(i);
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- };
58 self.encode_rgb(host, W, H, W * 4, true, &pic)97 self.encode_rgb(host, W, H, W * 4, true, &pic)
59 }98 }
60 99
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+
61 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {104 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
62- let pic = H264Picture {105+ self.encode_dmabuf(src, &h264_picture(i))
63- idr: i == 0,106+ }
64- idr_pic_id: 0,107+}
65- frame_num: i as u32,108+
66- poc: 2 * i as i32,109+fn h264_picture(i: usize) -> H264Picture {
67- slot: (i % 2) as u32,110+ H264Picture {
68- reference: (i > 0).then(|| H264Ref {111+ idr: i == 0,
69- slot: ((i - 1) % 2) as u32,112+ idr_pic_id: 0,
70- frame_num: (i - 1) as u32,113+ frame_num: i as u32,
71- poc: 2 * (i - 1) as i32,114+ poc: 2 * i as i32,
72- }),115+ slot: (i % 2) as u32,
73- };116+ reference: (i > 0).then(|| H264Ref {
74- self.encode_dmabuf(src, &pic)117+ slot: ((i - 1) % 2) as u32,
118+ frame_num: (i - 1) as u32,
119+ poc: 2 * (i - 1) as i32,
120+ }),
75 }121 }
76 }122 }
77 123
78 impl Encode for H265EncodeSession {124 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> {
80 let cfg = H265EncodeConfig {126 let cfg = H265EncodeConfig {
81 width: size.0,127 width: size.0,
82 height: size.1,128 height: size.1,
83 fps: FPS,129 fps: FPS,
84 rate: RATE,130 rate: RATE,
85- bit_depth: 8,131+ bit_depth: bits,
86 };132 };
87 H265EncodeSession::new(gpu, &cfg)133 H265EncodeSession::new(gpu, &cfg)
88 }134 }
@@ -92,6 +138,15 @@ impl Encode for H265EncodeSession {
92 self.encode_rgb(host, W, H, W * 4, true, &pic)138 self.encode_rgb(host, W, H, W * 4, true, &pic)
93 }139 }
94 140
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+
95 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {150 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
96 self.encode_dmabuf(src, &h265_picture(i))151 self.encode_dmabuf(src, &h265_picture(i))
97 }152 }
@@ -110,13 +165,13 @@ fn h265_picture(i: usize) -> H265Picture {
110 }165 }
111 166
112 impl Encode for Av1EncodeSession {167 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> {
114 let cfg = Av1EncodeConfig {169 let cfg = Av1EncodeConfig {
115 width: size.0,170 width: size.0,
116 height: size.1,171 height: size.1,
117 fps: FPS,172 fps: FPS,
118 rate: RATE,173 rate: RATE,
119- bit_depth: 8,174+ bit_depth: bits,
120 };175 };
121 Av1EncodeSession::new(gpu, &cfg)176 Av1EncodeSession::new(gpu, &cfg)
122 }177 }
@@ -126,6 +181,15 @@ impl Encode for Av1EncodeSession {
126 self.encode_rgb(host, W, H, W * 4, true, &pic)181 self.encode_rgb(host, W, H, W * 4, true, &pic)
127 }182 }
128 183
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+
129 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {193 fn dma(&mut self, src: &DmaBuf, i: usize) -> Result<Vec<u8>, Error> {
130 self.encode_dmabuf(src, &av1_picture(i))194 self.encode_dmabuf(src, &av1_picture(i))
131 }195 }
@@ -175,12 +239,17 @@ fn memory_index(
175 .expect("memory type")239 .expect("memory type")
176 }240 }
177 241
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> {
179 let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build();248 let mut list = vk::DrmFormatModifierPropertiesListEXT::builder().build();
180 let mut props = vk::FormatProperties2::builder()249 let mut props = vk::FormatProperties2::builder()
181 .push_next(&mut list)250 .push_next(&mut list)
182 .build();251 .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) };
184 let count = list.drm_format_modifier_count as usize;253 let count = list.drm_format_modifier_count as usize;
185 254
186 let mut entries: Vec<vk::DrmFormatModifierPropertiesEXT> = (0..count)255 let mut entries: Vec<vk::DrmFormatModifierPropertiesEXT> = (0..count)
@@ -192,18 +261,17 @@ fn pick_modifier(instance: &Instance, physical: vk::PhysicalDevice) -> u64 {
192 let mut props = vk::FormatProperties2::builder()261 let mut props = vk::FormatProperties2::builder()
193 .push_next(&mut list)262 .push_next(&mut list)
194 .build();263 .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) };
196 265
197 let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST;266 let want = vk::FormatFeatureFlags::TRANSFER_SRC | vk::FormatFeatureFlags::TRANSFER_DST;
198 entries267 entries
199 .iter()268 .iter()
200 .find(|e| {269 .find(|e| {
201 e.drm_format_modifier != 0270 e.drm_format_modifier != 0
202- && e.drm_format_modifier_plane_count == 1271+ && e.drm_format_modifier_plane_count == planes
203 && e.drm_format_modifier_tiling_features.contains(want)272 && e.drm_format_modifier_tiling_features.contains(want)
204 })273 })
205 .map(|e| e.drm_format_modifier)274 .map(|e| e.drm_format_modifier)
206- .expect("tiled single-plane modifier")
207 }275 }
208 276
209 fn export(277 fn export(
@@ -212,8 +280,11 @@ fn export(
212 d: &Device,280 d: &Device,
213 queue: vk::Queue,281 queue: vk::Queue,
214 family: u32,282 family: u32,
283+ format: vk::Format,
215 modifier: u64,284 modifier: u64,
216 host: &[u8],285 host: &[u8],
286+ regions: &[(vk::ImageAspectFlags, u64, u32, u32)],
287+ memory_planes: usize,
217 ) -> Export {288 ) -> Export {
218 let modifiers = [modifier];289 let modifiers = [modifier];
219 let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()290 let mut list = vk::ImageDrmFormatModifierListCreateInfoEXT::builder()
@@ -224,7 +295,7 @@ fn export(
224 .build();295 .build();
225 let info = vk::ImageCreateInfo::builder()296 let info = vk::ImageCreateInfo::builder()
226 .image_type(vk::ImageType::_2D)297 .image_type(vk::ImageType::_2D)
227- .format(FORMAT)298+ .format(format)
228 .extent(vk::Extent3D {299 .extent(vk::Extent3D {
229 width: W,300 width: W,
230 height: H,301 height: H,
@@ -270,12 +341,26 @@ fn export(
270 .build();341 .build();
271 let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd");342 let fd = unsafe { d.get_memory_fd_khr(&fd_info) }.expect("export fd");
272 let fd = unsafe { OwnedFd::from_raw_fd(fd) };343 let fd = unsafe { OwnedFd::from_raw_fd(fd) };
273- let sub = vk::ImageSubresource {344+ let memory_aspects = [
274- aspect_mask: vk::ImageAspectFlags::MEMORY_PLANE_0_EXT,345+ vk::ImageAspectFlags::MEMORY_PLANE_0_EXT,
275- mip_level: 0,346+ vk::ImageAspectFlags::MEMORY_PLANE_1_EXT,
276- array_layer: 0,347+ ];
277- };348+ let planes = memory_aspects[..memory_planes]
278- let layout = unsafe { d.get_image_subresource_layout(image, &sub) };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();
279 364
280 let bytes = host.len() as u64;365 let bytes = host.len() as u64;
281 let buf_info = vk::BufferCreateInfo::builder()366 let buf_info = vk::BufferCreateInfo::builder()
@@ -312,34 +397,44 @@ fn export(
312 .level(vk::CommandBufferLevel::PRIMARY)397 .level(vk::CommandBufferLevel::PRIMARY)
313 .command_buffer_count(1);398 .command_buffer_count(1);
314 let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0];399 let cb = unsafe { d.allocate_command_buffers(&alloc) }.expect("command buffer")[0];
315- let range = vk::ImageSubresourceRange {400+ let to_dst: Vec<vk::ImageMemoryBarrier> = regions
316- aspect_mask: vk::ImageAspectFlags::COLOR,401+ .iter()
317- base_mip_level: 0,402+ .map(|&(aspect, ..)| {
318- level_count: 1,403+ vk::ImageMemoryBarrier::builder()
319- base_array_layer: 0,404+ .old_layout(vk::ImageLayout::UNDEFINED)
320- layer_count: 1,405+ .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)
321- };406+ .src_access_mask(vk::AccessFlags::empty())
322- let to_dst = vk::ImageMemoryBarrier::builder()407+ .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)
323- .old_layout(vk::ImageLayout::UNDEFINED)408+ .image(image)
324- .new_layout(vk::ImageLayout::TRANSFER_DST_OPTIMAL)409+ .subresource_range(vk::ImageSubresourceRange {
325- .src_access_mask(vk::AccessFlags::empty())410+ aspect_mask: aspect,
326- .dst_access_mask(vk::AccessFlags::TRANSFER_WRITE)411+ base_mip_level: 0,
327- .image(image)412+ level_count: 1,
328- .subresource_range(range)413+ base_array_layer: 0,
329- .build();414+ layer_count: 1,
330- let copy = vk::BufferImageCopy::builder()415+ })
331- .image_subresource(vk::ImageSubresourceLayers {416+ .build()
332- aspect_mask: vk::ImageAspectFlags::COLOR,
333- mip_level: 0,
334- base_array_layer: 0,
335- layer_count: 1,
336 })417 })
337- .image_extent(vk::Extent3D {418+ .collect();
338- width: W,419+ let copies: Vec<vk::BufferImageCopy> = regions
339- height: H,420+ .iter()
340- depth: 1,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()
341 })436 })
342- .build();437+ .collect();
343 let begin =438 let begin =
344 vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);439 vk::CommandBufferBeginInfo::builder().flags(vk::CommandBufferUsageFlags::ONE_TIME_SUBMIT);
345 unsafe {440 unsafe {
@@ -351,14 +446,14 @@ fn export(
351 vk::DependencyFlags::empty(),446 vk::DependencyFlags::empty(),
352 &[] as &[vk::MemoryBarrier],447 &[] as &[vk::MemoryBarrier],
353 &[] as &[vk::BufferMemoryBarrier],448 &[] as &[vk::BufferMemoryBarrier],
354- &[to_dst],449+ &to_dst,
355 );450 );
356 d.cmd_copy_buffer_to_image(451 d.cmd_copy_buffer_to_image(
357 cb,452 cb,
358 staging,453 staging,
359 image,454 image,
360 vk::ImageLayout::TRANSFER_DST_OPTIMAL,455 vk::ImageLayout::TRANSFER_DST_OPTIMAL,
361- &[copy],456+ &copies,
362 );457 );
363 d.end_command_buffer(cb).expect("end");458 d.end_command_buffer(cb).expect("end");
364 let cbs = [cb];459 let cbs = [cb];
@@ -376,24 +471,53 @@ fn export(
376 memory,471 memory,
377 fd,472 fd,
378 modifier,473 modifier,
379- offset: layout.offset as u32,474+ planes,
380- stride: layout.row_pitch as u32,
381 }475 }
382 }476 }
383 477
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+
384 fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) {508 fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &Export) {
385 let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))];509 let cases = [(linear, (W, H)), (tiled, (W, H)), (linear, (W / 2, H / 2))];
386 for (export, size) in cases {510 for (export, size) in cases {
387- let mut a = S::open(gpu, size).expect("encoder");511+ let mut a = S::open(gpu, size, 8).expect("encoder");
388- let mut b = S::open(gpu, size).expect("encoder");512+ let mut b = S::open(gpu, size, 8).expect("encoder");
513+ let fds = [export.fd.as_fd()];
389 let src = DmaBuf {514 let src = DmaBuf {
390- fd: export.fd.as_fd(),515+ fds: &fds,
516+ planes: &export.planes,
391 width: W,517 width: W,
392 height: H,518 height: H,
393- stride: export.stride,
394- offset: export.offset,
395 modifier: export.modifier,519 modifier: export.modifier,
396- bgr: true,520+ format: DmaBufFormat::Bgrx,
397 };521 };
398 let mut left = Vec::new();522 let mut left = Vec::new();
399 let mut right = Vec::new();523 let mut right = Vec::new();
@@ -413,6 +537,39 @@ fn run<S: Encode>(gpu: &Gpu, name: &str, host: &[u8], linear: &Export, tiled: &E
413 }537 }
414 }538 }
415 539
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+
416 fn main() {573 fn main() {
417 let gpu = Gpu::open().expect("open GPU");574 let gpu = Gpu::open().expect("open GPU");
418 let (instance, physical, d) = gpu.vulkan();575 let (instance, physical, d) = gpu.vulkan();
@@ -422,16 +579,83 @@ fn main() {
422 .expect("graphics family") as u32;579 .expect("graphics family") as u32;
423 let queue = unsafe { d.get_device_queue(family, 0) };580 let queue = unsafe { d.get_device_queue(family, 0) };
424 let host = gradient();581 let host = gradient();
425- let linear = export(instance, physical, d, queue, family, 0, &host);582+ let rgb_regions = [(vk::ImageAspectFlags::COLOR, 0, W, H)];
426- let modifier = pick_modifier(instance, physical);583+ let linear = export(
427- let tiled = export(instance, physical, d, queue, family, modifier, &host);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+ );
428 run::<H264EncodeSession>(&gpu, "h264", &host, &linear, &tiled);609 run::<H264EncodeSession>(&gpu, "h264", &host, &linear, &tiled);
429 run::<H265EncodeSession>(&gpu, "h265", &host, &linear, &tiled);610 run::<H265EncodeSession>(&gpu, "h265", &host, &linear, &tiled);
430 run::<Av1EncodeSession>(&gpu, "av1", &host, &linear, &tiled);611 run::<Av1EncodeSession>(&gpu, "av1", &host, &linear, &tiled);
431- for e in [linear, tiled] {612+
432- unsafe {613+ let nv12 = Pattern::new(8);
433- d.destroy_image(e.image, None);614+ let p010 = Pattern::new(10);
434- d.free_memory(e.memory, None);615+ let mut exports = vec![linear, tiled];
435- }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);
436 }660 }
437 }661 }
shims/vk-video-ffi/src/av1_encode.rsmodified+7 -1
@@ -275,7 +275,7 @@ impl Av1EncodeSession {
275 })?;275 })?;
276 self.encode_uploaded(pic)276 self.encode_uploaded(pic)
277 }277 }
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.
279 #[cfg(target_os = "linux")]279 #[cfg(target_os = "linux")]
280 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {280 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
281 self.check(pic)?;281 self.check(pic)?;
@@ -283,6 +283,12 @@ impl Av1EncodeSession {
283 self.encode_uploaded(pic)283 self.encode_uploaded(pic)
284 }284 }
285 285
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+
286 fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {292 fn encode_uploaded(&mut self, pic: &Av1Picture) -> Result<Vec<u8>, Error> {
287 let extent = self.enc.extent;293 let extent = self.enc.extent;
288 294
shims/vk-video-ffi/src/dmabuf.rsmodified+342 -40
@@ -1,27 +1,62 @@
1 use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd};1 use std::os::fd::{AsRawFd, BorrowedFd, IntoRawFd};
2+use std::os::unix::fs::MetadataExt;
2 3
3 use vulkanalia::prelude::v1_3::*;4 use vulkanalia::prelude::v1_3::*;
4 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;5 use vulkanalia::vk::KhrExternalMemoryFdExtensionDeviceCommands;
5 6
6-use crate::session::{memory_type, vk};7+use crate::session::{NV12, P010, memory_type, vk};
7 use crate::{Error, Gpu};8 use crate::{Error, Gpu};
8 9
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)]
10 pub struct DmaBuf<'a> {47 pub struct DmaBuf<'a> {
11- /// DMA-BUF file descriptor, duplicated on import.48+ /// DMA-BUF descriptors, duplicated on import.
12- pub fd: BorrowedFd<'a>,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],
13 /// Width in pixels.52 /// Width in pixels.
14 pub width: u32,53 pub width: u32,
15 /// Height in pixels.54 /// Height in pixels.
16 pub height: u32,55 pub height: u32,
17- /// Row pitch in bytes.
18- pub stride: u32,
19- /// Byte offset of the plane.
20- pub offset: u32,
21 /// DRM format modifier.56 /// DRM format modifier.
22 pub modifier: u64,57 pub modifier: u64,
23- /// BGRx byte order when true, RGBx otherwise.58+ /// Pixel format.
24- pub bgr: bool,59+ pub format: DmaBufFormat,
25 }60 }
26 61
27 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {62 pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
@@ -39,35 +74,184 @@ pub(crate) fn check(gpu: &Gpu) -> Result<(), Error> {
39 }74 }
40 }75 }
41 76
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+
42 pub(crate) struct Import {214 pub(crate) struct Import {
43 pub(crate) image: vk::Image,215 pub(crate) image: vk::Image,
44- memory: vk::DeviceMemory,216+ memories: Vec<vk::DeviceMemory>,
45 }217 }
46 218
47 impl Import {219 impl Import {
48- pub(crate) fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {220+ fn new(gpu: &Gpu, src: &DmaBuf) -> Result<Self, Error> {
49 check(gpu)?;221 check(gpu)?;
222+ validate(src)?;
50 let d = gpu.device();223 let d = gpu.device();
51- let format = if src.bgr {224+ let format = match src.format {
52- vk::Format::B8G8R8A8_UNORM225+ DmaBufFormat::Bgrx => vk::Format::B8G8R8A8_UNORM,
53- } else {226+ DmaBufFormat::Rgbx => vk::Format::R8G8B8A8_UNORM,
54- vk::Format::R8G8B8A8_UNORM227+ DmaBufFormat::Nv12 => NV12,
228+ DmaBufFormat::P010 => P010,
55 };229 };
56- let planes = [vk::SubresourceLayout {230+ let layouts: Vec<vk::SubresourceLayout> = src
57- offset: src.offset as u64,231+ .planes
58- size: 0,232+ .iter()
59- row_pitch: src.stride as u64,233+ .map(|p| vk::SubresourceLayout {
60- array_pitch: 0,234+ offset: p.offset as u64,
61- depth_pitch: 0,235+ size: 0,
62- }];236+ row_pitch: p.pitch as u64,
237+ array_pitch: 0,
238+ depth_pitch: 0,
239+ })
240+ .collect();
63 let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder()241 let mut explicit = vk::ImageDrmFormatModifierExplicitCreateInfoEXT::builder()
64 .drm_format_modifier(src.modifier)242 .drm_format_modifier(src.modifier)
65- .plane_layouts(&planes)243+ .plane_layouts(&layouts)
66 .build();244 .build();
67 let mut external = vk::ExternalMemoryImageCreateInfo::builder()245 let mut external = vk::ExternalMemoryImageCreateInfo::builder()
68 .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)246 .handle_types(vk::ExternalMemoryHandleTypeFlags::DMA_BUF_EXT)
69 .build();247 .build();
248+ let flags = if src.fds.len() == 2 {
249+ vk::ImageCreateFlags::DISJOINT
250+ } else {
251+ vk::ImageCreateFlags::empty()
252+ };
70 let info = vk::ImageCreateInfo::builder()253 let info = vk::ImageCreateInfo::builder()
254+ .flags(flags)
71 .image_type(vk::ImageType::_2D)255 .image_type(vk::ImageType::_2D)
72 .format(format)256 .format(format)
73 .extent(vk::Extent3D {257 .extent(vk::Extent3D {
@@ -86,8 +270,8 @@ impl Import {
86 .push_next(&mut explicit)270 .push_next(&mut explicit)
87 .build();271 .build();
88 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };272 let image = unsafe { vk(d.create_image(&info, None), "vkCreateImage")? };
89- match bind(gpu, image, src.fd) {273+ match bind(gpu, image, src) {
90- Ok(memory) => Ok(Import { image, memory }),274+ Ok(memories) => Ok(Import { image, memories }),
91 Err(e) => {275 Err(e) => {
92 unsafe { d.destroy_image(image, None) };276 unsafe { d.destroy_image(image, None) };
93 Err(e)277 Err(e)
@@ -95,17 +279,76 @@ impl Import {
95 }279 }
96 }280 }
97 281
98- pub(crate) fn destroy(&self, d: &Device) {282+ fn destroy(&self, d: &Device) {
99 unsafe {283 unsafe {
100 d.destroy_image(self.image, None);284 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+ }
102 }288 }
103 }289 }
104 }290 }
105 291
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> {
107 let d = gpu.device();336 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+ };
109 let owned = fd352 let owned = fd
110 .try_clone_to_owned()353 .try_clone_to_owned()
111 .map_err(|_| Error::Invalid("DMA-BUF descriptor".into()))?;354 .map_err(|_| Error::Invalid("DMA-BUF descriptor".into()))?;
@@ -132,17 +375,76 @@ fn bind(gpu: &Gpu, image: vk::Image, fd: BorrowedFd) -> Result<vk::DeviceMemory,
132 let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()375 let mut dedicated = vk::MemoryDedicatedAllocateInfo::builder()
133 .image(image)376 .image(image)
134 .build();377 .build();
135- let alloc = vk::MemoryAllocateInfo::builder()378+ let alloc = if plane.is_some() {
136- .allocation_size(req.size)379+ vk::MemoryAllocateInfo::builder()
137- .memory_type_index(index)380+ .allocation_size(req.size)
138- .push_next(&mut dedicated)381+ .memory_type_index(index)
139- .push_next(&mut import)382+ .push_next(&mut import)
140- .build();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+ };
141 let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };392 let memory = unsafe { vk(d.allocate_memory(&alloc, None), "vkAllocateMemory")? };
142 let _ = owned.into_raw_fd();393 let _ = owned.into_raw_fd();
143- let bound = unsafe { vk(d.bind_image_memory(image, memory, 0), "vkBindImageMemory") };394+ Ok(memory)
144- if bound.is_err() {395+}
145- unsafe { d.free_memory(memory, None) };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);
146 }448 }
147- bound.map(|_| memory)449+ Ok(memories)
148 }450 }
shims/vk-video-ffi/src/h264_encode.rsmodified+7 -1
@@ -287,7 +287,7 @@ impl H264EncodeSession {
287 self.encode_uploaded(pic)287 self.encode_uploaded(pic)
288 }288 }
289 289
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.
291 #[cfg(target_os = "linux")]291 #[cfg(target_os = "linux")]
292 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {292 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H264Picture) -> Result<Vec<u8>, Error> {
293 self.check(pic)?;293 self.check(pic)?;
@@ -295,6 +295,12 @@ impl H264EncodeSession {
295 self.encode_uploaded(pic)295 self.encode_uploaded(pic)
296 }296 }
297 297
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+
298 fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {304 fn encode_uploaded(&mut self, pic: &H264Picture) -> Result<Vec<u8>, Error> {
299 let extent = self.enc.extent;305 let extent = self.enc.extent;
300 306
shims/vk-video-ffi/src/h265_encode.rsmodified+7 -1
@@ -315,7 +315,7 @@ impl H265EncodeSession {
315 self.encode_uploaded(pic)315 self.encode_uploaded(pic)
316 }316 }
317 317
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.
319 #[cfg(target_os = "linux")]319 #[cfg(target_os = "linux")]
320 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {320 pub fn encode_dmabuf(&mut self, src: &DmaBuf<'_>, pic: &H265Picture) -> Result<Vec<u8>, Error> {
321 self.check(pic)?;321 self.check(pic)?;
@@ -323,6 +323,12 @@ impl H265EncodeSession {
323 self.encode_uploaded(pic)323 self.encode_uploaded(pic)
324 }324 }
325 325
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+
326 fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {332 fn encode_uploaded(&mut self, pic: &H265Picture) -> Result<Vec<u8>, Error> {
327 let extent = self.enc.extent;333 let extent = self.enc.extent;
328 334
shims/vk-video-ffi/src/lib.rsmodified+1 -1
@@ -27,7 +27,7 @@ pub use av1_decode::{
27 };27 };
28 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};28 pub use av1_encode::{Av1EncodeConfig, Av1EncodeSession, Av1Picture, Av1Ref};
29 #[cfg(target_os = "linux")]29 #[cfg(target_os = "linux")]
30-pub use dmabuf::DmaBuf;30+pub use dmabuf::{DmaBuf, DmaBufFormat, DmaBufPlane};
31 pub use vp9_decode::{31 pub use vp9_decode::{
32 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,32 Vp9ColorConfig, Vp9DecodeConfig, Vp9DecodePicture, Vp9DecodeSession, Vp9FrameHeader,
33 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,33 Vp9InterpolationFilter, Vp9LoopFilter, Vp9Segmentation,
shims/vk-video-ffi/src/rgb_convert.rsmodified+16 -0
@@ -324,6 +324,22 @@ impl RgbConverter {
324 )324 )
325 };325 };
326 326
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+
327 let written = vk::BufferMemoryBarrier2::builder()343 let written = vk::BufferMemoryBarrier2::builder()
328 .src_stage_mask(vk::PipelineStageFlags2::COPY)344 .src_stage_mask(vk::PipelineStageFlags2::COPY)
329 .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE)345 .src_access_mask(vk::AccessFlags2::TRANSFER_WRITE)
shims/vk-video-ffi/src/session.rsmodified+95 -11
@@ -5,7 +5,7 @@ use vulkanalia::vk::{
5 };5 };
6 6
7 #[cfg(target_os = "linux")]7 #[cfg(target_os = "linux")]
8-use crate::dmabuf::{DmaBuf, Import};8+use crate::dmabuf::{DmaBuf, DmaBufFormat, ImportCache, acquire, plane_copy, release};
9 #[cfg(target_os = "linux")]9 #[cfg(target_os = "linux")]
10 use crate::rgb_convert::check_size;10 use crate::rgb_convert::check_size;
11 use crate::rgb_convert::{Input, RgbConverter};11 use crate::rgb_convert::{Input, RgbConverter};
@@ -703,6 +703,8 @@ pub(crate) struct Encoder {
703 pub(crate) src: Image,703 pub(crate) src: Image,
704 staging: Buffer,704 staging: Buffer,
705 rgb: Option<RgbConverter>,705 rgb: Option<RgbConverter>,
706+ #[cfg(target_os = "linux")]
707+ pub(crate) imports: ImportCache,
706 pub(crate) bitstream: Buffer,708 pub(crate) bitstream: Buffer,
707 query: vk::QueryPool,709 query: vk::QueryPool,
708 }710 }
@@ -736,6 +738,8 @@ impl Encoder {
736 src: Default::default(),738 src: Default::default(),
737 staging: Default::default(),739 staging: Default::default(),
738 rgb: None,740 rgb: None,
741+ #[cfg(target_os = "linux")]
742+ imports: Default::default(),
739 bitstream: Default::default(),743 bitstream: Default::default(),
740 query: Default::default(),744 query: Default::default(),
741 };745 };
@@ -938,18 +942,96 @@ impl Encoder {
938 942
939 #[cfg(target_os = "linux")]943 #[cfg(target_os = "linux")]
940 pub(crate) fn upload_dmabuf(&mut self, src: &DmaBuf) -> Result<(), Error> {944 pub(crate) fn upload_dmabuf(&mut self, src: &DmaBuf) -> Result<(), Error> {
945+ let gpu = self.vs.gpu.clone();
941 let (width, height) = (src.width as usize, src.height as usize);946 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> {
943 let gpu = self.vs.gpu.clone();979 let gpu = self.vs.gpu.clone();
944- let import = Import::new(&gpu, src)?;980+ let d = gpu.device();
945- let result = self.upload(Input::DmaBuf {981+ let cb = self.upload.cb;
946- image: import.image,982+ let (w, h) = (self.input.0 as u32, self.input.1 as u32);
947- width,983+ let aspects = [PLANE_0, PLANE_1];
948- height,984+ let regions = [plane_copy(PLANE_0, w, h), plane_copy(PLANE_1, w / 2, h / 2)];
949- bgr: src.bgr,985+ self.upload.begin()?;
950- });986+ acquire(d, cb, image, &aspects, self.upload.family);
951- import.destroy(gpu.device());987+ unsafe {
952- result988+ 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
953 }1035 }
954 1036
955 /// Records one encode with its rate control chains, submits it and returns the coded bytes.1037 /// Records one encode with its rate control chains, submits it and returns the coded bytes.
@@ -1057,6 +1139,8 @@ impl Drop for Encoder {
1057 for img in self.dpb.iter().chain(std::iter::once(&self.src)) {1139 for img in self.dpb.iter().chain(std::iter::once(&self.src)) {
1058 img.destroy(d);1140 img.destroy(d);
1059 }1141 }
1142+ #[cfg(target_os = "linux")]
1143+ self.imports.destroy(d);
1060 if let Some(rgb) = &self.rgb {1144 if let Some(rgb) = &self.rgb {
1061 rgb.destroy(d);1145 rgb.destroy(d);
1062 }1146 }