Expand description
Typed, owned native GPU resource handles, cross-API sync points and video pixel formats — the vocabulary for passing GPU resources between libraries: a decoder handing frames to a renderer, a renderer handing textures to an encoder, one graphics API importing another’s memory.
GpuResource— one validated newtype per native handle kind (Vulkan, D3D11 / D3D12, Metal / IOSurface / CoreVideo, OpenGL, CUDA, OpenCL, DMA-BUF / VA-API,AHardwareBuffer/ MediaCodec,wgpu, the browser, CPU memory). OS handles and refcounted foreign objects are owned behind anArc; borrowed API handles can carry aResourceKeepAlivefrom their producer.GpuContext/ExternalQueue— an existing context or queue a host asks a library to work inside.SyncPoint/SyncWaiter— “this work is done” across APIs, with blocking, timeout-bounded andasyncwaits.PixelFormat— video and image pixel formats with their plane layouts, bit depths, alpha semantics and stable shader ordinals.MemoryBudget,BackendKind,DeviceId,Error— the accounting and identity types around them.
What the pixels mean — colour, frame metadata, geometry — lives one
crate down, in video-types, whose types this crate’s API uses directly.
No dyn dispatch on the per-frame hot path. One background thread, owned
and documented: the WaiterThread that parks on fences a caller cannot
poll. Async waits are offered beside the blocking ones, never instead of
them. No backend-library knowledge: nothing here links FFmpeg, CUDA or
OpenCL, and wgpu only behind the wgpu feature.
§Features
| Feature | Default | Enables |
|---|---|---|
wgpu | on | wgpu-backed resource / context / sync variants, texture byte estimates, the device-creation and error-scope locks |
serde | off | Serialize / Deserialize on PixelFormat, PlaneFormat, AlphaChannel; forwards video-types/serde |
cuda, opencl | off | The CUDA / OpenCL compute backends’ BackendKind variants, queue variants and budget caps (no library is linked) |
web, webgl, web-codecs | off | Browser handles on wasm32 (WebGPU, WebGL, DOM image sources, WebCodecs VideoFrame) |
ash | off | VkImage::as_ash_image / VkBufferHandle::as_ash_buffer |
Structs§
- Backend
Wait Future - Future returned by
WaiterThread::enqueue. Resolves when the waiter thread reportsSignaled/Failed/Err(Timeout)on the deadline. - Budget
Caps - Per-backend budget caps.
Nonedisables that side (e.g. soft_cap only, hard_cap only, or unbounded). - Budget
Caps Set - Named-field set of per-backend caps. Deliberately a struct with
cfg-gated fields rather than a
[BudgetCaps; N]— noBackendKind::COUNTto mislead under--no-default-features, and partial configs compose via..Default::default(). - Budget
Pressure Event - Budget
Reservation - RAII token. Dropping the token releases the reservation back to the pool.
- ClContext
- OpenCL
cl_contextborrowed for an OpenCL sync-target dispatch. The platform/device parentage is rederived inside the bridge viaclGetContextInfo. - ClQueue
Ref - OpenCL
cl_command_queueborrowed byExternalQueue::OpenClQueue. - CpuBytes
- Flat CPU byte buffer. The raw
ptris non-owning;keep_alivepins whatever owns the backing allocation (an SDK decoder’s frame anchor, an aligned-buffer pool slot, a boxed expand buffer, …) so the bytes outlive every clone the caller hands off. PassNoneonly when the caller guarantees the allocation’s lifetime by other means (e.g. a test stack buffer that outlives the handle). - CpuPlane
- CpuPlane
Set - Up-to-four-plane CPU buffer set.
count∈1..=4; unused slots areNone. Zero heap allocation — the[Option<CpuPlane>; 4]is inline. - CpuShared
Slot - Producer-allocated CPU staging slot. Caller cannot dereference; reads land via the producer’s readback API.
- Cuda
Buffer Handle - 1D (flat) CUDA device pointer with byte size.
- Cuda
Context - CUDA
CUcontextborrowed for the duration of a CUDA sync-target dispatch. - Cuda
Ptr2D - 2D (pitched) CUDA device pointer (
CUdeviceptraliased asu64). - Cuda
Stream Ref - CUDA
CUstreamborrowed byExternalQueue::CudaStream. The stream’s lifetime is anchored by the caller’s CUDA context. - Cuda
Surface wgpu - Opaque CUDA
CUsurfObjectbound to aCUarray, used as asurf2Dwritekernel write target. - D3D11
Device ID3D11Device*borrowed for a D3D11 sync-target dispatch. Caller has setD3D11_RESOURCE_MISC_SHARED_KEYEDMUTEXor the multithread-protect flag — that’s the cross-thread contract.- D3D11
Texture ID3D11Texture2D*keyed-mutex / shared-handle resource.- D3D12
Buffer Handle - Buffer-dimension
ID3D12Resource*(committed withDimension = D3D12_RESOURCE_DIMENSION_BUFFER). - D3D12
Device ID3D12Device*borrowed for a D3D12 sync-target dispatch. LUID-matched against the sourceVkDevice/ Vulkan instance by the bridge dispatcher.- D3D12
Resource ID3D12Resource*keyed-mutex / shared-handle resource (Texture2D dimension).- Deferred
Wgpu Slot wgpu - Shared, mutate-once slot the producer fills in after the caller
submits the encoded work. Used by
SyncPoint::DeferredWgpu. - Device
Info - DmaBuf
Handle Android or Linux - Linux / Android DMA-BUF descriptor — the direct analogue of libva’s
VADRMPRIMESurfaceDescriptor(va_drmcommon.h). - DmaBuf
Import Desc Android or Linux - Everything about a DMA-BUF surface except the object fds themselves —
the layout half of
DmaBufHandle. - GlBuffer
Handle - GL buffer object (
GLuint) + binding metadata. - GlContext
Ref - Platform-native OpenGL context handle (
EGLContext/HGLRC/CGLContextObj). TheGlBackendflavour travels alongside it in an OpenGL sync target so the bridge dispatcher resolves the matching proc-address loader without re-probing. - GlTexture
Handle - GL texture name (
GLuint) + binding metadata. - Memory
Budget - Metal
Buffer Handle MTLBuffer*.- Metal
Texture Handle MTLTexture*(Objective-C-bridged Metal texture).- MtlCommand
Buffer Ref id<MTLCommandBuffer>borrowed byExternalQueue::MetalCommandBuffer. Recording into the same command buffer from multiple threads is undefined, and nothing here prevents it — the borrow is shared and the newtype isCopy, so confining recording to one thread is the caller’s obligation.- MtlDevice
id<MTLDevice>borrowed for a Metal sync-target dispatch.- Open
ClGl Sharing - Caller-asserted GL-sharing handles for an
OpenClcontext. - Open
ClMem cl_memhandle paired with its producingcl_command_queue.- Plane
Info - Storage description of a single plane in a
PlaneLayout. - Plane
Layout - How a pixel format lays out its planes in memory.
- Pool
Handle - Pressure
Callback Handle - RawFence
Carrier Waiter - A
SyncWaiterfor aSyncPointreconstructed from a raw foreign fence handle that has not yet been imported onto a waiting device. - Vaapi
Surface Linux - VAAPI surface (
VASurfaceID+VADisplay), as a newtype so theGpuResourceenum carries it uniformly with the rest. - VkAcquire
Binary Hermit or Unix or WASI or Windows - Per-frame fresh BINARY semaphore carrier — the NVIDIA-Windows
fallback path when
VkAcquireTimelinecannot be GPU-waited by the consumer (no exportable D3D12_FENCE timeline flavour AND noGL_NV_timeline_semaphore + OPAQUE_WIN32import support). - VkAcquire
Timeline Hermit or Unix or WASI or Windows - Optional GPU-side acquire-sync attached to a
VkOpaqueFd/VkOpaqueWin32carrier. - VkBuffer
Handle - Vulkan
VkBufferon a specificVkDevice. - VkDevice
VkDeviceborrowed for a Vulkan sync-target dispatch.- VkImage
- Vulkan
VkImageon a specificVkDevice, with optional cross-vendor identity (deviceUUID). - VkInstance
VkInstanceborrowed for a Vulkan sync-target dispatch. Required even for device-level work because ash resolves device fn pointers throughvkGetDeviceProcAddr, which is itself an instance-level command (vkGetInstanceProcAddr(NULL, ...)returns NULL).- VkOpaque
Export Desc Hermit or Unix or WASI or Windows - The producer-side export descriptor both native opaque-handle
carriers carry —
VkOpaqueFdon POSIX,VkOpaqueWin32on Windows. (Those two are mutually-exclusive#[cfg]s, so they are named as plain code spans here rather than intra-doc links: no single rustdoc target can resolve both.) - VkOpaque
Fd Hermit or Unix or WASI - Vulkan opaque-fd export via
VK_KHR_external_memory_fd. - VkSlot
Release - Consumer→producer slot-release back-pressure carrier.
- Waiter
Thread - Permanently-attached waiter thread + request channel.
- Wgpu
Texture wgpu - A native
wgpu::Texturethat already lives on the consumer’s own wgpu device — the zero-interop passthrough.
Enums§
- Alpha
Channel - What a
PixelFormat’s fourth component means — the contract a consumer must honour before it reads lane 3 of a packed layout (or the fourth plane of a planar one). - Angle
Backend - Underlying implementation of an ANGLE “GL” context. Probed via
glGetString(GL_RENDERER)+ the matchingEGL_ANGLE_*extension whenGlBackend::Angle(_)is selected. - Backend
Kind - Identity of a compute backend. Used as a discriminant on error
variants, budget accounting,
GpuContext,SyncPoint, etc. - Budget
Pressure - Device
Id - Stable identity of a physical GPU / CPU / accelerator. Used as cache
key in multi-GPU setups and as an equality test for
Error::DeviceMismatch. - Error
- Domain error for every leaf operation in
gpu-handle-types. - Error
Kind - Classification of an
Error. Callers branch on.kind()for retry / abort / reconfigure decisions without pattern-matching every variant. - Execution
Path - Which path a frame went down. Carried on per-call result types (an interop layer’s import / export results) rather than process-global cells.
- External
Queue - Borrowed handle into an external command queue. The
'alifetime ties the queue to the caller’s scope so the borrow-checker prevents reentrant use across the call it is lent to. - GlBackend
- Which GL context flavour
GpuContext::OpenGL::contextpoints at. - GlBuffer
Target - GL buffer bind target. Non-exhaustive — covers the targets a video / VFX caller realistically allocates exportable buffers under.
- GlInternal
Format - GL sized internal-format enum the texture was created with — only the subset that a video pipeline ever surfaces.
- GlTexture
Target - GL bind target the texture was allocated with. Maps 1:1 onto the
matching
GL_TEXTURE_*enum value. - GpuContext
- GpuContext
Error - Failure modes for the typed
GpuContextunpackers above. - GpuResource
- Zero-copy GPU resource handle.
- Invalid
Handle Error - Returned from
try_from_rawconstructors when the caller-supplied payload violates an invariant the newtype enforces (e.g. a null VkImage, a zero-sized D3D12 buffer). - Pixel
Format - Every pixel layout this crate understands.
- Plane
Format - Per-plane storage primitive. A plane’s
PlaneFormatnames the smallest texture format a GPU upload would use for it; the shader reinterprets the channels when needed (e.g. AYUV64LE usesRGBA16storage with AYUV channel semantics). - Slice
Outcome - Result of one slice-bounded native wait. Returned by the
SliceFnclosure each per-backendwait_asyncoverride supplies. - Sync
Point - GPU sync primitive. Produced by every submit-side path; consumed by anything that needs to serialise on a prior GPU submission.
- Vulkan
Semaphore Kind - Discriminator for
SyncPoint::Vulkan’sVkSemaphoreflavour.
Constants§
- DEFAULT_
WAIT_ TIMEOUT - Default wait budget for
SyncPoint::wait()andSyncPoint::wait_blocking()— 10 seconds. - WAITER_
SLICE - Per-slice native blocking-with-timeout budget. Sized to:
Traits§
- Cuda
Event Waiter - CUDA-event-specific extension trait for the
SyncPoint::CudaEventvariant. Supertrait ofSyncWaiterso aCudaEventWaiteralways satisfies the genericSyncPoint::waitdispatch path; adds the CUDA-onlywait_on_foreign_streamextension method that cross-API bridges downcast to viaSyncWaiter::as_any. - Evictable
Pool - Pool trait — drop unused resources on request. This is the single
dynexception in this crate; see the module doc-comment. TheMaybeSendSyncsupertrait isSend + Syncoff wasm and empty on wasm. - GlContext
Executor - Host-supplied scheduler that posts a closure onto the thread that owns a particular OpenGL context.
- Maybe
Send Non- target_family=wasm Sendoff wasm; empty on wasm.- Maybe
Send Sync Non- target_family=wasm Send + Syncoff wasm; empty on wasm. See module docs.- Resource
Keep Alive - Marker trait for per-variant lifetime anchors carried on
GpuResourcenewtypes. - Sync
Waiter - Backend-specific wait dispatch + lifetime anchor for a
SyncPoint.
Functions§
- duration_
to_ ms_ u32 - Helper: convert a
Durationto milliseconds, saturating atu32::MAXfor the Win32INFINITEsentinel (WaitForSingleObject,WaitForMultipleObjects). - duration_
to_ ns - Helper: convert a
Durationto nanoseconds, saturating atu64::MAXfor “wait forever”. MatchesvkWaitSemaphores’UINT64_MAXinfinite-wait sentinel. - estimate_
descriptor_ bytes wgpu - Convenience wrapper around
estimate_texture_bytesfor callers that already hold awgpu::TextureDescriptor. - estimate_
texture_ bytes wgpu - Estimate the on-device byte footprint of a 2D / 3D texture.
- lock_
device_ creation wgpu - Acquire the process-global wgpu device-creation lock. Hold the returned
guard across the whole
Instance::new → request_adapter → request_devicesequence (and drop it once the device exists). Reentrant on the holding thread, so a library call made inside the sequence that takes the lock itself proceeds instead of deadlocking. - make_
deferred_ wgpu_ sync_ point wgpu - Construct a
SyncPoint::DeferredWgpucomplete with its waiter. - run_
hybrid_ wait - Compose the fast-path yield-spin (bounded) + the waiter-thread
fallback (thread handoff) into the canonical hybrid
wait_asyncbody. - wait_
deadline - The absolute deadline a
wait(timeout)poll loop should honour, orNonefor theSyncWaiter::waitcontract’sDuration::MAX“wait forever” sentinel. - with_
device_ creation_ lock wgpu - Run
f(a wgpu device-creation sequence) under the process-global device-creation lock. See the module docs for why this exists. - with_
error_ scope wgpu - Run
f(an allocation already bracketed bypush_error_scope/pop_error_scopeondevice) while holdingdevice’s process-global error-scope lock, so the push/pop triple cannot interleave with a concurrent triple on the same device. - yield_
once - Runtime-agnostic single-yield future. Returns
Pendingonce then resolves toReady(())on the next poll, withwake_by_refdriving the re-poll. Works under any executor (pollster,tokio,smol,futures::executor).
Type Aliases§
- BoxFuture
Non- target_family=wasm - Boxed dyn-future return shape used by
SyncWaiter::wait_asyncso the trait stays object-safe throughArc<dyn SyncWaiter>. Nativeasync fnon the trait would be RPITIT and dyn-incompatible by default; callers dispatch throughArc<dyn SyncWaiter>, so boxing the future is mandatory. - Keep
Alive - Convenience alias for the boxed-trait-object form most call sites use.
- Pressure
Callback Non- target_family=wasm - SliceFn
Non- target_family=wasm - Boxed closure each per-backend
wait_asyncoverride builds at handoff time. The waiter thread calls it on its own thread with the current slice budget; the closure must: