diff --git a/crates/reims-vgpu-video/src/vaapi/va/d3d11.rs b/crates/reims-vgpu-video/src/vaapi/va/d3d11.rs index aea6df9b2..d0f2a919d 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/d3d11.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/d3d11.rs @@ -1,4 +1,4 @@ -//! Direct3D 11 on Windows: a picture's planes drawn from the shared texture it decoded into +//! Direct3D 11 on Windows: a picture's planes drawn from the pool texture it decoded into //! (`Frame::texture`) into two textures of one plane each, which another device imports as //! images of one plane ([`PlaneDraw`], [`PlaneTargets`]). //! @@ -10,7 +10,9 @@ //! (`D3D11_RESOURCE_MISC_SHARED | D3D11_RESOURCE_MISC_SHARED_NTHANDLE`): the luma as `R8_UNORM` (`R16_UNORM` for 10-bit samples) and the chroma's Cb and Cr samples packed into //! one texel, `Cb | Cr << 8` as `R16_UINT` (`<< 16`, `R32_UINT`), which reads as `RG8Unorm` //! (`RG16Unorm`) in a view of the same bits. The draws run on a Direct3D 11 device over a -//! Direct3D 12 device of ours (D3D11On12), which opens each pool texture by its NT handle and +//! Direct3D 12 device of ours (D3D11On12), the pools' own device (one a process and adapter, +//! `super::d3d12`), which wraps each pool texture's resource (`CreateWrappedResource`) rather +//! than open an NT handle of it, an open that would stay charged for good (`super::d3d12`), and //! reads its planes through views of `R8_UINT` and `R8G8_UINT` (`R16_UINT` and `R16G16_UINT`): //! one triangle a plane over the crop's extent, each pixel its texel from the crop's origin, so //! the targets hold what the CPU's copy writes, at their first texel, and nothing past it. @@ -32,11 +34,11 @@ //! What a picture's draw would otherwise pay the first time is made with the [`PlaneDraw`], at a //! decoder's open: the devices, the shaders, compiled by `D3DCompile` at run time, and the //! pipelines of the four target formats, by a draw into a texture of each. A pool texture's open -//! and views are made at its first picture, and kept while it lives: the texture tells the draws -//! as it goes (`SharedTexture::on_let_go`), and they let go of its open then, on the thread that -//! let go of the texture, and flush as a pair of targets let go does (below). An open keeps the -//! texture's memory, so a pool's goes as the pool does, not at the draws' next picture of another -//! pool, which may never come. +//! (the wrap of its resource) and views are made at its first picture, and kept while it lives: +//! the texture tells the draws as it goes (`SharedTexture::on_let_go`), and they let go of its +//! open then, on the thread that let go of the texture, and flush as a pair of targets let go does +//! (below). An open keeps the texture's memory, so a pool's goes as the pool does, not at the +//! draws' next picture of another pool, which may never come. //! //! Direct3D 11 destroys an object whose last reference goes only at a later flush of its //! device's immediate context ("deferred destruction", `ID3D11DeviceContext::Flush`'s @@ -91,7 +93,7 @@ use crate::core::sync::{Condvar, Mutex}; use super::d3d12::{ Com, CommandQueueDesc, CreateEventW, DEVICE_CREATE_COMMAND_QUEUE, DEVICE_CREATE_FENCE, Device, FENCE_GET_COMPLETED_VALUE, FENCE_SET_EVENT_ON_COMPLETION, Guid, Handle, Hresult, - IID_ID3D12_COMMAND_QUEUE, IID_ID3D12_FENCE, IID_ID3D12_RESOURCE, LetGo, QUEUE_SIGNAL, + IID_ID3D12_COMMAND_QUEUE, IID_ID3D12_FENCE, LetGo, QUEUE_SIGNAL, SharedTexture, WAIT_OBJECT_0, WaitForSingleObject, adapter_of, check, guid, system_function, }; @@ -129,7 +131,6 @@ const DEVICE_CREATE_VERTEX_SHADER: usize = 12; const DEVICE_CREATE_PIXEL_SHADER: usize = 15; const DEVICE_CHECK_FEATURE_SUPPORT: usize = 33; const DEVICE1_OPEN_SHARED_RESOURCE_1: usize = 48; -const D3D12_DEVICE_OPEN_SHARED_HANDLE: usize = 32; const CONTEXT_PS_SET_SHADER_RESOURCES: usize = 8; const CONTEXT_PS_SET_SHADER: usize = 9; const CONTEXT_VS_SET_SHADER: usize = 11; @@ -371,7 +372,7 @@ struct Makers { struct Opened { /// The texture's life, which the texture's drop names the entry by (module doc). texture: Weak<()>, - /// The texture's Direct3D 12 resource, opened by its NT handle. + /// The texture's Direct3D 12 resource, a reference of the draws' own. _resource: Com, /// The resource wrapped for the Direct3D 11 device, and its luma and chroma views. wrapped: Com, @@ -809,24 +810,7 @@ impl State { if let Some(at) = (self.opened.iter()).position(|o| Weak::ptr_eq(&o.texture, &life)) { return Ok((at, false)); } - let mut out = null_mut(); - // SAFETY: the method is ID3D12Device's `OpenSharedHandle`, of the texture's NT handle, - // which is open while the texture lives, with ID3D12Resource's IID. - let result = unsafe { - let open: unsafe extern "system" fn( - *mut c_void, - *mut c_void, - *const Guid, - *mut *mut c_void, - ) -> Hresult = self.d3d12.device.method(D3D12_DEVICE_OPEN_SHARED_HANDLE); - open( - self.d3d12.device.raw(), - texture.raw_handle(), - &IID_ID3D12_RESOURCE, - &mut out, - ) - }; - let resource = Com::made("ID3D12Device::OpenSharedHandle", result, out)?; + let resource = texture.resource(&self.d3d12.device)?; let flags = ResourceFlags { bind_flags: D3D11_BIND_SHADER_RESOURCE, misc_flags: 0, diff --git a/crates/reims-vgpu-video/src/vaapi/va/d3d11/tests.rs b/crates/reims-vgpu-video/src/vaapi/va/d3d11/tests.rs index eff8d13fe..be6609084 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/d3d11/tests.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/d3d11/tests.rs @@ -12,7 +12,7 @@ use crate::core::runtime::{Runtime as _, StdRuntime}; use super::super::d3d12::{ Com, Device, Guid, Hresult, SharedTexture, check, default_adapter_device_references, - default_adapter_device_references_once_let_go, guid, + default_adapter_device_references_once_let_go, guid, process_gpu_memory_settled, }; use super::super::display::Display; use super::super::frame::{Frame, PlaneRows}; @@ -489,11 +489,15 @@ fn targets_let_go_give_back_their_memory() { /// session's end: while they live the draws keep an open of each, and once they are let go none /// (the fix's own claim, by count). By memory, three cycles: the level after the last, against the /// level after the first, is up by less than a tenth of what a cycle's 16 textures held, so that -/// what a pool left behind would add up past the bound. The level after the first cycle is not -/// asserted: on the UHD Graphics 630 that cycle left 63,930,368 of the 466,493,440 bytes its -/// textures held, with one flush of the draws' contexts and with a second after a wait for the GPU -/// alike (**measured** 2026-11-26, driver 31.0.101.2145, potluck jobs m3-max-75548 and -/// m3-max-75554); the test prints it. Run holding the GPU, on the default adapter. +/// what a pool left behind would add up past the bound, as DXGI counts the process's memory and +/// as Windows charges it (`super::super::d3d12::process_gpu_memory`): an open of each texture's NT +/// handle, which DXGI did not count, stayed charged for good, 16 times a texture's 12.4 MB a cycle +/// (`super::super::d3d12`'s module doc), where the draws' wrap of its resource leaves nothing. The +/// level after the first cycle is not asserted: on the UHD Graphics 630, with those opens, that +/// cycle left 63,930,368 of the 466,493,440 bytes its textures held as DXGI counts them, with one +/// flush of the draws' contexts and with a second after a wait for the GPU alike (**measured** +/// 2026-11-26, driver 31.0.101.2145, potluck jobs m3-max-75548 and m3-max-75554); the test prints +/// both. Run holding the GPU, on the default adapter. #[test] #[ignore = "needs Direct3D 11 on the default adapter: run on the Windows host"] fn pool_textures_let_go_give_back_their_memory() { @@ -502,8 +506,9 @@ fn pool_textures_let_go_give_back_their_memory() { let draw = PlaneDraw::new(None).expect("the plane draws"); let to = draw.targets((64, 48), false).expect("the targets"); let device = Device::new(None).expect("a Direct3D 12 device"); - // A cycle (above): what its textures held above the level it began at, and the level after. - let cycle = |n: usize| -> (u64, u64) { + // A cycle (above): what its textures held above the level it began at, and the level after, + // as DXGI counts it and as Windows charges it. + let cycle = |n: usize| -> (u64, u64, u64) { let start = memory_used(&draw); let textures: Vec> = (0..16) .map(|_| { @@ -532,22 +537,30 @@ fn pool_textures_let_go_give_back_their_memory() { 0, "cycle {n}: no open of a texture let go" ); - (held, memory_used(&draw)) + (held, memory_used(&draw), process_gpu_memory_settled()) }; - let before = memory_used(&draw); - let (held, first) = cycle(1); + let before = (memory_used(&draw), process_gpu_memory_settled()); + let (held, first, first_charged) = cycle(1); println!( - "the first cycle left {} bytes of the {held} that its 16 pool textures held", - first.saturating_sub(before) + "the first cycle left {} bytes of the {held} that its 16 pool textures held, and {} bytes \ + charged", + first.saturating_sub(before.0), + first_charged.saturating_sub(before.1) ); cycle(2); - let (held, last) = cycle(3); + let (held, last, last_charged) = cycle(3); let grown = last.saturating_sub(first); assert!( grown < held / 10, "{grown} bytes more after the third cycle than after the first, of the {held} that a \ cycle's 16 pool textures held" ); + let grown = last_charged.saturating_sub(first_charged); + assert!( + grown < held / 10, + "{grown} bytes more charged after the third cycle than after the first, of the {held} \ + that a cycle's 16 pool textures held" + ); } /// Pairs of targets let go of together share their flushes (the module doc's): four pairs of diff --git a/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs b/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs index 76560587e..8f7c1353b 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/d3d12.rs @@ -1,16 +1,29 @@ //! Direct3D 12, on Windows, as much of it as the module needs: a device on the display's DXGI -//! adapter, shared NV12 and P010 textures that the display's pools are made of, and copies -//! between them. +//! adapter, the NV12 and P010 textures that the display's pools are made of, and copies between +//! them. //! -//! A pool's surfaces on Windows are textures of ours, made here on the adapter's device with a -//! shared heap (`D3D12_HEAP_FLAG_SHARED`), each opened by Mesa's VA driver (`vaon12`) through its -//! NT handle (`VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE`), so that what decodes into them can be read -//! by others that open the same handle: the Vulkan platform's copy of a picture into the guest's -//! planes. vaon12's own surfaces are not shared, and their export fails (measured on the UHD 630, +//! A pool's surfaces on Windows are textures of ours, made here on the adapter's device, each +//! handed to Mesa's VA driver (`vaon12`) as its resource +//! (`VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE`), so that what decodes into them can be read by +//! the plane draws (`super::d3d11`), which wrap the same resource. Direct3D 12 makes one device a +//! process and adapter (`D3D12CreateDevice` answers the one that lives), so the driver's, the +//! draws' and the pools' devices on the decode's adapter are one, and each takes the resource as +//! its own. vaon12's own surfaces cannot be read so: their export fails (measured on the UHD 630, //! Mesa 26.2.7, 2026-11-16). A copy of one texture into another (a stand-in for a lost frame, //! `super::surface`) runs on a copy queue of this device's, which the module waits for on its //! fence. //! +//! No pool texture is shared by an NT handle. An open of a texture's NT handle on the device that +//! made it (`ID3D12Device::OpenSharedHandle`) charged the process's GPU memory with the texture's +//! size for good: past the open's release, the texture's and its handle's, and the display's +//! `vaTerminate`, while the device lived; and vaon12's import of an NT handle +//! (`VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE`) is such an open, charged again at each import of the +//! same texture. A pool of six 3840x2160 NV12 textures was charged 72 MiB at each import and at +//! each of the draws' opens, with no VA call for the opens alone, in the "GPU Process Memory" +//! counters' Shared Usage, which DXGI's `QueryVideoMemoryInfo` does not count; handed over and +//! wrapped as resources, none (measured on an Intel UHD Graphics 630, driver 31.0.101.2145, Mesa +//! 26.2.7, 2026-11-26, with a program of our own on D3D12 and libva alone). +//! //! The binding is written by hand: the functions are loaded from `d3d12.dll` and `dxgi.dll` with //! `LoadLibraryW` and `GetProcAddress`, as libva is (`super::libva`), and each COM method is //! called through its object's vtable at the index the Windows SDK's headers give it (MSYS2 @@ -97,7 +110,6 @@ pub(super) const IID_ID3D12_FENCE: Guid = guid( // The vtable indices of the methods called (the SDK's `Vtbl` structures). const QUERY_INTERFACE: usize = 0; -#[cfg(test)] const ADD_REF: usize = 1; const RELEASE: usize = 2; const FACTORY4_ENUM_ADAPTER_BY_LUID: usize = 26; @@ -105,7 +117,6 @@ pub(super) const DEVICE_CREATE_COMMAND_QUEUE: usize = 8; const DEVICE_CREATE_COMMAND_ALLOCATOR: usize = 9; const DEVICE_CREATE_COMMAND_LIST: usize = 12; const DEVICE_CREATE_COMMITTED_RESOURCE: usize = 27; -const DEVICE_CREATE_SHARED_HANDLE: usize = 31; pub(super) const DEVICE_CREATE_FENCE: usize = 36; const QUEUE_EXECUTE_COMMAND_LISTS: usize = 10; pub(super) const QUEUE_SIGNAL: usize = 14; @@ -120,12 +131,11 @@ const DXGI_FORMAT_NV12: u32 = 103; const DXGI_FORMAT_P010: u32 = 104; const D3D_FEATURE_LEVEL_11_0: u32 = 0xb000; const D3D12_HEAP_TYPE_DEFAULT: u32 = 1; -const D3D12_HEAP_FLAG_SHARED: u32 = 0x1; +const D3D12_HEAP_FLAG_NONE: u32 = 0; const D3D12_RESOURCE_DIMENSION_TEXTURE2D: u32 = 3; const D3D12_RESOURCE_FLAG_ALLOW_RENDER_TARGET: u32 = 0x1; const D3D12_RESOURCE_STATE_COMMON: u32 = 0; const D3D12_COMMAND_LIST_TYPE_COPY: u32 = 3; -const GENERIC_ALL: u32 = 0x1000_0000; pub(super) const WAIT_OBJECT_0: u32 = 0; /// `D3D12_HEAP_PROPERTIES`. @@ -245,6 +255,18 @@ impl Com { self.0.as_ptr() } + /// Another reference of the object (`AddRef`, every COM object's method 1), released when + /// dropped. + pub(super) fn another(&self) -> Com { + // SAFETY: `AddRef` is every COM object's method 1; the reference it adds is the new + // `Com`'s, which releases it once. + unsafe { + let add_ref: unsafe extern "system" fn(*mut c_void) -> u32 = self.method(ADD_REF); + add_ref(self.raw()); + } + Com(self.0) + } + /// The method at `index` of the object's vtable, as `F`. /// /// # Safety @@ -373,16 +395,18 @@ impl Drop for Handle { } } -/// A shared texture of a pool's: the resource, and the NT handle that opens it elsewhere. +/// A texture of a pool's, shared by the driver's decodes and the draws (module doc), which each +/// take its resource ([`SharedTexture::raw_resource`], [`SharedTexture::resource`]). /// -/// Another device opens it by its NT handle ([`SharedTexture::handle`]), which stays the -/// texture's: an import of it is let go once [`SharedTexture::alive`] no longer upgrades, and a -/// device that keeps its open asks to be told as the texture goes ([`SharedTexture::on_let_go`]), -/// since an open keeps the texture's memory while it lives. +/// An import of it is let go once [`SharedTexture::alive`] no longer upgrades, and a device that +/// keeps one (the draws' wrap of its resource) asks to be told as the texture goes +/// ([`SharedTexture::on_let_go`]), since it keeps the texture's memory while it lives. #[derive(Debug)] pub struct SharedTexture { resource: Com, - handle: Handle, + /// The device that made it, which the draws' device is to be (module doc): its pointer, as + /// the device's identity, never dereferenced. + device: usize, format: SurfaceFormat, size: (u32, u32), /// Its life, which another device's imports of it are let go by. @@ -418,15 +442,19 @@ impl Drop for SharedTexture { } impl SharedTexture { - /// The NT handle that opens the texture, as a pointer, for the driver's import. - pub(crate) fn raw_handle(&self) -> *mut c_void { - self.handle.0.as_ptr() + /// The texture's resource (an `ID3D12Resource`), for the driver's import, which takes a + /// reference of its own. + pub(crate) fn raw_resource(&self) -> *mut c_void { + self.resource.raw() } - /// The NT handle that opens the texture, which stays the texture's. - pub fn handle(&self) -> std::os::windows::io::BorrowedHandle<'_> { - // SAFETY: the handle is open while the texture lives, and the borrow ends with it. - unsafe { std::os::windows::io::BorrowedHandle::borrow_raw(self.handle.0.as_ptr()) } + /// Another reference of the texture's resource, for a device of `device`'s to wrap: `Err` + /// where `device` did not make it, as only the device that made a resource uses it. + pub(super) fn resource(&self, device: &Com) -> Result { + if device.raw().addr() != self.device { + return Err("a texture of another Direct3D 12 device".to_owned()); + } + Ok(self.resource.another()) } /// Whether its samples are 10-bit in 16 (P010), else 8-bit (NV12). @@ -483,7 +511,7 @@ impl Device { }) } - /// A texture of `format`, `width` by `height`, in a shared heap, and its NT handle. + /// A texture of `format`, `width` by `height`, for a pool (module doc). pub(crate) fn shared_texture( &self, format: SurfaceFormat, @@ -532,7 +560,7 @@ impl Device { create( self.device.raw(), &heap, - D3D12_HEAP_FLAG_SHARED, + D3D12_HEAP_FLAG_NONE, &desc, D3D12_RESOURCE_STATE_COMMON, null(), @@ -541,34 +569,9 @@ impl Device { ) }; let resource = Com::made("CreateCommittedResource", result, resource)?; - let mut handle = null_mut(); - // SAFETY: the method is `CreateSharedHandle`, of a resource of this device's in a shared - // heap, with no security attributes and no name. - let result = unsafe { - let share: unsafe extern "system" fn( - *mut c_void, - *mut c_void, - *const c_void, - u32, - *const u16, - *mut *mut c_void, - ) -> Hresult = self.device.method(DEVICE_CREATE_SHARED_HANDLE); - share( - self.device.raw(), - resource.raw(), - null(), - GENERIC_ALL, - null(), - &mut handle, - ) - }; - check("CreateSharedHandle", result)?; - let handle = NonNull::new(handle) - .map(Handle) - .ok_or("CreateSharedHandle made no handle")?; Ok(SharedTexture { resource, - handle, + device: self.device.raw().addr(), format, size: (width, height), life: Arc::new(()), @@ -849,6 +852,134 @@ pub(super) fn video_memory_used() -> Result<[u64; 2], String> { Ok(used) } +/// What Windows charges this process on its GPUs, in bytes: the "GPU Process Memory" counters' +/// Shared Usage and Dedicated Usage of the process's instances (one an adapter, named +/// `pid__luid_...`), summed, read once. It counts what an open of a texture's NT handle left +/// charged, which DXGI's `QueryVideoMemoryInfo` does not (module doc). Tests only. +#[cfg(test)] +pub(super) fn process_gpu_memory() -> Result { + /// `PDH_FMT_COUNTERVALUE_ITEM_W` read as `PDH_FMT_LARGE`: the instance's name, then + /// `PDH_FMT_COUNTERVALUE`'s status and its value. + #[repr(C)] + struct Item { + name: *const u16, + status: u32, + value: i64, + } + type OpenQuery = unsafe extern "system" fn(*const u16, usize, *mut *mut c_void) -> u32; + type AddCounter = + unsafe extern "system" fn(*mut c_void, *const u16, usize, *mut *mut c_void) -> u32; + type Collect = unsafe extern "system" fn(*mut c_void) -> u32; + type CounterArray = + unsafe extern "system" fn(*mut c_void, u32, *mut u32, *mut u32, *mut Item) -> u32; + type CloseQuery = unsafe extern "system" fn(*mut c_void) -> u32; + const PDH_FMT_LARGE: u32 = 0x400; + const PDH_MORE_DATA: u32 = 0x8000_07d2; + const COUNTERS: [&str; 2] = [ + "\\GPU Process Memory(*)\\Shared Usage", + "\\GPU Process Memory(*)\\Dedicated Usage", + ]; + let wide = |text: &str| -> Vec { text.encode_utf16().chain([0]).collect() }; + let function = |name: &CStr| system_function("pdh.dll", name); + // SAFETY: each function is pdh.dll's of that name (pdh.h), as the type says. + let (open, add, collect, array, close) = unsafe { + ( + std::mem::transmute::, OpenQuery>(function(c"PdhOpenQueryW")?), + std::mem::transmute::, AddCounter>(function(c"PdhAddEnglishCounterW")?), + std::mem::transmute::, Collect>(function(c"PdhCollectQueryData")?), + std::mem::transmute::, CounterArray>(function( + c"PdhGetFormattedCounterArrayW", + )?), + std::mem::transmute::, CloseQuery>(function(c"PdhCloseQuery")?), + ) + }; + let failed = |what: &str, status: u32| format!("{what} failed: {status:#010x}"); + let mut query = null_mut(); + // SAFETY: no data source (the live counters), and where to write the query. + let status = unsafe { open(null(), 0, &mut query) }; + if status != 0 { + return Err(failed("PdhOpenQueryW", status)); + } + let prefix = format!("pid_{}_", std::process::id()); + let read = || -> Result { + let mut counters = [null_mut(); 2]; + for (path, counter) in COUNTERS.iter().zip(&mut counters) { + let path = wide(path); + // SAFETY: the query is open, the path NUL-terminated. + let status = unsafe { add(query, path.as_ptr(), 0, counter) }; + if status != 0 { + return Err(failed("PdhAddEnglishCounterW", status)); + } + } + // SAFETY: the query is open. + let status = unsafe { collect(query) }; + if status != 0 { + return Err(failed("PdhCollectQueryData", status)); + } + let mut bytes = 0u64; + for counter in counters { + let (mut size, mut count) = (0u32, 0u32); + // SAFETY: a null buffer of no size asks for the size. + let status = + unsafe { array(counter, PDH_FMT_LARGE, &mut size, &mut count, null_mut()) }; + if status != PDH_MORE_DATA { + return Err(failed("PdhGetFormattedCounterArrayW", status)); + } + let mut items: Vec = + Vec::with_capacity(usize::try_from(size).unwrap_or(0) / size_of::() + 1); + // SAFETY: the buffer holds `size` bytes, aligned for the items, which the call writes + // with the names they point at after them. + let status = unsafe { + array(counter, PDH_FMT_LARGE, &mut size, &mut count, items.as_mut_ptr()) + }; + if status != 0 { + return Err(failed("PdhGetFormattedCounterArrayW", status)); + } + // SAFETY: the call wrote `count` items. + unsafe { items.set_len(usize::try_from(count).unwrap_or(0)) }; + for item in &items { + // SAFETY: each name is NUL-terminated UTF-16 in the buffer, which lives. + let name = unsafe { + let length = (0..).take_while(|&i| *item.name.add(i) != 0).count(); + String::from_utf16_lossy(std::slice::from_raw_parts(item.name, length)) + }; + if item.status == 0 && name.starts_with(&prefix) { + bytes += u64::try_from(item.value).unwrap_or(0); + } + } + } + Ok(bytes) + }; + let bytes = read(); + // SAFETY: the query is open, and closed once. + unsafe { close(query) }; + bytes +} + +/// [`process_gpu_memory`] once it has moved by less than 1 MiB over its last 2 s, read every +/// 250 ms, or as it is 30 s on. Tests only. +#[cfg(test)] +pub(super) fn process_gpu_memory_settled() -> u64 { + use crate::core::runtime::{Runtime as _, StdRuntime}; + // The tests' clock: std's, which the library does not read. + let clock = StdRuntime; + let start = clock.now(); + let mut reads = std::collections::VecDeque::new(); + loop { + let bytes = process_gpu_memory().expect("the GPU Process Memory counters"); + reads.push_back(bytes); + if reads.len() > 8 { + reads.pop_front(); + } + let (low, high) = (reads.iter().min(), reads.iter().max()); + let settled = reads.len() == 8 && high.zip(low).is_some_and(|(h, l)| h - l < 1 << 20); + if settled || clock.elapsed_since(start) >= Duration::from_secs(30) { + return bytes; + } + std::thread::sleep(Duration::from_millis(250)); + } +} + /// The device of the display opened on `luid`, made at its first use and kept; `Err` with why /// where none is made, for good. pub(crate) fn device_of( diff --git a/crates/reims-vgpu-video/src/vaapi/va/display.rs b/crates/reims-vgpu-video/src/vaapi/va/display.rs index f979482d8..daa1f36fa 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/display.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/display.rs @@ -275,7 +275,9 @@ impl Display { /// adapter the driver picks, for the examples. No import check runs: /// Windows makes no dma-buf, so the driver is lent no import /// ([`Display::import_writes`] says so) and frames come back through - /// images. + /// images. `Err` where the driver takes no Direct3D 12 resource as a + /// decode's surface, the one way a pool hands it its textures + /// (`super::surface::takes_resources`). #[cfg(windows)] pub fn open_adapter(luid: Option<[u8; 8]>, runtime: Arc) -> Result { let Some(step) = runtime.exit_step() else { @@ -296,7 +298,9 @@ impl Display { Some(luid) => format!("the DXGI adapter of LUID {:#x}", u64::from_le_bytes(luid)), None => "the DXGI adapter the driver picks".to_owned(), }; - Self::initialise(raw, name, None, luid, runtime, step) + let display = Self::initialise(raw, name, None, luid, runtime, step)?; + super::surface::takes_resources(&display)?; + Ok(display) } /// The Direct3D 12 device on the display's adapter, which its pools diff --git a/crates/reims-vgpu-video/src/vaapi/va/ffi.rs b/crates/reims-vgpu-video/src/vaapi/va/ffi.rs index ca239d9ef..9d70c4ff1 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/ffi.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/ffi.rs @@ -105,11 +105,11 @@ pub(crate) const VA_SURFACE_ATTRIB_SETTABLE: u32 = 0x2; /// `VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2` (va_drmcommon.h): a surface /// over dma-bufs, described by a [`VADRMPRIMESurfaceDescriptor`]. pub(crate) const VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2: u32 = 0x4000_0000; -/// `VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE` (va_win32.h): a surface imported -/// from the NT handle of a Direct3D 12 resource, which the external buffer -/// descriptor attribute points at (an array of one handle a surface). +/// `VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE` (va_win32.h): a surface over +/// a Direct3D 12 resource, which the external buffer descriptor attribute +/// points at (an array of one `ID3D12Resource` pointer a surface). #[cfg(windows)] -pub(crate) const VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE: u32 = 0x0001_0000; +pub(crate) const VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE: u32 = 0x0002_0000; /// `vaExportSurfaceHandle`'s flags (va.h). pub(crate) const VA_EXPORT_SURFACE_READ_ONLY: u32 = 0x0001; pub(crate) const VA_EXPORT_SURFACE_WRITE_ONLY: u32 = 0x0002; diff --git a/crates/reims-vgpu-video/src/vaapi/va/frame.rs b/crates/reims-vgpu-video/src/vaapi/va/frame.rs index bb89c4592..03409088d 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/frame.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/frame.rs @@ -108,10 +108,9 @@ impl Frame { self.surface.export() } - /// The frame's surface as the shared Direct3D 12 texture it is, on Windows, for another - /// device to read its planes by the texture's NT handle (`super::d3d12`); `None` where its - /// pool's surfaces are the driver's own. It reads the decode only once [`Frame::sync`] - /// returned. + /// The frame's surface as the Direct3D 12 texture it is, on Windows, for the plane draws to + /// read its planes through its resource (`super::d3d12`); `None` where its pool's surfaces + /// are the driver's own. It reads the decode only once [`Frame::sync`] returned. #[cfg(windows)] pub fn texture(&self) -> Option> { self.surface.texture() diff --git a/crates/reims-vgpu-video/src/vaapi/va/surface.rs b/crates/reims-vgpu-video/src/vaapi/va/surface.rs index 826c89380..e89f30e4f 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/surface.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/surface.rs @@ -18,11 +18,11 @@ //! ([`end_context`]), is kept until the GPU is done with every one of its //! surfaces. //! -//! On Windows a pool's surfaces are Direct3D 12 textures of ours, made -//! shared, that the driver imports by their NT handles -//! (`shared_surfaces`, `super::d3d12`), so that another device can open -//! what decodes into them; where the adapter's device makes no such texture -//! or the driver imports none, they are the driver's own, as on Linux. +//! On Windows a pool's surfaces are Direct3D 12 textures of ours that the +//! driver takes as their resources (`shared_surfaces`, `super::d3d12`), so +//! that the plane draws can read what decodes into them; where the adapter's +//! device makes no such texture or the driver takes none, they are the +//! driver's own, as on Linux. use std::sync::{Arc, OnceLock}; use std::time::Duration; @@ -454,12 +454,12 @@ fn create_surfaces( Ok(ids) } -/// `count` surfaces of `pool`'s format and size, on Windows: each a shared -/// texture of the display's Direct3D 12 device that the driver imports by its -/// NT handle (`super::d3d12`), so that another device can read what decodes -/// into it; or, where the device makes no such texture or the driver imports -/// none, surfaces of the driver's own, as on Linux, with why at info once a -/// process (`kind`). +/// `count` surfaces of `pool`'s format and size, on Windows: each a texture +/// of the display's Direct3D 12 device that the driver takes as its resource +/// (`super::d3d12`), so that the plane draws can read what decodes into it; +/// or, where the device makes no such texture or the driver takes none, +/// surfaces of the driver's own, as on Linux, with why at info once a process +/// (`kind`). #[cfg(windows)] fn shared_surfaces(pool: &PoolInner, count: usize) -> Result, Error> { let display = &pool.display; @@ -500,8 +500,39 @@ fn shared_surfaces(pool: &PoolInner, count: usize) -> Result Result<(), Error> { + let mut without = None; + for profile in [Profile::H264_HIGH, Profile::HEVC_MAIN] { + let Ok(surfaces) = display.surface_capabilities(profile, Entrypoint::VLD) else { + continue; + }; + let types = surfaces.memory_types.unwrap_or(0); + if types & ffi::VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE != 0 { + return Ok(()); + } + without = Some(types); + } + match without { + Some(types) => Err(Error::Unsupported(format!( + "a Direct3D 12 resource as a decode's surface: its memory types are {types:#010x}, \ + without VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE" + ))), + None => Ok(()), + } +} + +/// A surface of `format`, `width` by `height`, that the driver makes over +/// `texture`'s resource (`VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE`), never +/// by an NT handle, whose import keeps the texture's memory charged for good +/// (`super::d3d12`). #[cfg(windows)] fn import_texture( display: &Display, @@ -510,7 +541,7 @@ fn import_texture( height: u32, texture: &SharedTexture, ) -> Result { - let mut handles = [texture.raw_handle()]; + let mut resources = [texture.raw_resource()]; let mut attributes = [ffi::VASurfaceAttrib::zeroed(); 3]; attributes[0].type_ = ffi::VASurfaceAttribPixelFormat; attributes[0].value.type_ = ffi::VAGenericValueTypeInteger; @@ -518,10 +549,10 @@ fn import_texture( attributes[1].type_ = ffi::VASurfaceAttribMemoryType; attributes[1].value.type_ = ffi::VAGenericValueTypeInteger; attributes[1].value.value.i = - i32::from_ne_bytes(ffi::VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE.to_ne_bytes()); + i32::from_ne_bytes(ffi::VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE.to_ne_bytes()); attributes[2].type_ = ffi::VASurfaceAttribExternalBufferDescriptor; attributes[2].value.type_ = ffi::VAGenericValueTypePointer; - attributes[2].value.value.p = handles.as_mut_ptr().cast(); + attributes[2].value.value.p = resources.as_mut_ptr().cast(); for attribute in &mut attributes { attribute.flags = ffi::VA_SURFACE_ATTRIB_SETTABLE; } @@ -529,8 +560,9 @@ fn import_texture( check( "vaCreateSurfaces", // SAFETY: `id` holds one entry; the attributes are valid, the - // descriptor points at one NT handle, which the call reads and the - // texture keeps open. + // descriptor points at one resource of the adapter's Direct3D 12 + // device, the driver's own (`super::d3d12`), which the texture keeps + // and the surface takes a reference of. display.call(|raw| unsafe { ffi::vaCreateSurfaces( raw, diff --git a/crates/reims-vgpu-video/src/vaapi/va/surface/shared.rs b/crates/reims-vgpu-video/src/vaapi/va/surface/shared.rs index 57b8c1572..3beb7aa9d 100644 --- a/crates/reims-vgpu-video/src/vaapi/va/surface/shared.rs +++ b/crates/reims-vgpu-video/src/vaapi/va/surface/shared.rs @@ -91,3 +91,39 @@ fn a_stand_in_copy_gives_the_surface_what_the_other_holds() { ); } } + +/// A decoder's pool gives back the GPU memory it held once let go, as Windows charges the process +/// for it (`super::super::d3d12`'s module doc): three pools in turn of six surfaces of 3840x2160 +/// NV12 each, lent and let go with the pool, as a session's pool is at its end; the charge after +/// the third is up by less than a tenth of a pool's textures on the charge after the first. A pool +/// whose textures the driver imported by NT handle stayed charged for good, 72 MiB a pool, which +/// this held two of (**measured** on the UHD 630, 2026-11-26). Run on the Windows host, holding +/// its GPU. +#[test] +#[ignore = "needs vaon12 on a Direct3D 12 GPU: run on the Windows host"] +fn pools_let_go_give_back_their_memory() { + const BIG: (u32, u32) = (3840, 2160); + const SURFACES: usize = 6; + let textures = SURFACES as u64 * u64::from(BIG.0 * BIG.1 * 3 / 2); + let display = Display::open_adapter(None, StdRuntime::shared()).expect("a VA display"); + let mut charged = Vec::new(); + for pool in 1..=3 { + { + let made = SurfacePool::new(&display, SurfaceFormat::Nv12, BIG.0, BIG.1, 0) + .expect("a pool"); + let lent: Vec = (0..SURFACES).map(|_| made.get().expect("a surface")).collect(); + assert!( + lent.iter().all(|surface| surface.texture().is_some()), + "pool {pool}: a surface of no texture of ours" + ); + } + charged.push(super::super::d3d12::process_gpu_memory_settled()); + } + let grown = charged[2].saturating_sub(charged[0]); + println!("charged after each pool: {charged:?} bytes"); + assert!( + grown < textures / 10, + "{grown} bytes more charged after the third pool than after the first, of the {textures} \ + that a pool's textures hold" + ); +} diff --git a/docs/lessons.md b/docs/lessons.md index 3304af420..df67e870f 100644 --- a/docs/lessons.md +++ b/docs/lessons.md @@ -53,6 +53,7 @@ one. A new trap found the same way goes here. - A race test can pass on the code it guards when the mutex it races on lets the unlocking thread take it again first, and macOS's default mutex policy does. The bundle's commit decided whether a held create had been refused in a second hold of the held messages, after the post's own hold (until 21e637db25): a create another thread held between the two failed a command buffer with `MTLCommandBufferErrorInternal` in 6 of the 7 walks of a rendering sample made at those trees. Tests whose other thread waited on the mutex through the first hold passed against that code on the default policy, and failed on libpthread's fair-share policy (`PTHREAD_MUTEX_DEFAULT_POLICY=1`), where an unlocked mutex goes to its waiter (**measured** on the M3 Max, macOS 27.0.1, 2026-11-21). A lock-free check before the second hold can still answer without waiting (the held messages' `any` flag, false after a post that took them all), so the protocol test keeps it set with a held destroy the kext refuses. Both tests run in a child of their binary on that policy (`rgfxRunFairShare`, `guest/bundle/tests/rgfx_test_ring.hpp`). How to spot the next one: a race test that passes before its fix as well as after; run it against the old code, in a child on the fair-share policy. - A wait for the work in flight, listed as the wait begins, misses the work that piles up while it lasts. A slab create of the guest bundle that found no room let the process's own slabs go, waited for the slabs other threads were giving back at that moment, and asked once more. Under CPU load the slabs' background thread, at utility QoS, fell behind on its drops: the wait lasted, the slabs other threads let go meanwhile stayed doomed with their memory out of the source, and the second ask was refused while 26 to 52 of them held it (`test_slab_thread`'s 3 MiB takes, **measured** on the M3 Max under Rosetta, 2026-11-21: 1 of 1,000 runs beside 16 busy loops on its 16 CPUs, 6 of 3,828 beside 48 busy loops and 8 dd copies; first seen once beside a 16-job cargo build). A create now goes round again for as long as a round gave memory back (`guest/bundle/src/RgfxSlabs.hpp`, THE FALLBACKS), and `test_slab_take_gives_back_slabs_let_go_while_it_waited` holds the background's releases to show it. How to spot the next one: a refusal or a timeout seen only under load, where a thread of lower priority does the giving back; count what is queued for that thread at the refusal, not only what is in use. - A Foundation file call in the guest bundle makes whatever system calls its release's Foundation picks, and an app's sandbox may kill the process at a call its list leaves out. On macOS 11.7.11 every Safari page that used WebGL lost its WebContent process, its crash report naming the sandbox's kill: the GL store wrote its entries with Foundation's atomic write (`NSDataWritingAtomic`), which on 11 makes its temporary file with `open_dprotected_np`, and WebKit's WebContent profile on 11 and 12 lists the system calls the process may make and kills it (SIGKILL) at any other. 11's list leaves out `open_dprotected_np`, 12's leaves out `setattrlist`, which a file's times can be set with, and from 13 on an unlisted call fails with EPERM instead (**read from** the guests' own profiles: 11.7.11, 12.7.6, 13.7.8, 14.8.9, 15.8.2 and 26.7.2 on x86-64, 27.0.1 on arm64). The bundle's earlier rule, that it import none of open(2)'s family, had sent its writes through Foundation, whose system calls nothing checked. Every Metal process loads the bundle, so its own writes now go through `guest/bundle/src/RgfxFiles.cpp`, plain POSIX calls whose system calls every list read takes, and `guest/bundle/tests/files_tests.mm` runs them, and the store over them, in a child under a sandbox that asks the kernel to kill it at every file call some list leaves out. That sandbox is not the whole check: on 27.0.1 the kernel kills under it at 67 of those 97 calls and lets the other 30, the ones that write (link, chown, utimes, pwrite, unlinkat, setxattr and others), through as if unlisted (**measured**: each call made under the sandbox, arm64 and x86_64). The test's first control, utimes, ran to its end and showed it. So the controls are calls the kernel does kill, and `guest/bundle/tests/bundle_files_check.sh` bans the bundle's imports of the library calls that make the 30. How to spot the next one: a sandboxed app's process dies at the bundle's first write with no fault in the bundle's code and a sandbox kill in its report, or the guest's log has a `deny(1) syscall-unix` line; `guest/bundle/tests/bundle_files_check.sh` fails on a Foundation file-writing selector or a file call that some list leaves out. And a sandbox a test builds proves only the calls its kernel is seen to kill: a control that runs to its end means that call gets through, so make each call of the list under the sandbox once before trusting it. +- What DXGI counts of a process's GPU memory is not what Windows charges it, and a leak can live in the difference. A guest's video export on a Windows host grew the VM's GPU memory a few hundred MiB a session while every holder of ours read flat and dropping the VA display gave back 10 MiB. A program of the platform's calls alone, grown one piece of ours at a time (a kept display, the pool's textures, the plane draws), showed it: an open of a texture's NT handle on the device that made it stays charged for good once everything is released ([docs/video/bugs.md](video/bugs.md), U34), and the VA driver's import by NT handle and the draws' open were two such opens, the same two the VM makes; DXGI's `QueryVideoMemoryInfo` showed none of it. How to spot the next one: a Windows memory figure that grows in the "GPU Process Memory" counters (what Task Manager shows) while DXGI's usage and the reference counts stay flat. Read both, and grow a program of the platform's calls one piece at a time until a piece keeps it. ## The Vulkan platform diff --git a/docs/video/bugs.md b/docs/video/bugs.md index 71af10a78..50cbf283e 100644 --- a/docs/video/bugs.md +++ b/docs/video/bugs.md @@ -136,9 +136,10 @@ Bugs in drivers, libraries and tools that our code or our checks work around. - **U29. radeonsi's decodes write an imported surface only within the bytes its planes as declared span from the luma plane's first byte.** Into an NV12 surface imported from a dma-buf (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`, one object, one layer of two planes, linear) whose chroma plane lies past the end of the luma's rows, a decode answers success and writes nothing past the luma's pitch times the import's height and the chroma's times half of it, from the luma plane's first byte: the chroma plane's last rows are never written, and the luma plane's first row is overwritten (**measured**, a Radeon 780M of Hawk Point and an RX 7900 XTX, Mesa 26.2.6, libva 2.24.1, Linux 7.3.1, 2026-11-08, with the target check's streams and a libva program written from scratch: a 240x144 picture at 256-byte rows lost the chroma's last row at a 256-byte gap, its last two at 512 and its last 16 at 4096, and every byte outside the planes' rows was left as it was; the same with HEVC Main into NV12 and Main 10 into P010). The same surfaces imported taller, so that the declared planes span the chroma plane's rows, the luma plane declared over the gap and into the chroma plane, were written whole; the driver refuses an import whose declared planes run past the dma-buf. Its video processing writes such surfaces at their offsets (the upstream folder's 105). Ours: a target is imported as tall as its planes need to be declared to span its chroma plane's rows (`declared_rows`, `crates/reims-vgpu-video/src/vaapi/va/target.rs`), and the target check's layout has a gap before the chroma plane, as CoreVideo's outputs do. A report, with that program, is written (the upstream folder's 109) and not filed yet. - **U30. iHD's decodes write their render target Y-tiled, whatever its import says.** Into an NV12 or P010 surface imported from a dma-buf (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`, one object, one layer of two planes, `DRM_FORMAT_MOD_LINEAR`), an H.264 or HEVC decode answers success and writes each plane in Y tiles (tiles of 4 KiB, 128 bytes by 32 rows, laid in columns of 16 bytes): H.264's from each plane's offset, and HEVC's from each plane's offset where it is a whole tile in, else the luma plane from the dma-buf's first byte (**measured** on an Iris Xe of an i9-13900H, intel-media-driver 26.3.5, 2026-11-20, with the target check's streams: every luma and chroma byte of the check's first picture at its Y-tile place, the luma plane at 0, 256 and 4096 bytes of the dma-buf; the driver's own surfaces decode the same pictures to every sample). Its decode configs' surfaces take `VA_SURFACE_ATTRIB_MEM_TYPE_VA`, `DRM_PRIME_2` and `DRM_PRIME_3`, its video processing's but for `USER_PTR`, `KERNEL_DRM` and `DRM_PRIME` (0x48000001 against 0x78000005). So the target check fails every kind at its first picture on iHD, and no picture is decoded into memory of ours there. Ours: the arm makes the device's caches dma-bufs where the import check passed a format as well as where the target check passed a kind (`cache_writes`, `crates/reims-vgpu/src/graphics/vaapi.rs`), and iHD's video processing writes each picture, decoded into a surface of the driver's own, into its output's cache's surface (U26). Not reported upstream yet. -- **U31. vaon12 keeps one Direct3D 12 object of every decode session past `vaTerminate`.** A VA decode context that decoded at least one picture leaves one object holding a reference on the adapter's Direct3D 12 device once the context, its surfaces and its config are destroyed and the display is terminated (`vaDestroyContext`, `vaDestroySurfaces`, `vaDestroyConfig`, `vaTerminate`): one for each session, whether it decoded 1, 2, 4, 8 or 16 pictures, each holding about 6.7 to 13 MiB of the adapter's local memory at 3840x2160. A context that decoded nothing, a pool of surfaces alone and a config alone leave none, and the surfaces' kind does not change it: the driver's own, or our shared textures imported by NT handle (**measured** on an Intel UHD Graphics 630, Mesa 26.2.7's vaon12, H.264 High at 3840x2160, 2026-11-20, with the VA crate's tests and probes of our own, the device's references counted by its `AddRef` and `Release` beside ours). The device answered decode tier 2 with no configuration flags for H.264 and HEVC Main and Main 10 at 1920x1080 and 3840x2160 (**measured**, same host and day), so vaon12 keeps its reference pictures as an array of textures and decodes into the target itself; which object stays is not plain from the driver's source (**read**, Mesa 26.2.7's `src/gallium/drivers/d3d12/d3d12_video_dec.cpp` and `src/gallium/frontends/va/`). The device is one an adapter and process, so it and those objects live until the process ends. Nothing in our order of calls reaches it: destroying a session's surfaces before its context instead left the device hung (the next `D3D12CreateDevice` answered `DXGI_ERROR_DEVICE_HUNG`), so ours keeps the context first. The VA crate's `a_display_let_go_after_its_decodes_leaves_no_reference_on_the_adapters_device` and `a_video_let_go_leaves_no_reference_on_the_adapters_device` hold what a driver without it does, and are ignored until one passes them. A report is written (the upstream folder's 126) and not filed yet. +- **U31. vaon12 keeps one Direct3D 12 object of every decode session past `vaTerminate`.** A VA decode context that decoded at least one picture leaves one object holding a reference on the adapter's Direct3D 12 device once the context, its surfaces and its config are destroyed and the display is terminated (`vaDestroyContext`, `vaDestroySurfaces`, `vaDestroyConfig`, `vaTerminate`): one for each session, whether it decoded 1, 2, 4, 8 or 16 pictures, each holding about 6.7 to 13 MiB of the adapter's local memory at 3840x2160. A context that decoded nothing, a pool of surfaces alone and a config alone leave none, and the surfaces' kind does not change it: the driver's own, our textures imported by NT handle, or our textures handed over as their resources (2026-11-26, where the object holds a reference of one of them) (**measured** on an Intel UHD Graphics 630, Mesa 26.2.7's vaon12, H.264 High at 3840x2160, 2026-11-20, with the VA crate's tests and probes of our own, the device's references counted by its `AddRef` and `Release` beside ours). The device answered decode tier 2 with no configuration flags for H.264 and HEVC Main and Main 10 at 1920x1080 and 3840x2160 (**measured**, same host and day), so vaon12 keeps its reference pictures as an array of textures and decodes into the target itself; which object stays is not plain from the driver's source (**read**, Mesa 26.2.7's `src/gallium/drivers/d3d12/d3d12_video_dec.cpp` and `src/gallium/frontends/va/`). The device is one an adapter and process, so it and those objects live until the process ends. Nothing in our order of calls reaches it: destroying a session's surfaces before its context instead left the device hung (the next `D3D12CreateDevice` answered `DXGI_ERROR_DEVICE_HUNG`), so ours keeps the context first. The VA crate's `a_display_let_go_after_its_decodes_leaves_no_reference_on_the_adapters_device` and `a_video_let_go_leaves_no_reference_on_the_adapters_device` hold what a driver without it does, and are ignored until one passes them. A report is written (the upstream folder's 126) and not filed yet. - **U32. iHD codes a frame from a linear encoder input otherwise than from its own surface.** Into an NV12 or P010 surface imported from a dma-buf (`VA_SURFACE_ATTRIB_MEM_TYPE_DRM_PRIME_2`, one object, one layer of two planes, `DRM_FORMAT_MOD_LINEAR`) as an encode's input, the same frame as uploaded into a surface of the driver's own codes to other bytes: H.264's P pictures at 640x360 and smaller, in Constrained Baseline, Main and High, at rows of the coded row's bytes rounded up to 64, 128 or 256 and the chroma plane right after the coded rows; every H.264 picture at 1280x720 and smaller at the driver's own pitch and offsets; every HEVC Main 10 picture, intra ones too; and at a pitch not a multiple of 64, even intra pictures. The driver's own inputs are Y-tiled (`I915_FORMAT_MOD_Y_TILED`), and an import declared Y-tiled in their layout, its bytes in Y tiles, coded as the upload did, byte for byte, at 320x192, 336x208, 640x360, 1280x720 and 1920x1080 in every profile, wherever two uploads coded the same bytes; HEVC Main at 640x360 and 1920x1080 differs from one upload to the next (**measured** with the VA crate's encoder and tests of our own, 6 frames of a moving ramp at a constant QP with no B pictures, an Iris Xe of an i9-13900H, intel-media-driver 26.3.5, libva 2.24.1, 2026-11-20). Ours: an encoder's imported input is laid out as the driver lays out its own where it lays them out in Y tiles (`VideoEncoder::input_layout`, `crates/reims-vgpu-video/src/vaapi/va/encoder.rs`, "Imported inputs"), and the rt platform's fill writes the frame there in Y tiles (`crates/reims-vgpu/src/graphics/vaapi/fill.rs`). A report is drafted (the upstream folder's 127) and not filed: it needs a program of its own first. - **U33. Intel's Direct3D 12 video driver decodes wrong pictures on a device's later video decode queue.** On a Direct3D 12 device where a video decode queue (`D3D12_COMMAND_LIST_TYPE_VIDEO_DECODE`) lives, a decode on a queue made after it answers success and writes wrong pictures. vaon12 makes a video decode queue for each decoder, one a VA context (`d3d12_video_decoder_create_command_objects`, Mesa 26.2.7's `d3d12_video_dec.cpp`), all on the process's one device on the adapter, so of two sessions decoding at once on one display, one decoded wrong pictures, and so did the churn test's short decoders beside its long one (**measured** on an Intel UHD Graphics 630, `igd12dxva64.dll` 31.0.101.2145, Windows 10.0.26300, 2026-11-20). What makes a lone VA decoder's 8 pictures of a 4K H.264 stream wrong, made on the device before it (potluck job m3-max-62074, twice): an idle video decode queue, 8 of 8 wrong; that queue, an `ID3D12VideoDecoder` and an `ID3D12VideoDecoderHeap`, 8 of 8; the decoder, the heap, or both, without the queue, none; nothing, none. FFmpeg 9.0.2's D3D12 decoders (`-hwaccel d3d12va`), each on a queue of its own, show it without Mesa: of two or three decoding at once in one process, one decoded the software decode's frames and the others none, at 3840x2160 and 1920x1080, in H.264 and HEVC; its D3D11 decoders two at once in one process, and two processes at once, decoded every frame right. Ours: while a display's device lives, the device answers every ask for a video decode queue with one queue (`crates/reims-vgpu-video/src/vaapi/va/decode_queue.rs`, [vaapi.md](vaapi.md), "On Windows a device makes one video decode queue"), and `two_decoders_at_once_on_one_display_decode_what_one_alone_does` holds it. Not reported upstream yet: a report, with a program of our own on Direct3D 12 alone, is written (the upstream folder's 128). +- **U34. An open of a Direct3D 12 texture's NT handle on the device that made it stays charged to the process for good.** `ID3D12Device::OpenSharedHandle` of a shared texture's NT handle (`D3D12_HEAP_FLAG_SHARED`, `CreateSharedHandle`) on its own device charges the process's GPU memory with the texture's size, and the charge stays once the open, the texture and the handle are released: each `Release` answers 0, the process's handles stay as many, and the charge outlives the display's `vaTerminate` while the device lives. A pool of six 3840x2160 NV12 textures was charged 72 MiB at each such open, again at each open of the same texture, in the "GPU Process Memory" counters' Shared Usage (Task Manager's), which DXGI's `QueryVideoMemoryInfo` does not count. vaon12's import of an NT handle (`VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE`) is such an open: a pool imported and destroyed, with no config, context or decode, left the same 72 MiB, and so did the plane draws' open of each texture; on the software adapter (WARP) the opens alone left 71.2 MiB a pool, so it is not the card's driver's. Handed to vaon12 as the resource (`VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE`, which its decode surfaces list beside `NTHANDLE`, 0x00030001) and wrapped as the resource by D3D11On12, a session left only U31's 12.7 MiB (**measured** with a program of our own on Direct3D 12, Direct3D 11 and libva alone, decoding a stream it writes itself, on an Intel UHD Graphics 630, driver 31.0.101.2145, Mesa 26.2.7, 2026-11-26, potluck jobs m3-max-75614, m3-max-75629, m3-max-75646 and m3-max-75648). Ours: no pool texture is shared by an NT handle, and a driver whose decode surfaces take no resource is refused at the display's open ([vaapi.md](vaapi.md), "What is here"; `crates/reims-vgpu-video/src/vaapi/va/d3d12.rs`). Not reported upstream yet. ## Untested, or tested by unit tests only diff --git a/docs/video/vaapi.md b/docs/video/vaapi.md index ee21d756d..6f1114f3d 100644 --- a/docs/video/vaapi.md +++ b/docs/video/vaapi.md @@ -47,14 +47,21 @@ over memory of ours, the import check (`Display::import_writes` finds no import), and the staged and mapped copies back. Its frames come back through `vaGetImage`, and its tests that need dma-bufs are Linux's. -On Windows a pool's surfaces are shared Direct3D 12 textures of ours +On Windows a pool's surfaces are Direct3D 12 textures of ours (`src/vaapi/va/d3d12.rs`): each made on the display's adapter, NV12 or -P010, in a shared heap, and imported by the driver through its NT handle -(`VA_SURFACE_ATTRIB_MEM_TYPE_NTHANDLE`), so that the Vulkan platform opens -what decodes into it (`Frame::texture`). `vaon12`'s own surfaces are not -shared, and their export fails (UHD 630, Mesa 26.2.7). Where the adapter's -device makes no such texture or the driver imports none, the pool's surfaces -are the driver's own, and why is logged at info once a process. The +P010, and handed to the driver as its resource +(`VA_SURFACE_ATTRIB_MEM_TYPE_D3D12_RESOURCE`), so that the plane draws +(`src/vaapi/va/d3d11.rs`), which wrap the same resource, read what decodes +into it (`Frame::texture`). Direct3D 12 makes one device a process and +adapter, so the driver's, the draws' and the pools' are one. No pool texture +is shared by an NT handle: an open of one on the device that made it stays +charged to the process for good ([bugs.md](bugs.md), U34). A display whose +driver lists no such memory type for its H.264 or HEVC decodes' surfaces is +refused at its open, as one is where libva does not load. `vaon12`'s own +surfaces cannot be read so, and their export fails (UHD 630, Mesa 26.2.7). +Where the adapter's device makes no texture or the driver takes none, the +pool's surfaces are the driver's own, and why is logged at info once a +process. The Direct3D 12 binding is written by hand: `d3d12.dll` and `dxgi.dll` loaded as libva is, each COM method called through its vtable.