🐎 Make a video cache's memory at the video's first use of it

In the per-shape form a cache made for the host's video is now a deferred
exportable buffer (an exported block for NVDEC, a dma-buf for VA-API) whose
memory is made where something first reaches it: a decode or an encode whose
buffer is the cache's, or a copy of the caches' through it. Its make on the
guest's SURFACE_PAGES call makes no memory and records no zeros.

The zeros the video's memory needs ahead of a write of the host's video,
which waits for no work of the platform's, are recorded as the video first
uses the memory, on the transfer queue, and the decode's op waits for them as
for the cache's last fill. A cache's planes, whose fill at their make read the
buffer's zeros, copy them from a 1 MiB buffer of zeros made with the surface
for that fill alone. A fill of the pages into a video cache whose memory is
not made goes straight into its shapes, as any deferred cache's does, and a
decode into the buffer then takes the pages into it over the zeros.

What changes for the guest: nothing it reads. Each plane, shape and buffer
holds the same bytes at the same points; a video cache whose pictures all
land in its surface holds no memory of its buffer.
This commit is contained in:
Anees Iqbal committed 2026-11-21 21:03:42 -08:00
1 parent 3b7193d0ab
commit 8b7135e521
8 files changed
+591 -122

No files matched your search

+6 -3
View File
@@ -2163,13 +2163,16 @@ impl<P: Platform> GraphicsDecoder<P> {
sh.unplaced_zeros
);
}
if sh.zero_taken > 0 {
if sh.zero_taken + sh.zero_sourced + sh.video_zeroed > 0 {
log::info!(
target: "reims_vgpu::graphics",
"IOSurface device caches' shapes on zeros: {} took their fill as made ({} \
MiB), their cache's buffer holding no memory and their image the \
platform's cleared one",
sh.zero_taken, sh.zero_taken_bytes >> 20
platform's cleared one; {} filled from the caches' zeros instead of a \
buffer that held none ({} MiB); {} caches for the host's video zeroed \
for it at their memory's make",
sh.zero_taken, sh.zero_taken_bytes >> 20, sh.zero_sourced,
sh.zero_sourced_bytes >> 20, sh.video_zeroed
);
}
if d.straight + d.buffer_refills + d.lacking_named > 0 {
@@ -24,8 +24,10 @@
//! its work reads them, so the host records no zeros of its own; only a cache whose memory is
//! made for the host's video (exportable, or a dma-buf), which the video writes with no work of
//! the platform's, is zeroed on the transfer queue before any use, ahead of such a write
//! ([`SurfaceCaches::zeros_of_new`]). The first thing that reads the cache makes the fill
//! before it reads
//! ([`SurfaceCaches::zeros_of_new`]), at its make, or, where its memory is made at its first
//! use ("Deferred memory"), as the video's use first makes it, the use waiting for that fill
//! as for the cache's last ([`SurfaceCaches::zero_for_video`]). The first thing that reads the
//! cache makes the fill before it reads
//! ([`SurfaceCaches::fill_owed`]): a use a command buffer names, a present, a command buffer of
//! render, compute or blit work in the process that made the first buffer over the block, and
//! a buffer over the block made by any other. So a texture over the surface that a command
@@ -408,11 +410,16 @@
//! download, an early copy, a release's copy, a write's copy into another shape of its plane,
//! and a command buffer that names an object over the buffer itself, the host's video's among
//! them where its picture lands in the buffer: a decode given the planes of the cache's surface
//! ([`exported`]) makes none (`super::GraphicsDecoder::video_planes`). A cache whose memory is
//! not made for the host's video (exportable, or a dma-buf) is made so that the platform makes
//! the buffer's memory at its first use alone
//! ([`exported`]) makes none (`super::GraphicsDecoder::video_planes`). A cache is made so that
//! the platform makes the buffer's memory at its first use alone
//! ([`GpuDevice::new_deferred_buffer_of_length`]), as zeros, as a new cache's are: a cache no
//! such copy reaches holds none. Each copy makes it first ([`Buffer::make_memory`]), a
//! such copy reaches holds none. A cache made for the host's video (exportable, or a dma-buf)
//! is made so too, its memory exported as it is made
//! (`GpuDevice::new_deferred_exportable_buffer_of_length`), and zeroed for the video at the
//! video's first use of it ("Fill", above): a cache whose pictures all land in its surface, and
//! whose shapes take their zeros from zeros of their own (the module doc of [`shapes`],
//! "Zeros") and the pages straight ("Straight fills"), holds none. Each copy makes it first
//! ([`Buffer::make_memory`]), a
//! download's, a release's, an early copy's and a write's copy into another shape's with the
//! caches' lock let go of ([`Caches::make_memory`]), as a cache's buffer is made
//! ([`CacheMaker`]); the others' on the thread of their use. Where the platform refuses the
@@ -430,7 +437,9 @@
//! - **Straight fills.** In the per-shape form a fill of a cache whose buffer holds no memory
//! copies the pages straight into its shapes' images, with nothing copied into the buffer
//! ([`SurfaceCache::fills_straight`]): its pages are a view or copied through pieces, it keeps
//! their layout with no wide home and carries nothing, no texture lies over its buffer as a rule,
//! their layout with no wide home and carries nothing, no texture lies over its buffer as a rule
//! (a cache the host's video writes itself fills so too: a video op that reads or writes its
//! buffer makes its memory and has it take the pages first, at its command buffer's begin),
//! and each shape's rows cross a piece's end only between texels. From the view, a shape's rows
//! go in one GPU copy; from the pieces the host's CPU copied the pages into ("Staged copies"), in
//! a copy for each run of rows that lies in one piece, a row that crosses a piece's end split
@@ -514,6 +523,8 @@ use reims_vgpu_vulkan::core::platform::command::{CommandBuffer, CommandQueue, Co
use reims_vgpu_vulkan::core::platform::device::GpuDevice;
use reims_vgpu_vulkan::core::platform::event::{EventRef, SharedEvent as _};
use reims_vgpu_vulkan::core::platform::os::clock::MonoTime;
#[cfg(unix)]
use reims_vgpu_vulkan::core::platform::resource::SurfaceHandle;
use reims_vgpu_vulkan::core::platform::resource::{Buffer as _, MemoryFor};
use reims_vgpu_vulkan::core::platform::types::NsRange;
use reims_vgpu_vulkan::core::platform::values::{PagesPlane, TextureDesc};
@@ -724,6 +735,12 @@ struct BufferMemory {
/// A command of the guest's named the buffer itself (an object over it,
/// [`SurfaceCaches::over_written`]).
commanded: bool,
/// The memory holds zeros that the host's video may write over, for a cache it writes itself
/// ([`exported::VideoMemory::written_outside`]): made at the cache's make, which zeroed it
/// on the transfer queue where the host's video writes it ([`SurfaceCaches::zeros_of_new`]);
/// zeroed so since ([`SurfaceCaches::zero_for_video`]); or reached by the platform's work, a
/// copy of the caches' through it, which the platform's own zeros are ahead of.
zeroed: bool,
}
/// What made a cache's buffer's memory ([`BufferMemory::by`]).
@@ -744,6 +761,7 @@ impl BufferMemory {
BufferMemory {
counted: made,
by: made.then_some(MadeBy::Make),
zeroed: made,
..BufferMemory::default()
}
}
@@ -766,6 +784,7 @@ impl BufferMemory {
self.seen();
}
self.through += 1;
self.zeroed = true;
}
/// The bytes of `bytes` the buffer holds that a fill, a download or anything else made, where
@@ -977,10 +996,12 @@ impl<P: Platform> SurfaceCache<P> {
/// nothing copied into its buffer (the module doc, "Straight fills"): its buffer holds no
/// memory, its pages are a view or are copied through pieces of `piece` bytes, it keeps the
/// pages' layout with no wide home, no texture lies over the buffer as a rule
/// ([`Self::raw`]), and each shape's rows cross a piece's end only between texels.
/// ([`Self::raw`]; a cache the host's video writes itself is raw for its decodes, which
/// make its memory and have it take the pages first, [`Caches::before`]), and each shape's rows
/// cross a piece's end only between texels.
fn fills_straight(&self, piece: u64) -> bool {
if self.device.memory_made()
|| self.raw
|| (self.raw && !self.surface.written_outside())
|| self.carried.is_some()
|| self.repitched.is_some()
|| self.wide.is_some()
@@ -2344,6 +2365,41 @@ pub(crate) struct SurfaceCaches<P: Platform> {
/// raise the guest's interrupt there. A block's are its key ([`Worker`]).
pub(crate) const INTO_PAGES_THREADS: &str = "reims-vgpu.graphics-into-pages";
/// Fills `length` bytes of `cache` with zeros on `transfer`'s queue, its command buffer owed to
/// `owed_commits` ([`SurfaceCaches::zero`]): the transfer event's value at which it is done,
/// `None` where the platform made no command buffer or encoder for it.
fn zero_on<P: Platform>(
transfer: &mut Transfer<P>,
owed_commits: &mut Vec<P::CommandBuffer>,
cache: &P::Buffer,
length: u64,
) -> RaiseResult<Option<u64>> {
let Some(cb) = transfer.queue.command_buffer(ON)? else {
return Ok(None);
};
let Some(blit) = cb.blit_encoder(ON)? else {
return Ok(None);
};
let range = NsRange::new(0, length);
blit.encode(
ON,
BlitCmd::FillBuffer {
buffer: cache,
range,
value: 0,
},
)?;
blit.encode(ON, BlitCmd::EndEncoding)?;
transfer.signalled += 1;
let value = transfer.signalled;
cb.encode_signal(Some(EventRef::Event(&transfer.event)), value)?;
let fills = Arc::clone(&transfer.fills);
// Told as the platform sees the fill done, with no handler thread woken between.
cb.add_completion_seen_handler(ON, Box::new(move |_: CompletedInfo| fills.finished(value)))?;
owed_commits.push(cb);
Ok(Some(value))
}
/// Makes the memory of `buffer`, a cache's, for `made_for`, where it was made deferred and its
/// memory is not made yet (the module doc, "Deferred memory"): whether it holds its memory, `false`
/// where the platform refused it.
@@ -3162,7 +3218,9 @@ impl<P: Platform> SurfaceCaches<P> {
/// of the platform's reads them (a drawn cache's too, whose planes' pictures land in textures
/// of their own); where the host's video writes it itself (`outside`: exportable, or a
/// dma-buf, [`exported::VideoMemory::written_outside`]), with no work of the platform's, the
/// value at which [`Self::zero`]'s fill is done. `None`, the cache refused, where the
/// value at which [`Self::zero`]'s fill is done. A cache whose memory is not made yet
/// ("Deferred memory") is zeroed so as the host's video first uses its memory
/// ([`Self::zero_for_video`]), its make's value 0. `None`, the cache refused, where the
/// platform made no transfer queue for its copies, or no command buffer or encoder for that
/// fill.
fn zeros_of_new(
@@ -3172,7 +3230,7 @@ impl<P: Platform> SurfaceCaches<P> {
outside: bool,
length: u64,
) -> RaiseResult<Option<u64>> {
if outside {
if outside && cache.memory_made() {
return self.zero(device, cache, length);
}
Ok(self.make_transfer(device)?.then_some(0))
@@ -3193,33 +3251,38 @@ impl<P: Platform> SurfaceCaches<P> {
let Some(transfer) = self.transfer.as_mut() else {
return Ok(None);
};
let Some(cb) = transfer.queue.command_buffer(ON)? else {
return Ok(None);
zero_on::<P>(transfer, &mut self.owed_commits, cache, length)
}
/// The memory of the block at `block`'s cache, made since the cache's make
/// ("Deferred memory") for a use of the host's video, which writes it itself
/// ([`exported::VideoMemory::written_outside`]), filled with zeros on the transfer queue
/// where nothing put zeros or bytes of the platform's work in it yet
/// ([`BufferMemory::zeroed`]), as [`Self::zeros_of_new`] fills a cache whose memory its make
/// made: the platform's own zeros come ahead of its next work, which a write of the host's
/// video does not wait for. The cache's uses wait for the fill as for its last
/// ([`Self::last_fill`]). A command of the guest's that made the memory (`Caches::memory_of`)
/// is no work of the caches', and its writes, were there any, would take these zeros over
/// them; the bundle names no such buffer.
/// Nothing for any other cache, and where the caches have no transfer queue or the platform
/// made no command buffer or encoder for the fill.
pub(super) fn zero_for_video(&mut self, block: u64) -> RaiseResult<()> {
let (Some(transfer), Some(cache)) = (self.transfer.as_mut(), self.by_block.get_mut(&block))
else {
return Ok(());
};
let Some(blit) = cb.blit_encoder(ON)? else {
return Ok(None);
if !cache.surface.written_outside() || !cache.device.memory_made() || cache.memory.zeroed {
return Ok(());
}
let Some(value) =
zero_on::<P>(transfer, &mut self.owed_commits, &cache.device, cache.bytes)?
else {
return Ok(());
};
let range = NsRange::new(0, length);
blit.encode(
ON,
BlitCmd::FillBuffer {
buffer: cache,
range,
value: 0,
},
)?;
blit.encode(ON, BlitCmd::EndEncoding)?;
transfer.signalled += 1;
let value = transfer.signalled;
cb.encode_signal(Some(EventRef::Event(&transfer.event)), value)?;
let fills = Arc::clone(&transfer.fills);
// Told as the platform sees the fill done, with no handler thread woken between.
cb.add_completion_seen_handler(
ON,
Box::new(move |_: CompletedInfo| fills.finished(value)),
)?;
self.owed_commits.push(cb);
Ok(Some(value))
cache.filled_at = cache.filled_at.max(value);
cache.memory.zeroed = true;
self.counts.shapes.video_zeroed += 1;
Ok(())
}
/// The pages of the deferred block at `block`, `named` by a view or by their runs, whose host
@@ -5091,6 +5154,19 @@ impl<P: Platform> SurfaceCaches<P> {
/// ([`Self::take_zeros`]). The transfer event's value at which it is done; `None` where it
/// made none, as where nothing was left to fill.
fn fill_shapes(&mut self, device: &P::Device, block: u64) -> RaiseResult<Option<u64>> {
self.fill_shapes_over(device, block, None)
}
/// [`Self::fill_shapes`], given `zeros`, a buffer of [`shapes::ZEROS_LEN`] bytes of zeros of
/// its own, where one was made for it: a fill that would copy the cache's buffer's zeros
/// ([`SurfaceCache::fills_zeros`]) copies them from there instead, with the buffer's memory
/// left unmade (the module doc of `shapes`, "Zeros"; [`shapes::fill_zeros`]).
pub(super) fn fill_shapes_over(
&mut self,
device: &P::Device,
block: u64,
zeros: Option<&P::Buffer>,
) -> RaiseResult<Option<u64>> {
self.touch_shapes(block);
if self.take_zeros(block) {
return Ok(None);
@@ -5110,8 +5186,13 @@ impl<P: Platform> SurfaceCaches<P> {
let straight = cache.lacks
&& cache.fills_straight(self.spares.piece)
&& !cache.shapes.iter().any(|s| s.dirty && !s.owed);
// A buffer that holds no memory and would fill its shapes with its zeros fills them from
// `zeros`, where given, instead ("Zeros").
let zeroing = zeros.filter(|_| {
!straight && cache.fills_zeros() && shapes::zeros_fit(&cache.shapes, |s| s.owed)
});
let Some(cb) = (transfer.queue.command_buffer(ON)?).filter(|_| {
if straight {
if straight || zeroing.is_some() {
return true;
}
let made = cache.copy_through(MemoryFor::FillShapes);
@@ -5129,6 +5210,11 @@ impl<P: Platform> SurfaceCaches<P> {
reserve.extend(self.left_over.remove(&block).unwrap_or_default());
let owed: &dyn Fn(&shapes::Shape<P::Texture>) -> bool = &|s| s.owed;
let mut filled = || -> RaiseResult<Vec<u64>> {
if let Some(zeros) = zeroing {
let counts = &mut self.counts.shapes;
shapes::fill_zeros::<P>(&cb, zeros, &mut cache.shapes, owed, counts)?;
return Ok(Vec::new());
}
let staging = (timed, &self.spares, &mut reserve);
if straight {
let way = (Way::In, block, Some(owed));
@@ -6223,9 +6309,10 @@ impl CacheMaker {
/// per-shape form, where no texture lies over it, one whose memory the platform makes at its
/// first use ([`GpuDevice::new_deferred_buffer_of_length`], "Deferred memory"); else as any
/// other buffer. An exportable cache places that byte alike
/// (`GpuDevice::new_exportable_buffer_of_length`). With the buffer, the cache's life where
/// its memory was made for the host's video, exportable or a dma-buf
/// ([`SurfaceCache::life`]).
/// (`GpuDevice::new_exportable_buffer_of_length`), and in the per-shape form its memory, and
/// a dma-buf cache's, is made at its first use too, exported as it is made
/// (`GpuDevice::new_deferred_exportable_buffer_of_length`). With the buffer, the cache's life
/// where it was made for the host's video, exportable or a dma-buf ([`SurfaceCache::life`]).
fn make<P: Platform>(
self,
device: &P::Device,
@@ -6267,10 +6354,33 @@ impl CacheMaker {
let two_planes = layout.is_some_and(|planes| planes.len() == 2);
let mut counts = MakerCounts::default();
let life = || Some(MemoryLife::new());
// In the per-shape form the guest's textures over a video cache are views of its shapes'
// images, its planes' in its surface where it takes one, and the buffer's memory, exported
// as the host's video takes it, is made at its first use alone ("Deferred memory").
#[cfg(unix)]
let video_made = |handle| match self.shaped {
true => device.new_deferred_exportable_buffer_of_length(
ON,
length,
STORAGE_PRIVATE,
aligned,
handle,
),
false => match handle {
SurfaceHandle::OpaqueFd => {
device.new_exportable_buffer_of_length(ON, length, STORAGE_PRIVATE, aligned)
}
SurfaceHandle::DmaBuf => device.new_dma_buf_buffer_of_length_padding_unobserved(
ON,
length,
STORAGE_PRIVATE,
aligned,
),
},
};
#[cfg(unix)]
if self.exportable && two_planes {
let made =
device.new_exportable_buffer_of_length(ON, length, STORAGE_PRIVATE, aligned)?;
let made = video_made(SurfaceHandle::OpaqueFd)?;
if let Some(cache) = made {
counts.exportable = true;
counts.aligned = aligned.is_some();
@@ -6280,12 +6390,7 @@ impl CacheMaker {
}
#[cfg(unix)]
if self.dma_buf && two_planes {
let made = device.new_dma_buf_buffer_of_length_padding_unobserved(
ON,
length,
STORAGE_PRIVATE,
aligned,
)?;
let made = video_made(SurfaceHandle::DmaBuf)?;
if let Some(cache) = made {
counts.dma_buf = true;
counts.aligned = aligned.is_some();
@@ -7052,6 +7157,13 @@ impl<P: Platform> Caches<P> {
})
}
/// The memory of the block at `block`'s cache zeroed for a use of the host's video where its
/// first use since the cache's make made it ([`SurfaceCaches::zero_for_video`]); the use waits
/// for it as for the cache's last fill ([`Self::wait_filled`]).
pub(crate) fn zero_for_video(&self, block: u64) -> RaiseResult<()> {
self.lock().zero_for_video(block)
}
/// The identity of the cache of the block at `block` ([`SurfaceCaches::identity`]).
pub(crate) fn identity(&self, block: u64) -> Option<MemoryIdentity> {
self.lock().identity(block)
@@ -7433,21 +7545,27 @@ impl<P: Platform> Caches<P> {
// The caches' buffers its video ops read or write, all but those of a decode that lands
// in its cache's surface, hold their memory before its uses' fills, made with the lock
// let go of, so none of those fills goes straight into the shapes alone, and a buffer
// that lacks the pages takes them (the module doc, "Straight fills").
// that lacks the pages takes them (the module doc, "Straight fills"). The memory of one
// the host's video writes itself is zeroed for it first, ahead of those fills.
let named: Vec<u64> = (reach.named.iter())
.filter(|&&(block, encoded)| {
encoded || !state.decodes_into_surface(block, decoded_of(block))
})
.map(|&(block, _)| block)
.collect();
let unmade: Vec<P::Buffer> = (named.iter())
let (made, unmade): (Vec<u64>, Vec<P::Buffer>) = (named.iter())
.filter_map(|&block| {
state.deferred_buffer(block, MemoryFor::Command, |c| !c.device.memory_made())
let unmade =
state.deferred_buffer(block, MemoryFor::Command, |c| !c.device.memory_made());
unmade.map(|buffer| (block, buffer))
})
.collect();
.unzip();
if !unmade.is_empty() {
state.unlocked(|| self.make_memory(unmade, MemoryFor::Command));
}
for block in made {
state.zero_for_video(block)?;
}
// The pieces the uses' staged fills would make for want of a spare are made with the
// lock let go of, once, and reserved for their blocks (the module doc, "Staged copies").
let fills: Vec<(u64, Way)> = (picked.iter())
@@ -17,11 +17,13 @@
//! (`SurfaceCaches::fill_planes_at_make`), where no command buffer begun and not finished uses
//! the cache and no copy of it waits, as a placed image's fill is made (`shapes`, "Placed
//! images"): the thread that makes the texture encodes and commits the fill and waits for
//! nothing. A decode's begin then owes the planes no fill. The host's video writes them outside
//! the platform's queues, so the decode op waits on its thread for the cache's last fill
//! (`Caches::wait_filled`), which that fill, made ahead of it, has as a rule done by then; every
//! command buffer that uses the cache after it waits for it on the GPU. A busy cache's planes owe
//! their fill to its next use.
//! nothing. Where the cache's buffer holds no memory yet (`super`'s "Deferred memory"), the
//! fill copies the zeros it would read from a buffer of zeros made with the surface for that
//! fill alone, so the buffer's memory stays unmade (`shapes`, "Zeros"). A decode's begin then
//! owes the planes no fill. The host's video writes them outside the platform's queues, so the
//! decode op waits on its thread for the cache's last fill (`Caches::wait_filled`), which that
//! fill, made ahead of it, has as a rule done by then; every command buffer that uses the cache
//! after it waits for it on the GPU. A busy cache's planes owe their fill to its next use.
//!
//! A decode whose luma and chroma textures show the planes whole is given the surface's planes
//! (`Caches::surface_targets`), and its picture lands there, by the hardware or by a copy into
@@ -100,14 +102,14 @@ use reims_vgpu_video::core::device_memory::MemoryLife;
use reims_vgpu_vulkan::core::platform::Handle as _;
use reims_vgpu_vulkan::core::platform::Platform;
use reims_vgpu_vulkan::core::platform::device::GpuDevice as _;
#[cfg(unix)]
use reims_vgpu_vulkan::core::platform::resource::{
Buffer as _, ExportedSurface, SurfaceDesc, SurfaceHandle, SurfaceMemory, SurfacePlaneDesc,
};
#[cfg(windows)]
use reims_vgpu_vulkan::core::platform::resource::{
D3d11PlaneDesc, ImportedSurface, ImportedSurfaceMemory,
};
#[cfg(unix)]
use reims_vgpu_vulkan::core::platform::resource::{
ExportedSurface, SurfaceDesc, SurfaceHandle, SurfaceMemory, SurfacePlaneDesc,
};
use reims_vgpu_vulkan::core::platform::values::PagesPlane;
use reims_vgpu_vulkan::core::raise::refusals;
@@ -122,6 +124,10 @@ use super::super::super::drawn::{DrawnPlanes, DrawnTarget};
use super::super::video::SurfaceTarget;
#[cfg(windows)]
use super::Now;
#[cfg(unix)]
use super::STORAGE_PRIVATE;
#[cfg(unix)]
use super::shapes::ZEROS_LEN;
use super::shapes::{Held, ShapeCounts, ShapeKey, ShapeTable};
#[cfg(windows)]
use super::spares::{SpareCodes, Spares};
@@ -234,6 +240,13 @@ impl<P: Platform> CacheSurface<P> {
self.made.is_some()
}
/// Whether the host's video writes the cache's memory itself
/// ([`VideoMemory::written_outside`]); `false` for a cache not made for it.
pub(super) fn written_outside(&self) -> bool {
self.video
.is_some_and(|(memory, _)| memory.written_outside())
}
/// The plane shapes of the surface to ask where `key`, a shape the cache's `shapes` hold none
/// of, is a plane shape of the cache's surface (module doc), and no shape of either plane is
/// held: with the cache's memory's kind, the bytes of a luma sample and the planes' image
@@ -604,11 +617,12 @@ impl<P: Platform> SurfaceCaches<P> {
impl<P: Platform> SurfaceCaches<P> {
/// The planes just added to the block at `block`'s cache ([`Self::add_planes`]) take their
/// fill from its buffer at once (the module doc), with the cache's other shapes that owe one
/// and its dirty shapes written back first ([`Self::fill_shapes`]), where no command buffer
/// begun and not finished uses the cache and no copy of it waits; else they owe it to the
/// cache's next use, counted ([`ShapeCounts::planes_owed_busy`]). A fill the platform raises
/// at is logged, and the planes owe theirs still.
fn fill_planes_at_make(&mut self, device: &P::Device, block: u64) {
/// and its dirty shapes written back first ([`Self::fill_shapes`]), or from `zeros`, where
/// given, while the buffer holds no memory ([`Self::fill_shapes_over`]), where no command
/// buffer begun and not finished uses the cache and no copy of it waits; else they owe it to
/// the cache's next use, counted ([`ShapeCounts::planes_owed_busy`]). A fill the platform
/// raises at is logged, and the planes owe theirs still.
fn fill_planes_at_make(&mut self, device: &P::Device, block: u64, zeros: Option<&P::Buffer>) {
if self.pending(block, false) > 0 || self.deferring(block) {
self.counts.shapes.planes_owed_busy += 1;
return;
@@ -616,7 +630,7 @@ impl<P: Platform> SurfaceCaches<P> {
let before = self.counts.shapes.plane_fills;
// A refusal of a buffer's memory is a begin's to fail its command buffer on, not this.
let refused = self.memory_refused;
if let Err(raise) = self.fill_shapes(device, block) {
if let Err(raise) = self.fill_shapes_over(device, block, zeros) {
log::warn!(
target: "reims_vgpu::graphics", kind:% = raise;
"the IOSurface block at {block:#x}: the platform raised at its video planes' fill \
@@ -703,14 +717,17 @@ impl<P: Platform> Caches<P> {
/// its image. `None` where the cache takes no surface for `key`, or the platform made none
/// (counted) or made it in its copy form, declined (counted, [`decline`]), or made its
/// description so before, declined unmade (counted, [`unasked`]), for the caller to make the
/// shape's image of its own.
/// shape's image of its own. Where the cache's buffer holds no memory yet, a buffer of zeros
/// is made with the surface for the planes' fill at their make, and let go of after it
/// ([`SurfaceCaches::fill_planes_at_make`]): the planes copy their zeros from it, with the
/// buffer's memory left unmade.
pub(super) fn plane_shape(
&self,
device: &P::Device,
block: u64,
key: &ShapeKey,
) -> Option<Held<P::Texture>> {
let ask = {
let (ask, unmade) = {
let mut state = self.state.lock();
let ask = state.surface_ask(block, key)?;
if state.copy_forms.holds(&ask) {
@@ -719,7 +736,8 @@ impl<P: Platform> Caches<P> {
unasked(block);
return None;
}
ask
let unmade = (state.by_block.get(&block)).is_some_and(|c| !c.device.memory_made());
(ask, unmade)
};
let made = match device.new_exported_surface(ON, &ask.desc()) {
Ok(made) => made.filter(|m| m.planes.len() == 2),
@@ -743,16 +761,31 @@ impl<P: Platform> Caches<P> {
state.copy_forms.note(&ask);
return None;
}
// A refusal leaves the planes to take the buffer's zeros, its memory made for them.
let zeros = match unmade {
true => match device.new_buffer_of_length(ON, ZEROS_LEN, STORAGE_PRIVATE) {
Ok(zeros) => zeros,
Err(raise) => {
log::warn!(
target: "reims_vgpu::graphics", kind:% = raise;
"the IOSurface block at {block:#x}: the platform raised at the zeros of \
its video planes' fill ({raise:?}); they take its buffer's"
);
None
}
},
false => None,
};
// The caches' lock, whose let-go commits the planes' fill (`Locked`).
let (found, gone) = {
let mut state = self.lock();
let added = state.add_planes(block, key, &ask, made);
if added.0.is_some() {
state.fill_planes_at_make(device, block);
state.fill_planes_at_make(device, block, zeros.as_ref());
}
added
};
if let Err(refusal) = refusals::refusing(move || drop(gone)) {
if let Err(refusal) = refusals::refusing(move || drop((gone, zeros))) {
log::warn!(
target: "reims_vgpu::graphics", kind:% = refusal;
"the IOSurface block at {block:#x}'s video planes or shapes past their bound were \
@@ -108,7 +108,12 @@
//! ([`Shape::cleared`]), holds them already: its fill is taken as made, with no copy, and the
//! buffer's memory is left unmade (`SurfaceCaches::fill_shapes`), counted ([`ZERO_TAKEN`]). The
//! guest reads the same zeros either way. A placed image holds its memory's bytes as they were,
//! so it is never taken so: its fill makes the buffer's memory and copies its zeros, as before.
//! so it is never taken so: its fill makes the buffer's memory and copies its zeros, as before;
//! and so does a plane shape's, whose image is its surface's plane, which holds undefined bytes
//! at its make ("Plane shapes"), but where the fill is given a buffer of zeros of its own: then
//! its shapes copy their zeros from that, a run of rows at a time, with the cache's buffer's
//! memory left unmade ([`fill_zeros`], counted in [`ShapeCounts::zero_sourced`]). The planes'
//! fill at their make is given one, made with the surface (`super::exported`).
//! Where the cache would hold zeros so, a new shape is not placed: the platform's own image takes
//! its zeros from the platform's clear, with no block taken for the buffer nor a copy
//! (`super::Caches::shape`), counted ([`UNPLACED_ZEROS`]).
@@ -136,8 +141,9 @@
//! holds undefined bytes at its make, so the planes take their fill from the buffer then, at the
//! texture's make, as a placed image does, where no command buffer begun and not finished uses
//! the cache and no copy of it waits (`super::exported`, counted
//! [`ShapeCounts::planes_filled_at_make`]); a decode's begin then owes none, and its wait for the
//! cache's last fill finds that fill made ahead of it. A busy cache's planes owe theirs to its
//! [`ShapeCounts::planes_filled_at_make`]), from zeros of their own where the buffer holds no
//! memory yet ("Zeros"); a decode's begin then owes none, and its wait for the cache's last fill
//! finds that fill made ahead of it. A busy cache's planes owe theirs to its
//! next use, as any new shape's ([`ShapeCounts::planes_owed_busy`]). A picture that lands over
//! part of the planes alone (a picture smaller than them, or one not written) leaves the rest
//! holding that fill. A CPU lock of the surface never reads the surface's memory beside the
@@ -483,6 +489,13 @@ pub(crate) struct ShapeCounts {
pub(crate) zero_taken: u64,
pub(crate) zero_taken_bytes: u64,
pub(crate) unplaced_zeros: u64,
/// Shapes filled from the caches' zeros instead of their cache's buffer, which held no memory
/// yet, and their bytes ([`fill_zeros`], the module doc, "Zeros"); and caches for the host's
/// video whose memory, made at a first use since their make, was zeroed for it
/// (`SurfaceCaches::zero_for_video`).
pub(crate) zero_sourced: u64,
pub(crate) zero_sourced_bytes: u64,
pub(crate) video_zeroed: u64,
/// Fills of plane shapes from their cache's buffer, and of them those made at the planes'
/// make (the module doc, "Plane shapes"); surfaces whose planes owed their fill past their
/// make, as a command buffer begun and not finished used the cache or a copy of it waited.
@@ -922,8 +935,82 @@ pub(crate) fn fill<P: Platform>(
Ok(())
}
/// `shape` took its fill ([`fill`], [`fill_from`]): it owes none and holds no write the buffer
/// lacks; counted in `counts`.
/// The bytes of zeros a fill of shapes from zeros copies from ([`fill_zeros`]), a buffer of the
/// platform's made for that fill alone (`super::Caches::plane_shape`): 4 rows of the widest a
/// texture takes, 16384 texels of 16 bytes, and 136 of a 3840-wide plane of 2-byte samples.
pub(crate) const ZEROS_LEN: u64 = 1 << 20;
/// The pitch a fill from zeros copies `key`'s rows at ([`fill_zeros`]): its rows' bytes, up to a
/// multiple of 256; `None` past [`ZEROS_LEN`].
fn zeros_pitch(key: &ShapeKey) -> Option<u64> {
let row = key.width.checked_mul(key.texel_bytes)?;
(row.checked_next_multiple_of(256)).filter(|&pitch| pitch > 0 && pitch <= ZEROS_LEN)
}
/// Whether a fill from zeros copies every row of each shape of `table` that `pick` picks
/// ([`fill_zeros`]).
pub(crate) fn zeros_fit<T>(table: &ShapeTable<T>, pick: impl Fn(&Shape<T>) -> bool) -> bool {
(table.iter())
.filter(|s| pick(s))
.all(|s| zeros_pitch(&s.key).is_some())
}
/// Encodes in `cb`, in a blit encoder of its own, a copy of zeros into each shape of `table` that
/// `pick` picks, from `zeros`, [`ZEROS_LEN`] bytes of zeros, in runs of the rows that fit there at
/// [`zeros_pitch`]: the bytes its cache's buffer, which holds no memory yet, reads (the module
/// doc, "Zeros"), with no copy through it. Each shape then owes no fill and holds no write the
/// buffer lacks, as [`fill`] leaves it, counted in `counts` as a fill and as one from zeros.
/// Nothing where it picks none, or the platform made no encoder; the caller made sure each row
/// fits ([`zeros_fit`]), and a shape whose rows do not is left owing its fill.
pub(crate) fn fill_zeros<P: Platform>(
cb: &P::CommandBuffer,
zeros: &P::Buffer,
table: &mut ShapeTable<P::Texture>,
pick: impl Fn(&Shape<P::Texture>) -> bool,
counts: &mut ShapeCounts,
) -> RaiseResult<()> {
const ON: OnFault = OnFault::Return;
if !table.iter().any(&pick) {
return Ok(());
}
let Some(blit) = cb.blit_encoder(ON)? else {
return Ok(());
};
for shape in table.iter_mut().filter(|s| pick(s)) {
let key = shape.key;
let Some(pitch) = zeros_pitch(&key) else {
continue;
};
let rows = ZEROS_LEN / pitch;
let mut y = 0;
while y < key.height {
let run = rows.min(key.height - y);
blit.encode(
ON,
BlitCmd::CopyBufferToTexture {
source_buffer: zeros,
source_offset: 0,
source_bytes_per_row: pitch,
source_bytes_per_image: pitch * run,
source_size: MtlSize::new(key.width, run, 1),
destination_texture: &shape.image,
destination_slice: 0,
destination_level: 0,
destination_origin: MtlOrigin::new(0, y, 0),
},
)?;
y += run;
}
counts.zero_sourced += 1;
counts.zero_sourced_bytes += shape.bytes;
filled(shape, counts);
}
blit.encode(ON, BlitCmd::EndEncoding)?;
Ok(())
}
/// `shape` took its fill ([`fill`], [`fill_from`], [`fill_zeros`]): it owes none and holds no
/// write the buffer lacks; counted in `counts`.
fn filled<T>(shape: &mut Shape<T>, counts: &mut ShapeCounts) {
shape.owed = false;
shape.dirty = false;
@@ -2310,10 +2310,12 @@ mod tests {
fills(calls).into_iter().map(|(b, _, i)| (b, i)).collect()
}
/// A video cache's planes (`surface_cache::exported`) take their fill from the cache's buffer
/// as the first texture over either is made, which makes them: on the transfer queue,
/// committed, with no wait on the CPU, counted as filled at their make. A texture over the
/// other plane fills nothing, and the decode's begin owes the planes no fill
/// A video cache's planes (`surface_cache::exported`) take their fill as the first texture
/// over either is made, which makes them: on the transfer queue, committed, with no wait on
/// the CPU, counted as filled at their make. The cache's buffer holds no memory, so the zeros
/// it would give them come from a buffer of zeros of their own, counted, its memory left
/// unmade (`shapes`, "Zeros"). A texture over the other plane fills nothing, and the decode's
/// begin owes the planes no fill
#[cfg(unix)]
#[test]
fn a_video_caches_planes_take_their_fill_at_their_make() {
@@ -2332,12 +2334,16 @@ mod tests {
assert_eq!(surfaces, 2, "the surface's planes: {sels:?}");
let filled = filled_images(&calls);
assert_eq!(filled.len(), 2, "both planes: {filled:?}");
assert_eq!(filled[0], (cache, luma), "luma's from the buffer");
let zeros = filled[0].0;
assert!(zeros != cache, "from zeros of their own: {filled:?}");
assert_eq!(filled[0], (zeros, luma), "luma's");
let chroma = filled[1].1;
assert!(
filled[1].0 == cache && chroma != luma,
filled[1].0 == zeros && chroma != luma,
"chroma's: {filled:?}"
);
let memory = (r.dec.caches().buffer(BLOCK)).is_some_and(|b| b.memory_made());
assert!(!memory, "the cache's buffer holds no memory");
assert!(
first(&calls, FILL) < first(&calls, "commit"),
"committed: {sels:?}"
@@ -2345,6 +2351,7 @@ mod tests {
assert!(!sels.contains(&"waitUntilCompleted"), "no wait: {sels:?}");
let counts = r.dec.caches().counts().shapes;
assert_eq!((counts.planes_filled_at_make, counts.plane_fills), (2, 2));
assert_eq!(counts.zero_sourced, 2, "both from zeros");
assert_eq!(counts.planes_owed_busy, 0);
assert_eq!(
(counts.surfaces, counts.surfaces_declined),
@@ -2503,13 +2510,14 @@ mod tests {
);
}
/// A picture smaller than its planes leaves the rest of them holding the cache's zeros, as a
/// new IOSurface reads: the cache's buffer took its zeros at its make, and nothing of the
/// pages since, as the decode takes the surface's first fill; the planes took the buffer at
/// their make, after the zeros, on the same queue; the decode op's wait on its thread for
/// the cache's last fill lasts until that fill is done, so the hardware's picture lands over
/// it; and its command buffer leaves the planes owing nothing, so no use after it fills them
/// from the buffer again. The fake holds no texels: the order pins the bytes
/// A picture smaller than its planes leaves the rest of them holding zeros, as a new
/// IOSurface reads: the planes took zeros at their make, copied from a buffer of zeros made
/// with the surface, the cache's buffer holding no memory (`shapes`, "Zeros"), and nothing of
/// the pages since, as the decode takes the surface's first fill; the decode op's wait on its
/// thread for the cache's last fill lasts until that fill is done, so the hardware's picture
/// lands over it; and its command buffer leaves the planes owing nothing, so no use after it
/// fills them again. The cache's buffer's memory is never made. The fake holds no texels: the
/// order pins the bytes
#[cfg(unix)]
#[test]
fn a_picture_smaller_than_its_planes_leaves_the_rest_reading_zeros() {
@@ -2558,15 +2566,22 @@ mod tests {
);
let calls = r.p.call_log().since(0);
let id = |a: &Arg| a.as_obj().map_or(0, |o| o.0);
let zeros = (calls.iter())
.position(|c| c.sel == "fillBuffer:range:value:" && id(&c.args[0]) == cache)
.expect("the cache's zeros at its make");
assert_eq!(filled_images(&calls), [(cache, luma), (cache, chroma)]);
assert!(
first(&calls, FILL) > zeros,
"the planes' fill after the zeros"
assert_eq!(
zeros_into(&calls, cache),
0,
"no zeros of the cache's buffer"
);
let filled = filled_images(&calls);
let zeros = filled.first().map_or(0, |&(from, _)| from);
assert!(zeros != cache, "not the cache's buffer: {filled:?}");
assert_eq!(filled, [(zeros, luma), (zeros, chroma)], "from one buffer");
let zeros_made = (calls.iter())
.filter(|c| c.sel == "newBufferWithLength:options:")
.filter(|c| c.args[0].as_u64() == Some(shapes::ZEROS_LEN))
.count();
assert_eq!(zeros_made, 1, "a buffer of zeros of their own");
let memory = (r.dec.caches().buffer(BLOCK)).is_some_and(|b| b.memory_made());
assert!(!memory, "the cache's buffer holds no memory");
let into_cache: Vec<_> = (copies(&calls).into_iter())
.filter(|&(_, to)| to == cache)
.collect();
@@ -2584,10 +2599,13 @@ mod tests {
/// A video cache's planes made while a command buffer begun and not finished uses the cache
/// owe their fill to its next use, counted, as a placed image's make finds the cache busy
/// (`shapes`, "Placed images"): that use fills them, counted as filled at a later use
/// (`shapes`, "Placed images"): that use fills them, counted as filled at a later use, from
/// the pages straight, as the cache's buffer holds no memory (the module doc of
/// `surface_cache`, "Straight fills")
#[cfg(unix)]
#[test]
fn a_busy_video_caches_planes_owe_their_fill_to_its_next_use() {
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
let mut r = video_shaped();
let cache = cache_id(&r);
let queue = r.device.new_command_queue().unwrap();
@@ -2616,38 +2634,43 @@ mod tests {
use_surfaces(&mut r, 1, 0x101, &[(BLOCK, 0, false)]);
let filled = filled_images(&r.p.call_log().since(mark));
assert_eq!(filled.len(), 2, "both planes at the next use: {filled:?}");
assert!(filled.contains(&(cache, luma)), "{filled:?}");
assert!(
filled
.iter()
.any(|&(from, image)| image == luma && from != cache),
"into the plane from the pages: {filled:?}"
);
let memory = (r.dec.caches().buffer(BLOCK)).is_some_and(|b| b.memory_made());
assert!(!memory, "the buffer's memory not made");
let counts = r.dec.caches().counts().shapes;
assert_eq!((counts.planes_filled_at_make, counts.plane_fills), (0, 2));
}
/// A decode whose textures show a video cache's planes whole, where the cache has its
/// surface, is given the surface's planes, which its picture lands in, and makes no memory of
/// the cache's buffer, which the picture does not touch: the buffer here stands in for a
/// deferred one whose memory is not made, as a Windows video cache's is, its surface over
/// Direct3D 11 textures ("Deferred memory"). A decode whose picture lands in the buffer (its
/// textures not showing the planes whole, or the cache having no surface) makes it, once, as
/// before
/// the cache's buffer, which the picture does not touch ("Deferred memory"). A decode whose
/// picture lands in the buffer (its textures not showing the planes whole, or the cache having
/// no surface) makes it, once, and zeros it for the host's video, which writes it with no
/// work of the platform's, before its wait for the cache's fills (`SurfaceCaches`'s
/// `zero_for_video`)
#[cfg(unix)]
#[test]
fn a_decode_into_a_caches_surface_makes_no_memory_of_its_buffer() {
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
use reims_vgpu_vulkan::core::testkit::objects::Model;
// (the textures show the planes whole, the platform makes the surface): whether the
// picture lands in the surface.
for (whole, surfaces) in [(true, true), (false, true), (true, false)] {
let case = format!("whole {whole}, surfaces {surfaces}");
let mut r = video_shaped();
let cache = cache_id(&r);
r.p.world().give_exported_surfaces(surfaces);
plane_texture_with(&mut r, 21, 10, 0, whole);
plane_texture_with(&mut r, 22, 10, 1, whole);
r.p.world().complete_all(CompleteOn::Caller);
if let Some(buffer) = r.dec.caches().buffer(BLOCK)
&& let Model::Buffer(m) = &mut buffer.state().model
{
m.deferred = Some(false);
}
// The zeros' command buffer completes as it is committed, so the planes' wait for it
// ends.
r.p.world().set_auto_complete(Some(CompleteOn::Thread));
let mark = r.p.call_log().mark();
let (luma, chroma) = r.dec.video_planes(0, 21, 22, true).unwrap();
let apart = whole && surfaces;
@@ -2657,9 +2680,15 @@ mod tests {
"{case}: the surface's planes"
);
drop((luma, chroma));
let made = r.p.call_log().since(mark);
let made = made.iter().filter(|c| c.sel == MAKE_MEMORY).count();
let calls = r.p.call_log().since(mark);
let made = calls.iter().filter(|c| c.sel == MAKE_MEMORY).count();
assert_eq!(made, usize::from(!apart), "{case}: the buffer's memory");
let zeroed = (
zeros_into(&calls, cache),
r.dec.caches().counts().shapes.video_zeroed,
);
let want = (usize::from(!apart), u64::from(!apart));
assert_eq!(zeroed, want, "{case}: the video's zeros");
let memory = r
.dec
.caches()
@@ -2669,6 +2698,193 @@ mod tests {
}
}
/// The fills of the block's video cache's buffer with zeros in `calls`: its cache is `cache`.
#[cfg(unix)]
fn zeros_into(calls: &[Call], cache: u64) -> usize {
let id = |a: &Arg| a.as_obj().map_or(0, |o| o.0);
(calls.iter())
.filter(|c| c.sel == "fillBuffer:range:value:" && id(&c.args[0]) == cache)
.count()
}
/// A cache made for the host's video in the per-shape form is a deferred buffer whose memory
/// is made at its first use, exported then (a dma-buf for VA-API, an exportable buffer for
/// NVDEC), with no zeros at its make (the module doc of `surface_cache`, "Deferred memory")
#[cfg(unix)]
#[test]
fn a_video_cache_in_the_per_shape_form_is_made_deferred() {
use reims_vgpu_graphics::wire::RGFX_SURFACE_PAGES_CACHED;
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
use reims_vgpu_vulkan::core::testkit::impls::device::{
DEFERRED_DMA_BUF_BUFFER, DEFERRED_EXPORTABLE_BUFFER, DMA_BUF_BUFFER, EXPORTABLE_BUFFER,
};
for exportable in [false, true] {
let mut r = rig(16);
let page = r.page;
let _made = take_shapes(&r);
if exportable {
r.dec.set_exportable_caches();
} else {
r.dec.set_dma_buf_caches();
}
let mark = r.p.call_log().mark();
let flags = RGFX_SURFACE_PAGES_CACHED;
let layout = Some(nv12_layout());
assert_eq!(
r.pages_laid_out(BLOCK, 0, &[(1, 4)], 4 * page, flags, layout),
RGFX_STATUS_OK
);
let sels = r.p.call_log().sels_since(mark);
let count = |sel: &str| sels.iter().filter(|&&s| s == sel).count();
let (deferred, whole) = match exportable {
true => (DEFERRED_EXPORTABLE_BUFFER, EXPORTABLE_BUFFER),
false => (DEFERRED_DMA_BUF_BUFFER, DMA_BUF_BUFFER),
};
assert_eq!(
(count(deferred), count(whole)),
(1, 0),
"exportable {exportable}: {sels:?}"
);
assert!(r.dec.caches().identity(BLOCK).is_some(), "given the video");
let memory = r.dec.caches().buffer(BLOCK).map(|b| b.memory_made());
assert_eq!(memory, Some(false), "exportable {exportable}: no memory");
assert!(
!sels.contains(&"fillBuffer:range:value:"),
"no zeros: {sels:?}"
);
}
}
/// A decode whose picture lands in a video cache's buffer, whose memory is not made, makes
/// it as its command buffer begins and fills it with zeros on the transfer queue, as the
/// buffer's make did when it made the memory: the host's video writes the memory itself,
/// ahead of the platform's own zeros of it (`SurfaceCaches::zero_for_video`). The decode's op
/// waits for those zeros, counted; a second decode makes and zeros nothing
#[cfg(unix)]
#[test]
fn a_decode_into_a_video_caches_buffer_makes_its_memory_and_zeros() {
use super::super::surface_cache::Reach;
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
use reims_vgpu_vulkan::core::testkit::impls::resource::MAKE_MEMORY;
let r = video_shaped();
let cache = cache_id(&r);
assert_eq!(
zeros_into(&r.p.call_log().since(0), cache),
0,
"none at its make"
);
let memory = |r: &Rig| (r.dec.caches().buffer(BLOCK)).is_some_and(|b| b.memory_made());
assert!(!memory(&r));
let queue = r.device.new_command_queue().unwrap();
for (round, want) in [(1, 1), (0, 0)].into_iter().enumerate() {
let cb = queue.command_buffer(ON).unwrap().unwrap();
let decode = Reach {
video: true,
decoded: vec![(BLOCK, nv12_planes())],
named: vec![(BLOCK, false)],
..Reach::default()
};
let writes = [RgfxOpSurfaceUse {
flags: RGFX_SURFACE_USE_WRITES,
..reading(BLOCK, 0)[0]
}];
let mark = r.p.call_log().mark();
let (_, uses) = (r.dec.surface_caches)
.before(&r.device, &cb, &writes, &decode)
.unwrap();
let calls = r.p.call_log().since(mark);
let made = calls.iter().filter(|c| c.sel == MAKE_MEMORY).count();
assert_eq!(
(made, zeros_into(&calls, cache)),
want,
"decode {round}: made, zeroed"
);
if round == 0 {
assert!(
r.dec.surface_caches.surface_targets(BLOCK).is_none(),
"no surface: the picture lands in the buffer"
);
let mut short = || true;
let now = || reims_vgpu_vulkan::core::platform::os::clock::MonoTime::from_nanos(0);
assert!(
!r.dec.surface_caches.wait_filled(BLOCK, &mut short, &now),
"the zeros not done: the decode's op waits"
);
assert_eq!(r.dec.caches().counts().shapes.video_fill_waits, 1);
}
r.p.world().complete_all(CompleteOn::Caller);
(r.dec.surface_caches)
.finish(&r.device, 1, None, &cb, uses.unwrap(), || cb.commit(ON))
.unwrap();
r.p.world().complete_all(CompleteOn::Caller);
assert!(memory(&r), "decode {round}: made");
}
assert_eq!(r.dec.caches().counts().shapes.video_zeroed, 1);
}
/// A video cache's buffer that holds no memory takes a fill from the pages straight into its
/// shapes, as any deferred cache's does (the module doc of `surface_cache`, "Straight
/// fills"), its memory left unmade. A decode whose picture lands in the buffer then makes the
/// memory, zeros it, and fills it from the pages over the zeros, all before the decode's
/// command buffer: the buffer the video writes holds the pages, as an eager cache's did
#[cfg(unix)]
#[test]
fn a_video_caches_buffer_takes_the_pages_over_its_zeros_at_a_decode() {
use super::super::surface_cache::Reach;
use reims_vgpu_vulkan::core::platform::resource::Buffer as _;
let mut r = video_shaped();
let cache = cache_id(&r);
r.p.world().give_exported_surfaces(false);
let luma = plane_texture(&mut r, 21, 0);
r.p.world().complete_all(CompleteOn::Caller);
let mark = r.p.call_log().mark();
use_surfaces(&mut r, 1, 0x101, &[(BLOCK, 1, false)]);
r.p.world().complete_all(CompleteOn::Caller);
let calls = r.p.call_log().since(mark);
let memory = |r: &Rig| (r.dec.caches().buffer(BLOCK)).is_some_and(|b| b.memory_made());
assert!(!memory(&r), "the pages' fill went straight");
let filled = filled_images(&calls);
assert!(
filled
.iter()
.any(|&(from, image)| image == luma && from != cache),
"into the shape from the pages: {filled:?}"
);
assert_eq!(zeros_into(&calls, cache), 0);
let queue = r.device.new_command_queue().unwrap();
let cb = queue.command_buffer(ON).unwrap().unwrap();
let decode = Reach {
video: true,
decoded: vec![(BLOCK, nv12_planes())],
named: vec![(BLOCK, false)],
..Reach::default()
};
let writes = [RgfxOpSurfaceUse {
flags: RGFX_SURFACE_USE_WRITES,
..reading(BLOCK, 1)[0]
}];
let mark = r.p.call_log().mark();
let (_, uses) = (r.dec.surface_caches)
.before(&r.device, &cb, &writes, &decode)
.unwrap();
let calls = r.p.call_log().since(mark);
assert!(memory(&r), "made for the decode");
let id = |a: &Arg| a.as_obj().map_or(0, |o| o.0);
let zeros = (calls.iter())
.position(|c| c.sel == "fillBuffer:range:value:" && id(&c.args[0]) == cache)
.expect("the memory's zeros");
let pages = (calls.iter())
.position(|c| c.sel == COPY && id(&c.args[2]) == cache)
.expect("the pages into the buffer");
assert!(zeros < pages, "the pages over the zeros");
(r.dec.surface_caches)
.finish(&r.device, 1, None, &cb, uses.unwrap(), || cb.commit(ON))
.unwrap();
r.p.world().complete_all(CompleteOn::Caller);
assert_eq!(r.dec.caches().counts().shapes.video_zeroed, 1);
}
/// Library 30 and compute pipeline `obj_id` of a function in it.
fn compute_pipeline(r: &mut Rig, obj_id: u64) {
use reims_vgpu_graphics::wire::{
+11 -2
View File
@@ -1079,9 +1079,15 @@ impl<P: Platform> GraphicsDecoder<P> {
decode: bool,
) -> RaiseResult<(VideoPlane<'_, P>, VideoPlane<'_, P>)> {
// Each plane's buffer is noted, and its memory made where the picture lands there, in
// the order a lookup of each plane that made it would take: luma's, then chroma's.
// the order a lookup of each plane that made it would take: luma's, then chroma's. A
// cache's memory made so is zeroed for the host's video, which writes it itself, before
// the waits for the cache's last fill.
let made = |(place, entry, buffer): (PlanePlace, &Entry<P>, &P::Buffer)| {
self.cache_memory(place.buffer_obj_id, entry, buffer)
self.cache_memory(place.buffer_obj_id, entry, buffer)?;
match (entry.over_cache, entry.span) {
(true, Some((block, _))) => self.surface_caches.zero_for_video(block),
_ => Ok(()),
}
};
let luma_plane = self.plane_of(luma_id)?;
self.note_over_cache(luma_plane.1);
@@ -1147,6 +1153,9 @@ impl<P: Platform> GraphicsDecoder<P> {
if landing_apart && !landed_apart {
made(luma_plane)?;
made(chroma_plane)?;
for block in luma_cache.into_iter().chain(chroma_cache) {
self.wait_for_cache(tag, block)?;
}
}
let plane = |place: PlanePlace, buffer, cache: Option<u64>| VideoPlane {
buffer,
+4 -2
View File
@@ -65,8 +65,10 @@ the device info (`GraphicsDevice::with_platform`, in `graphics.rs`):
them: NVDEC by its own GPU
work, where CUDA imports the device's exportable buffers ([nvidia.md](nvidia.md)), the
device's caches of surfaces of two planes (the outputs' NV12 and P010, as the layout a cached
block's `SURFACE_PAGES` carries gives them) then made exportable as they are made, and every
other cache made as any buffer; VA-API by the runtime device's copy
block's `SURFACE_PAGES` carries gives them) then made exportable as their memory is made (in
the per-shape form at its first use, such as a decode that lands in the cache's buffer, so that
a cache whose pictures all land in its surface may hold none), and every other cache made as
any buffer; VA-API by the runtime device's copy
of the decode surface, or the CPU's through the session's staging ([vaapi.md](vaapi.md)).
The guest's video driver then asks its output surfaces cached
(`guest/bundle/src/RgfxMetalDevice+Video.mm`), with their layout, as for any other surface,
+3 -2
View File
@@ -125,8 +125,9 @@ where it is NVIDIA's and CUDA opens it (`graphics/video_choice.rs`).
(a buffer of a 4K picture's bytes made exportable and imported, logged
with the make's time). The caps then ask the guest for cached outputs
(`RGFX_VIDEO_CAPS_OUTPUT_CACHED`), the device makes each cache of a surface
of two planes (NV12, P010) exportable as it makes it, the others as any
buffer, and the picture is copied within the GPU into the cache's
of two planes (NV12, P010) exportable as it makes its memory (in the
per-shape form, at the memory's first use), the others as any buffer, and
the picture is copied within the GPU into the cache's
memory, imported once a cache (`src/nvidia/external.rs`) and let go of as the
cache goes.
- **Into the output's pages**, where its planes lie in pages a device