Skip to main content

moq_video/frame/
vulkan.rs

1//! External Vulkan images and their producer-owned reuse slots.
2//!
3//! A producer exports a dedicated image and timeline semaphore once, then
4//! publishes the slot for each capture. Encoders import it on its declared
5//! device and return the slot only after their GPU reads have completed.
6
7use std::any::{Any, TypeId};
8use std::collections::HashMap;
9use std::fmt;
10use std::os::fd::OwnedFd;
11use std::sync::{Arc, Mutex};
12
13use crate::{Error, Size};
14
15/// The physical device and driver that own an external image.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub struct Device {
18	/// Vulkan physical-device UUID.
19	pub device_uuid: [u8; 16],
20	/// Vulkan driver UUID, required to import opaque Vulkan allocations.
21	pub driver_uuid: [u8; 16],
22	/// Render node `dev_t`, absent when the exporter has no DRM render node.
23	pub render_node: Option<u64>,
24}
25
26impl fmt::Display for Device {
27	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
28		write!(f, "device {} driver {}", uuid(self.device_uuid), uuid(self.driver_uuid))
29	}
30}
31
32/// One DRM modifier memory plane's allocation offset and row pitch.
33#[derive(Clone, Copy, Debug, PartialEq, Eq)]
34pub struct Plane {
35	/// Byte offset from the start of the exported allocation.
36	pub offset: u64,
37	/// Byte pitch reported by the producer, including any row padding.
38	pub row_pitch: u64,
39}
40
41/// The memory handle's import contract.
42#[derive(Clone, Debug, PartialEq, Eq)]
43pub enum Memory {
44	/// Dedicated optimal-tiling memory, imported with the exporter's memory type.
45	OpaqueFd {
46		/// Vulkan memory type index used for the original allocation.
47		memory_type: u32,
48	},
49	/// A DMA-BUF image, imported with its DRM format modifier.
50	DmaBuf {
51		/// DRM format modifier describing the allocation's tiling.
52		modifier: u64,
53		/// Explicit memory-plane layouts, in the DRM modifier's plane order.
54		/// Importers check the plane count against the modifier's properties.
55		planes: Vec<Plane>,
56	},
57}
58
59/// The Vulkan handles exported for one reusable image slot.
60pub struct Handles {
61	/// Memory exported with the handle type declared by [`Image::memory`].
62	pub memory: OwnedFd,
63	/// An `OPAQUE_FD` timeline semaphore.
64	pub timeline: OwnedFd,
65}
66
67impl Handles {
68	#[cfg_attr(
69		not(feature = "nvidia"),
70		allow(dead_code, reason = "only the `nvidia` feature uses it")
71	)]
72	fn try_clone(&self) -> Result<Self, Error> {
73		Ok(Self {
74			memory: self.memory.try_clone().map_err(|e| Error::codec(e.into()))?,
75			timeline: self.timeline.try_clone().map_err(|e| Error::codec(e.into()))?,
76		})
77	}
78}
79
80/// The Vulkan format of an image's packed pixels.
81#[derive(Clone, Copy, Debug, PartialEq, Eq)]
82pub enum Format {
83	/// `VK_FORMAT_R8G8B8A8_UNORM`.
84	Rgba8,
85	/// `VK_FORMAT_B8G8R8A8_UNORM`.
86	Bgra8,
87}
88
89/// An external dedicated Vulkan image, in `GENERAL` layout while being read.
90///
91/// The producer creates a 2D image with one mip, one array layer, one sample,
92/// no create flags, exclusive sharing, and usage `TRANSFER_DST | SAMPLED |
93/// STORAGE`. It binds dedicated memory at offset zero. `OpaqueFd` images use
94/// optimal tiling; `DmaBuf` images use DRM modifier tiling with explicit memory
95/// planes. [`Format`] names the exact UNORM format. Importers recreate
96/// this contract, including usage, rather than infer image creation parameters.
97#[derive(Clone, Debug, PartialEq, Eq)]
98pub struct Image {
99	/// Device and driver that allocated the image.
100	pub device: Device,
101	/// Memory handle type and its import parameters.
102	pub memory: Memory,
103	/// Visible image size.
104	pub size: Size,
105	/// Complete allocation size, rather than the number of visible pixel bytes.
106	pub allocation_size: u64,
107	/// Packed pixel format.
108	pub format: Format,
109}
110
111impl Image {
112	fn validate(&self) -> Result<(), Error> {
113		self.size.validate_nonzero("external Vulkan image")?;
114		if self.allocation_size == 0 {
115			return Err(Error::Unsupported(
116				"external Vulkan allocation size must be non-zero".into(),
117			));
118		}
119		match &self.memory {
120			Memory::OpaqueFd { memory_type } if *memory_type >= 32 => {
121				return Err(Error::Unsupported("Vulkan memory type index must be below 32".into()));
122			}
123			Memory::DmaBuf { planes, .. }
124				if (planes.is_empty()
125					|| planes.len() > 4
126					|| planes
127						.iter()
128						.any(|plane| plane.row_pitch == 0 || plane.offset >= self.allocation_size)) =>
129			{
130				return Err(Error::Unsupported("Vulkan DMA-BUF requires one to four explicit memory planes with non-zero row pitches and offsets within its allocation".into()));
131			}
132			_ => {}
133		}
134		Ok(())
135	}
136}
137
138/// Monotonic values for one producer-to-consumer-to-producer handoff.
139#[derive(Clone, Copy, Debug, PartialEq, Eq)]
140pub struct Timeline {
141	/// Value the producer signals after finishing writes and the layout transition.
142	pub ready: u64,
143	/// Value the consumer signals after the last GPU reader finishes.
144	pub complete: u64,
145}
146
147impl Timeline {
148	/// Create one handoff with a completion value greater than its ready value.
149	pub fn new(ready: u64, complete: u64) -> Result<Self, Error> {
150		if complete <= ready {
151			return Err(Error::Unsupported(format!(
152				"Vulkan completion value {complete} must exceed ready value {ready}"
153			)));
154		}
155		Ok(Self { ready, complete })
156	}
157}
158
159#[cfg_attr(
160	not(feature = "nvidia"),
161	allow(dead_code, reason = "only the `nvidia` feature uses it")
162)]
163struct Allocation {
164	handles: Handles,
165	image: Image,
166	// Imports belong to a slot, not to an FD that can be duplicated or reused.
167	imports: Mutex<HashMap<TypeId, Arc<dyn Any + Send + Sync>>>,
168}
169
170/// One external Vulkan allocation and the producer value that keeps it alive.
171pub struct Slot<T: Send + Sync + 'static> {
172	allocation: Arc<Allocation>,
173	owner: T,
174	last_complete: u64,
175}
176
177impl<T: Send + Sync + 'static> fmt::Debug for Slot<T> {
178	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
179		f.debug_struct("Slot")
180			.field("image", &self.allocation.image)
181			.field("last_complete", &self.last_complete)
182			.finish_non_exhaustive()
183	}
184}
185
186impl<T: Send + Sync + 'static> Slot<T> {
187	/// Own exported handles and retain their producer without opening a backend.
188	///
189	/// The producer guard must keep the Vulkan image, memory, and semaphore alive
190	/// and safely finish or cancel its own queued writes before destroying them.
191	/// An unread frame has no imported backend through which to wait for those
192	/// writes, so its failed completion releases the guard for producer teardown.
193	pub fn new(handles: Handles, image: Image, owner: T) -> Result<Self, Error> {
194		image.validate()?;
195		Ok(Self {
196			allocation: Arc::new(Allocation {
197				handles,
198				image,
199				imports: Mutex::new(HashMap::new()),
200			}),
201			owner,
202			last_complete: 0,
203		})
204	}
205
206	/// Access the producer-owned value while the slot is idle.
207	pub fn owner(&self) -> &T {
208		&self.owner
209	}
210
211	/// Mutate the producer-owned value while the slot is idle.
212	pub fn owner_mut(&mut self) -> &mut T {
213		&mut self.owner
214	}
215
216	/// Publish after queueing the ready signal, returning a completion handle.
217	///
218	/// Publish only what you will encode. A frame that no backend reads (one a
219	/// publisher drops under backpressure, say) fails completion and loses its
220	/// slot for good: no consumer signalled its timeline, so the producer must
221	/// export a new slot to replace it. Drop excess captures before publishing
222	/// instead. The guard must safely finish or cancel queued producer writes
223	/// before teardown, as required by [`Slot::new`].
224	pub fn publish(self, timeline: Timeline) -> Result<(Frame, Completion<T>), PublishError<T>> {
225		if timeline.complete <= timeline.ready || timeline.ready <= self.last_complete {
226			return Err(PublishError::new(
227				Error::Unsupported(format!(
228					"invalid Vulkan handoff {timeline:?} after completion {}",
229					self.last_complete
230				)),
231				self,
232			));
233		}
234		let (sender, receiver) = tokio::sync::oneshot::channel();
235		let allocation = self.allocation.clone();
236		let completion: Box<dyn Complete> = Box::new(ReturnSlot {
237			slot: Slot {
238				last_complete: timeline.complete,
239				..self
240			},
241			sender,
242		});
243		Ok((
244			Frame {
245				inner: Arc::new(FrameInner {
246					allocation,
247					timeline,
248					reader: Mutex::new(None),
249					completion: Some(completion),
250					#[cfg(feature = "nvidia")]
251					converted: Mutex::new(Vec::new()),
252				}),
253			},
254			Completion { receiver },
255		))
256	}
257}
258
259/// A published external image, retained until every consumer drops its clone.
260#[derive(Clone)]
261pub struct Frame {
262	inner: Arc<FrameInner>,
263}
264
265impl fmt::Debug for Frame {
266	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
267		f.debug_struct("Frame")
268			.field("image", &self.inner.allocation.image)
269			.field("timeline", &self.inner.timeline)
270			.finish_non_exhaustive()
271	}
272}
273
274impl Frame {
275	/// Image width in pixels.
276	pub fn width(&self) -> u32 {
277		self.image().size.width
278	}
279	/// Image height in pixels.
280	pub fn height(&self) -> u32 {
281		self.image().size.height
282	}
283	/// Image size in pixels.
284	pub fn size(&self) -> Size {
285		self.image().size
286	}
287	/// Image and device import contract.
288	pub fn image(&self) -> &Image {
289		&self.inner.allocation.image
290	}
291	/// Packed pixel format.
292	pub fn format(&self) -> Format {
293		self.image().format
294	}
295
296	#[cfg(any(feature = "nvidia", all(test, feature = "render")))]
297	pub(crate) fn handles(&self) -> Result<Handles, Error> {
298		self.inner.allocation.handles.try_clone()
299	}
300
301	#[cfg(all(test, feature = "render"))]
302	pub(crate) fn timeline(&self) -> Timeline {
303		self.inner.timeline
304	}
305
306	#[cfg(feature = "nvidia")]
307	pub(crate) fn import<T: Any + Send + Sync>(
308		&self,
309		create: impl FnOnce() -> Result<T, Error>,
310	) -> Result<Arc<T>, Error> {
311		let mut imports = self.inner.allocation.imports.lock().expect("Vulkan imports poisoned");
312		if let Some(imported) = imports.get(&TypeId::of::<T>()) {
313			return Ok(imported.clone().downcast().expect("Vulkan import type"));
314		}
315		let imported = Arc::new(create()?);
316		imports.insert(TypeId::of::<T>(), imported.clone());
317		Ok(imported)
318	}
319
320	#[cfg(feature = "nvidia")]
321	pub(crate) fn read(&self, imported: Arc<dyn Reader>) -> Result<(), Error> {
322		let mut reader = self.inner.reader.lock().expect("Vulkan reader poisoned");
323		if let Some(current) = reader.as_ref() {
324			if !Arc::ptr_eq(current, &imported) {
325				return Err(Error::Unsupported(
326					"external image cannot be read through multiple import backends".into(),
327				));
328			}
329		} else {
330			imported.wait(self.inner.timeline.ready)?;
331			*reader = Some(imported);
332		}
333		Ok(())
334	}
335
336	#[cfg(feature = "nvidia")]
337	pub(crate) fn converted(
338		&self,
339		color: crate::Color,
340		convert: impl FnOnce() -> Result<super::cuda::Frame, Error>,
341	) -> Result<super::cuda::Frame, Error> {
342		let mut converted = self.inner.converted.lock().expect("Vulkan conversions poisoned");
343		if let Some((_, frame)) = converted.iter().find(|(existing, _)| *existing == color) {
344			return Ok(frame.clone());
345		}
346		let frame = convert()?;
347		converted.push((color, frame.clone()));
348		Ok(frame)
349	}
350}
351
352pub(crate) trait Reader: Send + Sync {
353	#[cfg_attr(
354		not(feature = "nvidia"),
355		allow(dead_code, reason = "only the `nvidia` feature uses it")
356	)]
357	fn wait(&self, value: u64) -> Result<(), Error>;
358	fn finish(&self, value: u64, completion: Box<dyn Complete>);
359}
360
361struct FrameInner {
362	allocation: Arc<Allocation>,
363	timeline: Timeline,
364	reader: Mutex<Option<Arc<dyn Reader>>>,
365	completion: Option<Box<dyn Complete>>,
366	#[cfg(feature = "nvidia")]
367	converted: Mutex<Vec<(crate::Color, super::cuda::Frame)>>,
368}
369
370impl Drop for FrameInner {
371	fn drop(&mut self) {
372		let completion = self.completion.take().expect("Vulkan completion missing");
373		if let Some(reader) = self.reader.get_mut().expect("Vulkan reader poisoned").take() {
374			reader.finish(self.timeline.complete, completion);
375		} else {
376			completion.complete(false);
377		}
378	}
379}
380
381pub(crate) trait Complete: Send + Sync {
382	fn complete(self: Box<Self>, reusable: bool);
383}
384
385struct ReturnSlot<T: Send + Sync + 'static> {
386	slot: Slot<T>,
387	sender: tokio::sync::oneshot::Sender<Slot<T>>,
388}
389
390impl<T: Send + Sync + 'static> Complete for ReturnSlot<T> {
391	fn complete(self: Box<Self>, reusable: bool) {
392		if reusable {
393			let _ = self.sender.send(self.slot);
394		}
395	}
396}
397
398/// Resolves to the producer slot after the GPU has signalled completion.
399pub struct Completion<T: Send + Sync + 'static> {
400	receiver: tokio::sync::oneshot::Receiver<Slot<T>>,
401}
402
403impl<T: Send + Sync + 'static> Completion<T> {
404	/// Return the slot if the GPU has completed, without blocking or polling the GPU.
405	pub fn try_wait(&mut self) -> Result<Option<Slot<T>>, CompletionError> {
406		match self.receiver.try_recv() {
407			Ok(slot) => Ok(Some(slot)),
408			Err(tokio::sync::oneshot::error::TryRecvError::Empty) => Ok(None),
409			Err(tokio::sync::oneshot::error::TryRecvError::Closed) => Err(CompletionError),
410		}
411	}
412
413	/// Wait without blocking a thread until the image can be written again.
414	pub async fn wait(self) -> Result<Slot<T>, CompletionError> {
415		self.receiver.await.map_err(|_| CompletionError)
416	}
417}
418
419/// the GPU failed before the producer slot became safe to reuse.
420#[derive(Clone, Copy, Debug, thiserror::Error)]
421#[error("Vulkan GPU completion failed; the producer slot was released")]
422pub struct CompletionError;
423
424/// A publish failure that returns the still-idle slot.
425pub struct PublishError<T: Send + Sync + 'static> {
426	error: Error,
427	slot: Slot<T>,
428}
429
430impl<T: Send + Sync + 'static> PublishError<T> {
431	fn new(error: Error, slot: Slot<T>) -> Self {
432		Self { error, slot }
433	}
434
435	/// Split the error from the reusable slot.
436	pub fn into_parts(self) -> (Error, Slot<T>) {
437		(self.error, self.slot)
438	}
439}
440
441impl<T: Send + Sync + 'static> fmt::Debug for PublishError<T> {
442	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
443		f.debug_struct("PublishError")
444			.field("error", &self.error)
445			.finish_non_exhaustive()
446	}
447}
448
449impl<T: Send + Sync + 'static> fmt::Display for PublishError<T> {
450	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
451		fmt::Display::fmt(&self.error, f)
452	}
453}
454
455impl<T: Send + Sync + 'static> std::error::Error for PublishError<T> {}
456
457pub(crate) fn uuid(bytes: [u8; 16]) -> String {
458	bytes.iter().map(|byte| format!("{byte:02x}")).collect()
459}
460
461#[cfg(all(test, feature = "nvidia"))]
462#[path = "vulkan_test.rs"]
463pub(crate) mod tests;
464
465#[cfg(test)]
466mod unit_tests {
467	use super::*;
468	use std::os::unix::net::UnixStream;
469
470	fn image() -> Image {
471		Image {
472			device: Device {
473				device_uuid: [0xaa; 16],
474				driver_uuid: [0xbb; 16],
475				render_node: None,
476			},
477			memory: Memory::OpaqueFd { memory_type: 1 },
478			size: Size::new(4, 2),
479			allocation_size: 4096,
480			format: Format::Rgba8,
481		}
482	}
483
484	fn slot() -> Slot<()> {
485		let (memory, timeline) = UnixStream::pair().unwrap();
486		Slot::new(
487			Handles {
488				memory: memory.into(),
489				timeline: timeline.into(),
490			},
491			image(),
492			(),
493		)
494		.unwrap()
495	}
496
497	#[test]
498	fn rejects_invalid_image_contracts() {
499		let mut contract = image();
500		contract.size.width = 0;
501		assert!(contract.validate().is_err());
502		contract.size = Size::new(3, 5);
503		assert!(contract.validate().is_ok());
504		contract.allocation_size = 0;
505		assert!(contract.validate().is_err());
506		contract = image();
507		contract.memory = Memory::OpaqueFd { memory_type: 32 };
508		assert!(contract.validate().is_err());
509	}
510
511	#[test]
512	fn refuses_dma_buf_without_explicit_valid_plane_layouts() {
513		for planes in [
514			vec![],
515			vec![Plane {
516				offset: 0,
517				row_pitch: 0,
518			}],
519			vec![Plane {
520				offset: 4096,
521				row_pitch: 32,
522			}],
523			vec![
524				Plane {
525					offset: 0,
526					row_pitch: 32
527				};
528				5
529			],
530		] {
531			let mut contract = image();
532			contract.memory = Memory::DmaBuf { modifier: 0, planes };
533			assert!(contract.validate().is_err());
534		}
535		let mut padded = image();
536		padded.memory = Memory::DmaBuf {
537			modifier: 0,
538			planes: vec![Plane {
539				offset: 128,
540				row_pitch: 64,
541			}],
542		};
543		assert!(padded.validate().is_ok());
544	}
545
546	#[test]
547	fn validates_timeline_even_when_fields_are_set_directly() {
548		assert!(Timeline::new(4, 4).is_err());
549		assert!(Timeline::new(5, 4).is_err());
550		assert!(slot().publish(Timeline { ready: 4, complete: 4 }).is_err());
551		assert!(slot().publish(Timeline { ready: 0, complete: 1 }).is_err());
552	}
553
554	#[tokio::test]
555	async fn unconsumed_image_retains_guard_until_last_clone_and_is_never_recycled() {
556		use std::sync::atomic::{AtomicUsize, Ordering};
557		struct Guard(Arc<AtomicUsize>);
558		impl Drop for Guard {
559			fn drop(&mut self) {
560				self.0.fetch_add(1, Ordering::SeqCst);
561			}
562		}
563		let released = Arc::new(AtomicUsize::new(0));
564		let (memory, timeline) = UnixStream::pair().unwrap();
565		let slot = Slot::new(
566			Handles {
567				memory: memory.into(),
568				timeline: timeline.into(),
569			},
570			image(),
571			Guard(released.clone()),
572		)
573		.unwrap();
574		let (frame, mut completion) = slot.publish(Timeline::new(1, 2).unwrap()).unwrap();
575		let held = frame.clone();
576		drop(frame);
577		assert_eq!(released.load(Ordering::SeqCst), 0);
578		assert!(completion.try_wait().unwrap().is_none());
579		drop(held);
580		assert!(completion.wait().await.is_err());
581		assert_eq!(released.load(Ordering::SeqCst), 1);
582	}
583
584	#[cfg(feature = "nvidia")]
585	#[tokio::test]
586	async fn caches_imports_by_slot_and_returns_only_after_last_reader() {
587		struct Import;
588		impl Reader for Import {
589			fn wait(&self, _: u64) -> Result<(), Error> {
590				Ok(())
591			}
592			fn finish(&self, _: u64, completion: Box<dyn Complete>) {
593				completion.complete(true);
594			}
595		}
596		let (frame, mut completion) = slot().publish(Timeline::new(1, 2).unwrap()).unwrap();
597		let imported = frame.import(|| Ok(Import)).unwrap();
598		let duplicate_handles = frame.handles().unwrap();
599		drop(duplicate_handles);
600		assert!(Arc::ptr_eq(
601			&imported,
602			&frame.import::<Import>(|| panic!("imported twice")).unwrap()
603		));
604		frame.read(imported.clone()).unwrap();
605		let held = frame.clone();
606		drop(frame);
607		assert!(completion.try_wait().unwrap().is_none());
608		drop(held);
609		let slot = completion.wait().await.unwrap();
610		let (_, completion) = slot.publish(Timeline::new(2, 3).unwrap()).err().unwrap().into_parts();
611		let (frame, completion) = completion.publish(Timeline::new(3, 4).unwrap()).unwrap();
612		assert!(Arc::ptr_eq(
613			&imported,
614			&frame.import::<Import>(|| panic!("reimported slot")).unwrap()
615		));
616		frame.read(imported).unwrap();
617		drop(frame);
618		assert!(completion.wait().await.is_ok());
619	}
620}