Port NVIDIA Wave32 lowering, smooth movie-plane uploads, XMA audio fixes, and 32GB RAM residency budgets

This commit is contained in:
codec_d committed 2026-11-25 15:31:19 -08:00
1 parent 45e90f4de8
commit 3bcc96f9bb
11 files changed
+463 -110

No files matched your search

+10 -2
View File
@@ -221,7 +221,7 @@ static BAKE_SERVED: AtomicU64 = AtomicU64::new(0);
/// `PS_BakeDecorations_*`), by the first 16 hex digits of their hash as the
/// frame listings print it. They draw into a 256x256 corner of 2048x2048
/// targets and name no texture in a table.
const BAKE_PIXEL_SHADERS: [&str; 4] =
pub(crate) const BAKE_PIXEL_SHADERS: [&str; 4] =
["c0a7fe77b1862e10", "0d1575a396dfe513", "b7cfd8dda91ebb6b", "280967ad158cee0b"];
/// Since the start: early runs of the texture pass, and those of them
@@ -2239,7 +2239,15 @@ impl State {
});
let per_frame = match asked {
Some(mb) => mb << 20,
None => staging_budget_per_frame(memory.map(|[budget, ..]| budget)),
None => {
let base = staging_budget_per_frame(memory.map(|[budget, ..]| budget));
let capped = if crate::residency::limited_host_ram() {
base.min(128 << 20)
} else {
base
};
crate::residency::prefetch_limit(capped, crate::residency::pressured())
}
};
static FRAME: AtomicU64 = AtomicU64::new(u64::MAX);
static SPENT: AtomicU64 = AtomicU64::new(0);
+40 -1
View File
@@ -376,7 +376,7 @@ pub(crate) fn ram_idle_ms(avail_phys: Option<u64>) -> u64 {
(Some(a), Some(b)) => Some(a.min(b)),
(a, b) => a.or(b),
};
ram_idle_for(effective, keep_freed())
ram_idle_for(effective, keep_freed() && !crate::residency::limited_host_ram())
}
fn ram_idle_for(avail_phys: Option<u64>, keep: bool) -> u64 {
@@ -2236,6 +2236,8 @@ enum Step {
/// Brings a texture's staging buffer up to date: once per submission,
/// whichever lists sample it, until a `Copy` or `Run` intervenes.
Texture(std::sync::Arc<crate::texture::Staging>),
/// Reads a CPU-written linear movie plane into a per-list upload buffer.
Plane((usize, usize), Box<dyn Fn() + Send>),
/// A title buffer copy that the list does on the card ([`place`]): what
/// is done on the CPU for it.
Placed(place::Placed),
@@ -2249,6 +2251,8 @@ struct Deferred {
/// Destination, source, bytes.
copies: Vec<Step>,
uploads: Vec<ID3D12Resource>,
/// Standalone upload footprints kept through this list's fence (movie planes).
plane_uploads: Vec<(Chunk, u64)>,
/// The bytes of `uploads` (counted in [`ALIVE`] while they are held).
upload_bytes: u64,
/// Host objects the list's commands name (pipelines, root signatures,
@@ -2313,6 +2317,7 @@ impl Deferred {
impl Drop for Deferred {
fn drop(&mut self) {
give_chunks(std::mem::take(&mut self.plane_uploads));
ALIVE[6].fetch_sub(self.uploads.len() as u64, Ordering::Relaxed);
ALIVE[7].fetch_sub(self.upload_bytes, Ordering::Relaxed);
}
@@ -2991,6 +2996,16 @@ fn blocked_by(written: &[(usize, usize)], runs: &[&HostList], count: bool) -> Op
return Some(WHY_READ);
}
}
&Step::Plane((at, len), _) => {
if touches(written, at, at.saturating_add(len)) {
if count {
LATE_STATS[17].fetch_add(1, Ordering::Relaxed);
#[cfg(feature = "diagnostics")]
blame("a movie plane", written, at, len);
}
return Some(WHY_READ);
}
}
Step::Run(_) => return Some(WHY_RUN),
Step::Placed(p) => match p.waits(written) {
place::Waits::No => {}
@@ -7242,6 +7257,23 @@ impl HostList {
self.deferred().copies.push(Step::Texture(staging));
}
/// A copy source owned exclusively by this list until reset after its
/// last execution. A different list can prepare its movie plane concurrently.
pub(crate) fn plane_upload(
&self,
size: u64,
read: (usize, usize),
fill: impl Fn(usize) + Send + 'static,
) -> Option<ID3D12Resource> {
let chunk = take_chunk(host()?, size)?;
let source = chunk.buffer.clone();
let destination = chunk.data;
let mut deferred = self.deferred();
deferred.plane_uploads.push((chunk, size));
deferred.copies.push(Step::Plane(read, Box::new(move || fill(destination))));
Some(source)
}
/// Runs the list's submission-time steps; refreshes go into `batch`
/// (the title's big buffers, a 174 MB one among them, are read by most
/// lists of a submission, through many ranges). Copies and fills that
@@ -7360,6 +7392,13 @@ impl HostList {
}
continue;
}
Step::Plane((_, len), fill) => {
let started = std::time::Instant::now();
fill();
PREPARING[2].fetch_add(started.elapsed().as_micros() as u64, Ordering::Relaxed);
PREPARING[3].fetch_add(*len as u64, Ordering::Relaxed);
continue;
}
};
us += started.elapsed();
bytes += copied as u64;
@@ -201,6 +201,7 @@ pub(super) fn copied_read(copies: &[Writer], runs: &[&HostList]) -> bool {
.iter()
.any(|w| w.from < *at + *len && *at < w.to && w.shadow.as_ref().is_none_or(|s| !Arc::ptr_eq(s, shadow))),
Step::Host(_, (from, to)) => copies.iter().any(|w| w.from < *to && *from < w.to),
Step::Plane((at, len), _) => copies.iter().any(|w| w.from < at.saturating_add(*len) && *at < w.to),
_ => false,
})
})
@@ -440,6 +441,11 @@ fn does_of(written: &[(usize, usize)], runs: &[&HostList]) -> (Vec<Does>, Vec<(u
asked: touches(written, at, at + len),
}
}
&Step::Plane((at, len), _) => Does::Read {
from: at,
to: at.saturating_add(len),
asked: touches(written, at, at.saturating_add(len)),
},
&Step::Host(_, (from, to)) if from < to => Does::Read { from, to, asked: false },
Step::Refresh(shadow, at, len) => Does::Refresh {
shadow: Arc::as_ptr(shadow) as usize,
+1
View File
@@ -119,6 +119,7 @@ pub(super) fn read_by(runs: &[&HostList], mut ranges: Vec<(usize, usize)>) -> bo
let (at, len) = staging.memory();
touches(&ranges, at, at + len)
}
&Step::Plane((at, len), _) => touches(&ranges, at, at.saturating_add(len)),
Step::Host(_, (from, to)) => touches(&ranges, *from, *to),
Step::Placed(p) => p.from.is_some() && touches(&ranges, p.src, p.src + p.len),
_ => false,
+88 -6
View File
@@ -41,8 +41,63 @@ pub(crate) struct Pending {
/// whether a draw or dispatch has requested it yet.
key: String,
used: AtomicBool,
/// A pass over the screen ([`GraphicsState::screen_pass`]).
/// A pass over the screen ([`GraphicsState::screen_pass`]) or a confirmed
/// opening-scene / bake producer that must never sit behind cold RT shaders.
screen: bool,
/// Confirmed first-scene / bake producer prepared early even on a cold cache.
scene_input: bool,
/// Why this pipeline is intentionally skipped (e.g. RT resolve without BVH).
left_out: Option<&'static str>,
}
fn named(shaders: &[Arc<Shader>], name: &[u8]) -> bool {
shaders
.iter()
.any(|s| s.stage == "compute" && s.container.windows(name.len()).any(|w| w == name))
}
fn left_out(shaders: &[Arc<Shader>]) -> Option<&'static str> {
static SKIP_RT_RESOLVE: OnceLock<bool> = OnceLock::new();
let skip_rt = *SKIP_RT_RESOLVE.get_or_init(|| {
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
if builder {
return false;
}
// Without BVH, ~1,000 CS_RaytracingResolve shaders shade no hits while
// clogging the cold compiler queue; skip unless VICTORY_RT_RESOLVE=1.
std::env::var_os("VICTORY_RT_RESOLVE").is_none_or(|v| v == "0")
});
if skip_rt && named(shaders, b"CS_RaytracingResolve") {
return Some("shades ray-tracing hits without BVH, left out");
}
static SKIP_ACTIVATE_RAYS: OnceLock<bool> = OnceLock::new();
let skip_activate = *SKIP_ACTIVATE_RAYS.get_or_init(|| {
let builder = std::env::var_os("VICTORY_BVH_BUILDER").is_some_and(|v| v == "1");
if builder {
return std::env::var_os("VICTORY_ACTIVATE_RAYS").is_some_and(|v| v == "0");
}
std::env::var_os("VICTORY_ACTIVATE_RAYS").is_none_or(|v| v == "0")
});
if skip_activate && named(shaders, b"CS_ScreenProbes_ActivateRays") {
return Some("ray activation shader without BVH, left out");
}
None
}
/// Confirmed first-scene producers. Prepare these at creation even on a cold
/// launch so cutscene lighting, tiling, and bakes never miss their first frame.
fn scene_input(shaders: &[Arc<Shader>]) -> bool {
shaders.iter().any(|s| {
matches!(
s.hash.as_str(),
"970c4fbb3b017c0e"
| "068c90badc86f1fd"
| "e4a7e088c7780ce8"
| "ebe4e53f031f5249"
| "2cc4c197ee29e291"
| "369cbe906ea72764"
) || crate::draw::BAKE_PIXEL_SHADERS.contains(&s.hash.as_str())
})
}
// SAFETY: D3D12 objects are free-threaded; the graphics state (whose input
@@ -59,8 +114,15 @@ impl Pending {
key.update(s.hash.as_bytes());
}
key.update(graphics.as_ref().map(|g| g.describe()).unwrap_or_default().as_bytes());
let scene_input = scene_input(&shaders);
let screen = (graphics.as_ref().is_some_and(|g| g.screen_pass())
&& shaders.iter().all(|s| s.stage != "mesh"))
|| scene_input;
let left_out = left_out(&shaders);
Pending {
screen: graphics.as_ref().is_some_and(|g| g.screen_pass()),
screen,
scene_input,
left_out,
shaders,
graphics,
queue_state: AtomicU8::new(NOT_QUEUED),
@@ -159,6 +221,9 @@ pub(crate) fn waiting() -> u64 {
/// The host pipeline if it is made (or is made within the frame's budget);
/// queues it on first use.
pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
if p.left_out.is_some() {
return None;
}
// A still-pending pipeline was requested by the title too. Prewarm it
// on the next launch, even if this run never got to use it.
if !p.used.load(Ordering::Relaxed) && !p.used.swap(true, Ordering::Relaxed) {
@@ -174,16 +239,23 @@ pub(crate) fn ready(p: &Arc<Pending>) -> Option<&HostPipeline> {
/// Makes `p` on this thread if it is not made yet (waiting for a worker
/// that is making it); whether it has a host pipeline.
pub(crate) fn now(p: &Arc<Pending>) -> bool {
if p.left_out.is_some() {
return false;
}
p.make();
p.made.get().is_some_and(|made| made.is_some())
}
/// At the title's creation of a pipeline: starts it at once if an earlier
/// run drew with it (during loading, so the world's first frames find it).
/// run drew with it (during loading, so the world's first frames find it),
/// or if it is a confirmed opening-scene / bake producer.
pub(crate) fn early(p: &Arc<Pending>) {
if !p.shaders.is_empty() && super::library::wanted_early(&p.key) {
if p.left_out.is_some() {
return;
}
if !p.shaders.is_empty() && (p.scene_input || super::library::wanted_early(&p.key)) {
super::library::EARLY.fetch_add(1, Ordering::Relaxed);
start(p, EARLY);
start(p, if p.scene_input { REQUESTED } else { EARLY });
}
}
@@ -400,8 +472,13 @@ fn next(screens_only: bool) -> Arc<Pending> {
/// 64), else two thirds of the logical processors, 2 to 16. They run below the
/// title's own threads, and a cold cache queues hundreds at once.
fn worker_count(asked: Option<usize>, processors: usize) -> usize {
worker_count_for(asked, processors, false)
}
fn worker_count_for(asked: Option<usize>, processors: usize, limited_ram: bool) -> usize {
match asked {
Some(n) => n.clamp(1, 64),
None if limited_ram => (processors * 3 / 4).clamp(2, 8),
None => (processors * 2 / 3).clamp(2, 16),
}
}
@@ -411,11 +488,12 @@ fn workers() -> bool {
static RUNNING: OnceLock<bool> = OnceLock::new();
*RUNNING.get_or_init(|| {
let mut running = false;
let workers = worker_count(
let workers = worker_count_for(
std::env::var("VICTORY_PIPELINE_WORKERS")
.ok()
.and_then(|v| v.trim().parse().ok()),
std::thread::available_parallelism().map_or(2, |n| n.get()),
crate::residency::limited_host_ram(),
);
tracing::info!(workers, "pipeline workers");
let screens = if screens_first() { SCREEN_WORKERS } else { 0 };
@@ -488,6 +566,10 @@ mod tests {
assert_eq!(worker_count(None, 64), 16);
assert_eq!(worker_count(Some(0), 24), 1);
assert_eq!(worker_count(Some(20), 24), 20);
assert_eq!(worker_count_for(None, 8, true), 6);
assert_eq!(worker_count_for(None, 16, true), 8);
assert_eq!(worker_count_for(None, 24, true), 8);
assert_eq!(worker_count_for(Some(12), 8, true), 12);
}
/// A first use queues the pipeline and, within the budget, gets the
+144 -72
View File
@@ -519,7 +519,7 @@ pub(crate) fn let_go_idle() {
if map.is_empty() {
return;
}
let idle_ms = crate::host::ram_idle_ms(crate::host::available_physical_ram());
let idle_ms = crate::host::ram_idle_ms(crate::residency::headroom());
// A list that recorded an upload or a check holds the staging until it
// is reset: one only the table holds is named by no list, recorded or
// running.
@@ -788,6 +788,25 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
}
}
}
// The video decoder cycles CPU-written linear plane buffers. Keep a
// dedicated per-list upload buffer through the list's GPU fence so
// concurrent frames never overwrite each other or stall on staging hashes.
if staging.movie_plane() {
let (at, len) = staging.memory();
let footprint = staging.footprints[0].Footprint;
let pitch = footprint.RowPitch as usize;
let bytes = pitch * staging.rows[0] as usize;
let plane = staging.clone();
let Some(source) = list.plane_upload(bytes as u64, (at, len), move |dst| {
fill_plane(&plane.layout, at, len, dst, bytes, pitch);
}) else {
once!("no upload buffer for a CPU-written movie plane");
return;
};
record_upload(list, resource, texture, &staging, &source, 0);
staging.uploaded.store(true, Relaxed);
return;
}
// The host texture has the staging buffer's contents: only the check
// at submission is left, and what it finds changed the next list that
// samples the texture uploads (a frame late where every list of the
@@ -807,77 +826,7 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
};
staging.expected.store(there, Relaxed);
}
const COPY_DEST: u32 = 0x400;
// A texture cut from a block may lie where another did: what the card
// holds of that one is done with before the first upload into this one.
if crate::pool::on() && !staging.uploaded.load(Relaxed) {
let aliasing = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
}),
},
};
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[aliasing]) };
}
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging buffer lives as long as `staging`, which the deferred
// refresh below holds until the list is reset.
for (i, footprint) in staging.footprints.iter().enumerate() {
#[cfg(feature = "diagnostics")]
{
let f = footprint.Footprint;
// SAFETY: live resources.
let (gpu, d) = unsafe { (staging.buffer.GetGPUVirtualAddress(), texture.GetDesc()) };
let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
list.note_read(
|| {
format!(
"texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
d.Width,
d.Height,
d.DepthOrArraySize,
d.Format.0,
d.MipLevels,
staging.footprints.len(),
staging.size,
staging.base + footprint.Offset,
f.Width,
f.Height,
f.Depth,
f.RowPitch
)
},
(gpu + staging.base + footprint.Offset, len),
);
}
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: staging.first - staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(&staging.buffer) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: staging.base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
record_upload(list, resource, texture, &staging, &staging.buffer, staging.base);
// When the list is submitted, its copy takes what the staging buffer
// holds by then: noted before the check below, which sets `dirty`
// again if it detiles (the next list then uploads once more).
@@ -921,6 +870,115 @@ pub(crate) fn upload_from(list: &HostList, resource: This, first: u32) {
});
}
fn record_upload(
list: &HostList,
resource: This,
texture: &ID3D12Resource,
staging: &Staging,
source: &ID3D12Resource,
base: u64,
) {
use std::sync::atomic::Ordering::Relaxed;
const COPY_DEST: u32 = 0x400;
// A texture cut from a block may lie where another did: what the card
// holds of that one is done with before the first upload into this one.
if crate::pool::on() && !staging.uploaded.load(Relaxed) {
let aliasing = D3D12_RESOURCE_BARRIER {
Type: D3D12_RESOURCE_BARRIER_TYPE_ALIASING,
Flags: D3D12_RESOURCE_BARRIER_FLAG_NONE,
Anonymous: D3D12_RESOURCE_BARRIER_0 {
Aliasing: std::mem::ManuallyDrop::new(D3D12_RESOURCE_ALIASING_BARRIER {
pResourceBefore: std::mem::ManuallyDrop::new(None),
// SAFETY: a borrowed pointer the barrier never releases.
pResourceAfter: unsafe { std::mem::transmute_copy(texture) },
}),
},
};
// SAFETY: an open list and a live texture.
unsafe { list.list.ResourceBarrier(&[aliasing]) };
}
crate::list::ensure_state(list, resource, COPY_DEST);
// The staging/plane upload buffer lives until the list is reset.
for (i, footprint) in staging.footprints.iter().enumerate() {
#[cfg(feature = "diagnostics")]
{
let f = footprint.Footprint;
// SAFETY: live resources.
let (gpu, d) = unsafe { (source.GetGPUVirtualAddress(), texture.GetDesc()) };
let len = u64::from(f.RowPitch) * u64::from(staging.rows[i]) * u64::from(f.Depth);
list.note_read(
|| {
format!(
"texture upload {resource:?} ({}x{}x{} f{} mips {}) sub {i} of {} from staging {gpu:#x}+{:#x}: offset {:#x} {}x{}x{} pitch {}",
d.Width,
d.Height,
d.DepthOrArraySize,
d.Format.0,
d.MipLevels,
staging.footprints.len(),
staging.size,
base + footprint.Offset,
f.Width,
f.Height,
f.Depth,
f.RowPitch
)
},
(gpu + base + footprint.Offset, len),
);
}
let to = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: a borrowed pointer the location never releases.
pResource: unsafe { std::mem::transmute_copy(texture) },
Type: D3D12_TEXTURE_COPY_TYPE_SUBRESOURCE_INDEX,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
SubresourceIndex: staging.first - staging.level0 + i as u32,
},
};
let from = D3D12_TEXTURE_COPY_LOCATION {
// SAFETY: as above.
pResource: unsafe { std::mem::transmute_copy(source) },
Type: D3D12_TEXTURE_COPY_TYPE_PLACED_FOOTPRINT,
Anonymous: D3D12_TEXTURE_COPY_LOCATION_0 {
PlacedFootprint: D3D12_PLACED_SUBRESOURCE_FOOTPRINT {
Offset: base + footprint.Offset,
..*footprint
},
},
};
// SAFETY: an open list; both locations name live resources.
unsafe { list.list.CopyTextureRegion(&to, 0, 0, 0, &from, None) };
}
}
fn fill_plane(
layout: &victory_formats::texture::Layout,
at: usize,
len: usize,
dst: usize,
bytes: usize,
pitch: usize,
) {
let _pin = crate::watch::title_memory_reading();
// SAFETY: the list owns this full upload allocation until its GPU work completes.
let out = unsafe { std::slice::from_raw_parts_mut(dst as *mut u8, bytes) };
let mip = &layout.mips[0];
if mip.offset == 0
&& mip.pitch as usize * layout.desc.element_bytes as usize == pitch
&& bytes <= len
&& crate::host::read_into(at as *const _, out)
{
return;
}
with_read(len, |read| {
crate::host::copy_mapped(read.as_mut_ptr(), at as *const u8, len, false);
if let Err(error) = layout.detile(read, 0, 0, out, pitch, bytes) {
out.fill(0);
once!("could not copy the linear plane into the list's upload buffer: {error:?}");
}
});
}
/// Levels on demand: the levels a list claimed for its zeros
/// (`crate::tiles::Tiled::claim`), held by the list's submission-time
/// step. A list that is reset without having been submitted gives the
@@ -1169,6 +1227,20 @@ impl Staging {
preparing[3].fetch_add(read as u64, Relaxed);
}
fn movie_plane(&self) -> bool {
use windows::Win32::Graphics::Dxgi::Common::DXGI_FORMAT_R8_UNORM;
let desc = &self.layout.desc;
!self.on_demand
&& desc.dimension == victory_formats::texture::Dimension::Tex2d
&& desc.swizzle.0 == 0
&& desc.depth == 1
&& desc.mips == 1
&& desc.samples == 1
&& self.footprints.len() == 1
&& self.footprints[0].Offset == 0
&& self.footprints[0].Footprint.Format == DXGI_FORMAT_R8_UNORM
}
/// Returns the bytes of title memory read.
fn refresh_now(&self) -> usize {
let whole = std::time::Instant::now();
+3 -1
View File
@@ -103,7 +103,9 @@ fn claim(resource: This, first: u32, there: u64) -> Option<Taken> {
let way = ON_THEIR_WAY.lock().unwrap_or_else(|e| e.into_inner());
return way.iter().find(|(serial, _)| *serial == copy.serial).map(|(_, job)| Taken::Known(job.clone()));
}
if BYTES.load(Relaxed) >= MOST
let most = if crate::residency::limited_host_ram() { 32 << 20 } else { MOST };
if crate::residency::pressured()
|| BYTES.load(Relaxed) >= most
|| copy.flags() & 0x7 != 0
|| copy.state.load(Relaxed) != 0
|| copy.grown.load(Relaxed)